Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
8b25bf8
feat(render): embed real fonts in a layout's vector PDF (#1815, part 1)
elpidiofilho Nov 12, 2026
12d65d4
fix(render): review round 1 for embedded PDF fonts (#1815)
elpidiofilho Nov 12, 2026
58c6894
test(render): CFF faces embed as CIDFontType0 with the right glyphs (…
elpidiofilho Nov 12, 2026
480642c
fix(engine): refuse an unknown key in layout.export's "pdf" (#1815)
elpidiofilho Nov 12, 2026
9cd5902
docs: attribute the CFF test font (#1815)
elpidiofilho Nov 12, 2026
01e8018
fix(render): name the collection face that draws the text in the noti…
elpidiofilho Nov 12, 2026
c35eff2
Merge origin/main (#1834, layers) into feat/1815-pdf-real-fonts
elpidiofilho Nov 12, 2026
e9728a9
Merge remote-tracking branch 'origin/main' into feat/1815-pdf-real-fonts
elpidiofilho Nov 12, 2026
deee8d6
test(engine): the outlined-faces notice, none, one, two and eleven (#…
elpidiofilho Nov 12, 2026
e4d9b4e
feat(render): a label's halo is text in vector PDFs (#1815, halos)
elpidiofilho Nov 12, 2026
fd6dcd7
Merge remote-tracking branch 'fork/feat/1815-pdf-real-fonts' into fea…
elpidiofilho Nov 12, 2026
1d62ab9
fix(render): a halo of no width draws nothing (#1815, halos)
elpidiofilho Nov 12, 2026
6a8b64c
Merge origin/main (#1828 merged) into feat/1815-pdf-halos
elpidiofilho Nov 13, 2026
5e557ee
fix(render): a subset tag follows its face file (#1815, halos)
elpidiofilho Nov 13, 2026
54d217f
fix(render): an SVG halo copy is hidden from screen readers (#1815, h…
elpidiofilho Nov 13, 2026
88b7d7e
fix(render): the subset tag hashes every byte (#1815, halos)
elpidiofilho Nov 13, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 51 additions & 5 deletions crates/render/src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<f32>,
}

impl Canvas {
Expand All @@ -48,7 +50,7 @@ impl Canvas {
pub fn recording(width: u32, height: u32) -> Option<Canvas> {
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.
Expand Down Expand Up @@ -205,6 +207,7 @@ impl Canvas {
pub fn glyphs(&mut self, mut run: GlyphRun) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Contract gap (confidence: medium, latent). Canvas::halo rejects a width that isn't a positive number, but GlyphRun::halo is a public field, and Canvas::glyphs accepts a run that already carries one. A run built directly with halo: Some(0.0) or a negative width reaches the writers, where the PDF writer (halo.filter(…)) and the SVG writer (run.halo.filter(…)) fall back to an ordinary, unstroked copy of the text in the halo's colour. That is the white-copy artifact the PR says it removes. The check belongs at the source, so the invalid run is dropped here:

Suggested change
pub fn glyphs(&mut self, mut run: GlyphRun) {
pub fn glyphs(&mut self, mut run: GlyphRun) {
if run.halo.is_some_and(|w| !(w.is_finite() && w > 0.0)) {
return;
}
self.keep(|r| {
run.transform = r.ts.pre_concat(run.transform);
run.halo = run.halo.or(r.halo);
r.drawing.glyphs(run);
});
}

A regression test next to a_halo_of_no_width_draws_nothing would cover it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Halo runs are made only through Canvas::halo, which records nothing for a width that isn't a positive number. Both writers also ignore such a width (content.rs and svg/vectors.rs filter w.is_finite() && w > 0).

self.keep(|r| {
run.transform = r.ts.pre_concat(run.transform);
run.halo = run.halo.or(r.halo);
r.drawing.glyphs(run);
});
}
Expand All @@ -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)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug, low (confidence: medium). Canvas::halo doesn't guard width. A halo of width 0, or NaN, is accepted here. In the PDF writer (content.rs, run.halo.filter(|w| … *w > 0.0)) and the SVG writer, such a run is then drawn as an ordinary text run in the halo's colour, which is a white copy of the label under the label. The pixel path draws nothing, and the test comment at canvas.rs:519 says a halo of no width draws nothing. Current callers filter r > 0 before calling, so this is latent, but the contract should hold at the source:

Suggested change
pub fn halo(&mut self, width: f32, f: impl FnOnce(&mut Canvas)) {
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));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 1d62ab9. Canvas::halo now draws nothing when the width isn't a positive number, so the guard is in one place. Before, the PDF and SVG writers dropped the invalid halo but still set the copy as plain text in the halo's colour. New test canvas::tests::a_halo_of_no_width_draws_nothing covers 0, −1, NaN and infinity, which record nothing, and checks that 2.0 still records a halo run.

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.
Expand Down Expand Up @@ -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,
Expand All @@ -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::<String>(), "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::<String>().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.
Expand Down
34 changes: 32 additions & 2 deletions crates/render/src/pdf/content.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<u8>, 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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug, latent (confidence: medium). In outlines mode this branch passes the halo's colour to fill_and_stroke, which calls self.alpha(out, st, 1.0) before filling (content.rs:240). The run's own alpha is dropped here, while the font-mode branch below does honour it (self.alpha(out, st, run.color.alpha())). Both branches should give the same result for the same run. keep_halo always passes an opaque colour, so nothing is visibly wrong today, but a GlyphRun with a translucent halo colour would be drawn opaque in outlines and see-through in fonts. Either apply run.color.alpha() in fill_and_stroke's caller, or assert in a test that the halo colour is opaque.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing is drawn wrong today: keep_halo (text.rs) always sets the copy in an opaque colour, color.with_alpha(255), inside a group at the halo's alpha. A translucent halo run would get its alpha handled if one is ever added.

}
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) {
Expand All @@ -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");
Expand All @@ -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.
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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}");
Expand Down
73 changes: 69 additions & 4 deletions crates/render/src/pdf/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug, low (confidence: low). The tag now covers the name, glyphs and the file's bytes, but not the face's index in the file. embed gets index from drawn_as (line 113), and for a TTC or OTC the same file can hold several faces. Two members of one collection with the same PostScript name and the same glyph ids would share the tag ABCDEF+Name, though they are different font programs, which is what the doc comment says this tag must not do. Passing index into tag and hashing it alongside the length fixes this. Rare, so the priority is low.

Also a nit on cost: the byte-serial FNV pass reads the whole face file on every embed, which for large CJK faces is tens of MB on a path that runs on the interface thread for print. That is probably tens of milliseconds, so it is not worth changing now, but the doc comment should say the cost is linear in the file size.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Faces of one collection differ in PostScript name and glyph ids, both of which the tag hashes. A collision needs two faces of one .ttc with the same name and the same glyphs.

// 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()
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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.
Expand All @@ -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<f32>, 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::<Vec<_>>().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() {
Expand Down
5 changes: 5 additions & 0 deletions crates/render/src/pdf/fonts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Placed> {
Expand Down
35 changes: 33 additions & 2 deletions crates/render/src/svg/vectors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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#"<g aria-label="{}"{}{}>"#, 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| {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug, low (confidence: medium). When k is not positive (a run whose size is zero or negative), the k > 0.0 guard drops the stroke, but the run is still written with aria-hidden and the halo's fill. The result is an unstroked white copy of the text under the label, which is the artifact this PR removes everywhere else, and it breaks the "no width, no halo" contract. The halo should be dropped in that case rather than written as plain fill. Only reachable with a non-positive run size, so the fix is to return early in glyphs when run.halo.is_some() and k <= 0.0.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No recorded run has a size ≤ 0: Drawing::glyphs refuses a run whose size isn't finite and positive (vector.rs, run.size.is_finite() && run.size > 0.0), so the SVG writer never sees one.

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#"<g{label}{}{stroke}{}>"#, 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(),
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -415,6 +423,29 @@ mod tests {
assert!(defs.text.contains(r#"<clipPath id="clip2" clipPathUnits="userSpaceOnUse"><path d="M100 10"#));
}

/// A halo's copy of the text (#1815) is the run stroked as well, rounded, its width in the
/// glyphs' own units so that it is the run's once they are scaled; it is hidden from screen
/// readers, and the text over it keeps its label, so the label is read once.
#[test]
fn a_halo_run_is_stroked() {
let font = crate::text::label_font().unwrap();
let glyphs = vec![Glyph { id: ab_glyph::Font::glyph_id(font, 'H'), x: 0.0, ch: 'H' }];
let upm = ab_glyph::Font::units_per_em(font).unwrap();
let mut d = Drawing::new(40.0, 40.0);
let run = |color, halo| GlyphRun { font, size: 10.0, color, transform: Transform::identity(), glyphs: glyphs.clone(), halo };
d.glyphs(run(Color::WHITE, Some(2.0)));
d.glyphs(run(Color::BLACK, None));
let (_, _, list) = d.finish();
let (mut svg, mut defs) = (String::new(), Defs::default());
items(&mut svg, &mut defs, &list).unwrap();
let width = format!(r#"stroke-width="{}""#, trimmed(2.0 / (10.0 / upm), 4));
assert!(svg.contains(r##"stroke="#ffffff""##) && svg.contains(&width), "{svg}");
assert!(svg.contains(r#"stroke-linejoin="round" stroke-linecap="round""#), "{svg}");
let groups: Vec<&str> = svg.lines().filter(|l| l.starts_with("<g ")).collect();
assert!(groups[0].starts_with(r#"<g aria-hidden="true""#) && !groups[0].contains("aria-label"), "{svg}");
assert!(groups[1].starts_with(r#"<g aria-label="H""#) && !groups[1].contains("stroke"), "{svg}");
}

/// A blended map layer over another, each in a layer (#1815), blends with the one beneath in
/// the SVG as before: a layer's items are written in place, not in an isolated group.
#[test]
Expand Down
Loading
Loading