Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
53 changes: 25 additions & 28 deletions crates/tok-typeset/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
use crate::column_flow::{
ColumnFlowConfig, ColumnGeometry, ColumnParagraphInput, ContinuousColumnPaginator,
};
use crate::font::{FontManager, ShapingSession};
use crate::font::{FontChoice, FontManager, ShapingSession};
use crate::footnote_paginator::{DynamicFootnotePaginator, FootnotePaginatorConfig};
use crate::gematria::GematriaEngine;
use crate::geometry::{
Expand Down Expand Up @@ -680,6 +680,8 @@ impl TypesettingEngine {
let mut meta: Vec<ItemMeta> = Vec::with_capacity(est_items);
let mut word_start: Option<usize> = None;
let mut gap_offset: Option<usize> = None;
let paragraph_family = session.family_of(FontChoice::Primary).map(str::to_string);
let mut span_sessions: HashMap<String, ShapingSession<'_>> = HashMap::new();

let mut push_word = |start: usize, end: usize, gap: Option<usize>| {
if let Some(gap) = gap {
Expand Down Expand Up @@ -788,7 +790,27 @@ impl TypesettingEngine {
.extend(crate::masoretic::convert_opentype_settings(span_features));
}
}
let (mut run, choice) = session.shape_with_features(
// A span asking for another family (or bold) is shaped with that font: the
// glyph ids must belong to the font the run is tagged with, or the PDF draws
// them with the wrong font and the text comes out as garbage.
let requested_family: Option<String> = span_opt
.filter(|sp| sp.format.font_family.is_some() || sp.format.font_weight.is_some())
.and_then(|sp| {
let fam = sp
.format
.font_family
.as_deref()
.or(base_style.map(|s| s.font_family.as_str()))
.or(paragraph_family.as_deref())?;
Some(session.face_for(fam, run_weight))
});
let shaper: &ShapingSession<'_> = match requested_family {
Some(fam) if Some(&fam) != paragraph_family.as_ref() => span_sessions
.entry(fam)
.or_insert_with_key(|fam| session.sibling(fam)),
_ => session,
};
let (mut run, choice) = shaper.shape_with_features(
run_text,
run_font_size,
level % 2 == 1,
Expand All @@ -798,32 +820,7 @@ impl TypesettingEngine {
g.cluster += run_start as u32;
g.y_offset += baseline_shift;
}
let resolved_family_owned: Option<String> = if let Some(sp) = span_opt {
let is_bold_span = sp.format.font_weight.is_some_and(|w| w >= 600);
if let Some(ref fam) = sp.format.font_family {
if is_bold_span
&& !fam.ends_with(" Bold")
&& (fam == "Frank Ruhl Libre" || fam == "David Libre")
{
Some(format!("{} Bold", fam))
} else {
Some(fam.clone())
}
} else if let Some(base_fam) = session.family_of(choice) {
if is_bold_span
&& !base_fam.ends_with(" Bold")
&& (base_fam == "Frank Ruhl Libre" || base_fam == "David Libre")
{
Some(format!("{} Bold", base_fam))
} else {
Some(base_fam.to_string())
}
} else {
None
}
} else {
session.family_of(choice).map(ToString::to_string)
};
let resolved_family_owned = shaper.family_of(choice).map(ToString::to_string);
items.push(LayoutItem::Box {
width: run.total_width_pt,
text: text[run_start..run_end].to_string(),
Expand Down
18 changes: 17 additions & 1 deletion crates/tok-typeset/src/font.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,9 +353,21 @@ pub enum FontChoice {
pub struct ShapingSession<'a> {
primary: Option<(&'a FontData, Face<'a>)>,
fallbacks: Vec<(&'a FontData, Face<'a>)>,
manager: &'a FontManager,
}

impl<'a> ShapingSession<'a> {
/// A session for another family from the same font manager, for runs whose span
/// asks for a different font than the paragraph (or its bold face).
pub fn sibling(&self, font_family: &str) -> ShapingSession<'a> {
self.manager.session(font_family)
}

/// See [`FontManager::face_for`].
pub fn face_for(&self, family: &str, weight: u16) -> String {
self.manager.face_for(family, weight)
}

fn missing_glyphs(face: &Face<'_>, text: &str) -> usize {
text.chars()
.filter(|c| !c.is_whitespace() && !c.is_control())
Expand Down Expand Up @@ -853,7 +865,11 @@ impl FontManager {
}
}
}
ShapingSession { primary, fallbacks }
ShapingSession {
primary,
fallbacks,
manager: self,
}
}

/// Shapes text with the requested font family, automatically falling back for missing glyphs.
Expand Down
87 changes: 87 additions & 0 deletions crates/tok-typeset/tests/span_font_glyphs_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
//! A run is drawn with the font it is tagged with (`LineBox::fonts[font_index]`), so its
//! glyph ids must come from that font. Otherwise the PDF shows garbage (issue #40).

use tok_core::id::FractionalIndex;
use tok_core::model::{DocumentRoot, Flow, FlowType, ParagraphNode, SectionNode};
use tok_core::styles::CharacterFormat;
use tok_core::{FlowId, TextSpan};
use tok_typeset::engine::{TypesettingEngine, TypesettingEngineConfig};

const TEXT: &str = "וכתב רבינו שכך היא ההלכה";

fn typeset_with_span(format: CharacterFormat) -> (TypesettingEngine, Vec<(String, char, u32)>) {
let mut doc = DocumentRoot::new("span fonts");
doc.sections.clear();
let mut sec = SectionNode::new("s", "default");
sec.flows.clear();
let mut flow = Flow::new(FlowId::new("main"), FlowType::Main);
let mut p = ParagraphNode::new(FractionalIndex::initial(), "body", TEXT);
p.spans.push(TextSpan::new(0, TEXT.chars().count(), format));
flow.paragraphs.push(p);
sec.flows.push(flow);
doc.sections.push(sec);

let engine = TypesettingEngine::new(TypesettingEngineConfig::default());
let pages = engine.typeset_document(&doc);
let mut glyphs = Vec::new();
for frame in &pages[0].frames {
for line in &frame.lines {
for g in &line.glyphs {
let Some(ch) = g.character.filter(|c| !c.is_whitespace()) else {
continue;
};
glyphs.push((
line.fonts[usize::from(g.font_index)].clone(),
ch,
g.glyph_id,
));
}
}
}
assert!(!glyphs.is_empty());
(engine, glyphs)
}

fn assert_ids_belong_to_tagged_font(engine: &TypesettingEngine, glyphs: &[(String, char, u32)]) {
for (family, ch, gid) in glyphs {
let font = engine.font_manager.get_font(family).unwrap();
let face = font.shaping_face().unwrap();
let expected = face.glyph_index(*ch).map(|g| u32::from(g.0));
assert_eq!(
expected,
Some(*gid),
"{ch} tagged {family} has a glyph id of another font"
);
}
}

#[test]
fn span_in_another_family_is_shaped_with_that_family() {
let (engine, glyphs) = typeset_with_span(CharacterFormat {
font_family: Some("David Libre".to_string()),
..Default::default()
});
assert!(glyphs.iter().all(|(f, _, _)| f == "David Libre"));
assert_ids_belong_to_tagged_font(&engine, &glyphs);
}

#[test]
fn bold_span_is_shaped_with_the_bold_face() {
let (engine, glyphs) = typeset_with_span(CharacterFormat {
font_weight: Some(700),
..Default::default()
});
assert!(glyphs.iter().all(|(f, _, _)| f == "Frank Ruhl Libre Bold"));
assert_ids_belong_to_tagged_font(&engine, &glyphs);
}

#[test]
fn bold_span_in_a_family_without_bold_keeps_the_regular_face() {
let (engine, glyphs) = typeset_with_span(CharacterFormat {
font_family: Some("David Libre".to_string()),
font_weight: Some(700),
..Default::default()
});
assert!(glyphs.iter().all(|(f, _, _)| f == "David Libre"));
assert_ids_belong_to_tagged_font(&engine, &glyphs);
}
Loading