use crate::dvi::Writer;
use crate::tfm::Tfm;
const SP: f64 = 65536.0;
pub struct Layout {
pub measure: f64,
pub height: f64,
pub leading: f64,
pub margin: f64,
pub size: f64,
}
impl Default for Layout {
fn default() -> Self {
Self {
measure: 469.75,
height: 643.20,
leading: 12.0,
margin: 72.0,
size: 10.0,
}
}
}
pub fn to_dvi(text: &str, font: &Tfm, font_name: &str, layout: &Layout) -> Vec<u8> {
let chain = FontChain {
fonts: vec![Loaded {
tfm: font.clone(),
name: font_name.to_string(),
}],
map: Vec::new(),
};
to_dvi_chain(text, &chain, layout)
}
pub fn to_dvi_chain(text: &str, chain: &FontChain, layout: &Layout) -> Vec<u8> {
let mut w = Writer::new("texrs");
let at = (layout.size * SP) as i32;
for (i, f) in chain.fonts.iter().enumerate() {
w.define_font(i as u32, &f.name, at, f.tfm.checksum, at);
}
let lines = break_lines_chain(text, chain, layout);
let per_page = ((layout.height / layout.leading).floor() as usize).max(1);
for (page, chunk) in lines.chunks(per_page).enumerate() {
let counts = [page as i32 + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0];
w.begin_page(counts);
let mut current = usize::MAX;
let mut baseline = layout.margin + layout.leading;
for line in chunk {
w.push();
w.down((baseline * SP) as i32);
w.right((layout.margin * SP) as i32);
set_line(&mut w, line, chain, layout, &mut current);
w.pop();
baseline += layout.leading;
}
w.end_page();
}
w.finish()
}
fn set_line(w: &mut Writer, line: &str, chain: &FontChain, layout: &Layout, current: &mut usize) {
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\u{1}' {
let mut spec = String::new();
for c in chars.by_ref() {
if c == '\u{2}' {
break;
}
spec.push(c);
}
let parts: Vec<&str> = spec.split(',').collect();
if parts.len() == 3 {
w.special(&format!(
"color push rgb {} {} {}",
parts[0], parts[1], parts[2]
));
}
continue;
}
if ch == '\u{3}' {
w.special("color pop");
continue;
}
if let Some((f, slot)) = chain.resolve(ch) {
if *current != f {
w.font(f as u32);
*current = f;
}
let width = chain.fonts[f]
.tfm
.char(slot)
.map(|m| m.width)
.unwrap_or(0.0);
w.set_char(u32::from(slot), (width * layout.size * SP) as i32);
continue;
}
let Some(text) = FontChain::approximate(ch) else {
continue;
};
if *current != 0 {
w.font(0);
*current = 0;
}
for b in text.bytes() {
let width = chain.fonts[0].tfm.char(b).map(|m| m.width).unwrap_or(0.0);
w.set_char(u32::from(b), (width * layout.size * SP) as i32);
}
}
}
pub fn break_lines(text: &str, font: &Tfm, layout: &Layout) -> Vec<String> {
let chain = FontChain {
fonts: vec![Loaded {
tfm: font.clone(),
name: String::from("cmr10"),
}],
map: Vec::new(),
};
break_lines_chain(text, &chain, layout)
}
pub fn break_lines_chain(text: &str, chain: &FontChain, layout: &Layout) -> Vec<String> {
use rayon::prelude::*;
let paras: Vec<&str> = text.split("\n\n").collect();
paras
.par_iter()
.map(|para| break_paragraph(para, chain, layout))
.reduce(Vec::new, |mut acc, mut more| {
acc.append(&mut more);
acc
})
}
fn break_paragraph(para: &str, chain: &FontChain, layout: &Layout) -> Vec<String> {
let space = chain.width(' ', layout.size);
let mut lines = Vec::new();
let mut line = String::new();
let mut width = 0.0f64;
for word in para.split_whitespace() {
let ww = chain.width_of(word, layout.size);
let need = match line.is_empty() {
true => ww,
false => width + space + ww,
};
if !line.is_empty() && need > layout.measure {
lines.push(std::mem::take(&mut line));
width = ww;
line.push_str(word);
continue;
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
width = need;
}
if !line.is_empty() {
lines.push(line);
}
lines
}
pub fn find_font(name: &str) -> Option<std::path::PathBuf> {
let file = format!("{name}.tfm");
if let Ok(out) = std::process::Command::new("kpsewhich").arg(&file).output() {
if out.status.success() {
let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
if !p.is_empty() && std::path::Path::new(&p).exists() {
return Some(std::path::PathBuf::from(p));
}
}
}
for root in [
"/usr/local/texlive",
"/Library/TeX/texbin/../../texmf-dist",
"/usr/share/texmf-dist",
] {
let hit = std::process::Command::new("find")
.args([root, "-name", &file, "-maxdepth", "8"])
.output()
.ok()
.filter(|o| o.status.success())
.map(|o| {
String::from_utf8_lossy(&o.stdout)
.lines()
.next()
.unwrap_or("")
.to_string()
})
.filter(|p| !p.is_empty());
if let Some(p) = hit {
return Some(std::path::PathBuf::from(p));
}
}
None
}
pub struct Loaded {
pub tfm: Tfm,
pub name: String,
}
pub struct FontChain {
pub fonts: Vec<Loaded>,
map: Vec<(char, usize, u8)>,
}
const CM_SYMBOLS: &[(char, &str, u8)] = &[
('→', "cmsy10", 33),
('←', "cmsy10", 32),
('↔', "cmsy10", 36),
('−', "cmsy10", 0),
('×', "cmsy10", 2),
('÷', "cmsy10", 4),
('±', "cmsy10", 6),
('∪', "cmsy10", 91),
('∩', "cmsy10", 92),
('≤', "cmsy10", 20),
('≥', "cmsy10", 21),
('≠', "cmsy10", 54),
('·', "cmsy10", 1),
('∞', "cmsy10", 49),
('§', "cmsy10", 120),
('¶', "cmsy10", 123),
('†', "cmsy10", 121),
('‡', "cmsy10", 122),
];
const APPROXIMATIONS: &[(char, &str)] = &[
('©', "(c)"),
('®', "(R)"),
('™', "(TM)"),
('—', "---"),
('–', "--"),
('…', "..."),
('─', "-"),
('│', "|"),
('├', "|-"),
('└', "`-"),
('┌', ",-"),
('┐', "-."),
('┘', "-'"),
('┬', "-,-"),
('┴', "-'-"),
('┼', "-+-"),
('•', "*"),
('“', "``"),
('”', "''"),
('‘', "`"),
('’', "'"),
];
impl FontChain {
pub fn load(primary: &str, fallbacks: &[&str]) -> Result<FontChain, String> {
let mut fonts = Vec::new();
let path = find_font(primary).ok_or_else(|| format!("{primary}.tfm not found"))?;
fonts.push(Loaded {
tfm: Tfm::open(&path)?,
name: primary.to_string(),
});
for f in fallbacks {
if let Some(p) = find_font(f) {
if let Ok(tfm) = Tfm::open(&p) {
fonts.push(Loaded {
tfm,
name: (*f).to_string(),
});
}
}
}
let mut map = Vec::new();
for (ch, font_name, slot) in CM_SYMBOLS {
if let Some(i) = fonts.iter().position(|f| f.name == *font_name) {
if fonts[i].tfm.char(*slot).is_some() {
map.push((*ch, i, *slot));
}
}
}
Ok(FontChain { fonts, map })
}
pub fn resolve(&self, ch: char) -> Option<(usize, u8)> {
if ch.is_ascii() && self.fonts[0].tfm.char(ch as u8).is_some() {
return Some((0, ch as u8));
}
self.map
.iter()
.find(|(c, _, _)| *c == ch)
.map(|(_, f, s)| (*f, *s))
}
pub fn approximate(ch: char) -> Option<&'static str> {
APPROXIMATIONS
.iter()
.find(|(c, _)| *c == ch)
.map(|(_, s)| *s)
}
pub fn width(&self, ch: char, size: f64) -> f64 {
if matches!(ch, '\u{1}' | '\u{2}' | '\u{3}') || ch.is_control() {
return 0.0;
}
if let Some((f, slot)) = self.resolve(ch) {
return self.fonts[f].tfm.char(slot).map(|m| m.width).unwrap_or(0.0) * size;
}
if let Some(text) = Self::approximate(ch) {
return self.fonts[0].tfm.width_of(text) * size;
}
0.0
}
pub fn width_of(&self, text: &str, size: f64) -> f64 {
let mut total = 0.0;
let mut in_spec = false;
for ch in text.chars() {
match ch {
'\u{1}' => in_spec = true,
'\u{2}' => in_spec = false,
_ if in_spec => {}
c => total += self.width(c, size),
}
}
total
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FontFile {
pub path: Option<String>,
pub upright: Option<String>,
pub extension: Option<String>,
}
impl FontFile {
pub fn parse(options: &str) -> FontFile {
let mut out = FontFile::default();
for (key, value) in top_level_pairs(options) {
let value = value.trim().trim_matches(|c| c == '{' || c == '}');
match key.trim() {
"Path" => out.path = Some(value.to_string()),
"UprightFont" => out.upright = Some(value.to_string()),
"Extension" => out.extension = Some(value.to_string()),
_ => {}
}
}
out
}
pub fn resolve(&self, near: Option<&std::path::Path>) -> Option<std::path::PathBuf> {
let upright = self.upright.as_deref()?;
let extension = self.extension.as_deref().unwrap_or(".ttf");
let file = format!("{upright}{extension}");
if let Some(path) = &self.path {
let full = std::path::Path::new(path).join(&file);
if full.is_file() {
return Some(full);
}
if let (Some(dir), Some(near)) = (last_component(path), near) {
let beside = near.join(dir).join(&file);
if beside.is_file() {
return Some(beside);
}
}
}
let beside = near?.join(&file);
beside.is_file().then_some(beside)
}
}
fn last_component(path: &str) -> Option<&str> {
path.trim_end_matches('/')
.rsplit('/')
.next()
.filter(|c| !c.is_empty())
}
fn top_level_pairs(options: &str) -> Vec<(&str, &str)> {
let mut out = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
let bytes = options.as_bytes();
for (i, &b) in bytes.iter().enumerate() {
match b {
b'{' | b'[' => depth += 1,
b'}' | b']' => depth = depth.saturating_sub(1),
b',' if depth == 0 => {
if let Some(pair) = split_pair(&options[start..i]) {
out.push(pair);
}
start = i + 1;
}
_ => {}
}
}
if let Some(pair) = split_pair(&options[start..]) {
out.push(pair);
}
out
}
fn split_pair(text: &str) -> Option<(&str, &str)> {
let at = text.find('=')?;
Some((&text[..at], &text[at + 1..]))
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Families {
pub main: Option<String>,
pub main_file: FontFile,
pub sans: Option<String>,
pub mono: Option<String>,
}
pub fn base14_for(family: &str) -> &'static str {
let f = family.to_ascii_lowercase();
let mono = [
"mono",
"courier",
"consolas",
"menlo",
"inconsolata",
"sharetechmono",
"jetbrains",
"fira code",
"source code",
];
if mono.iter().any(|m| f.contains(m)) {
return "Courier";
}
let serif = [
"times",
"serif",
"georgia",
"garamond",
"minion",
"palatino",
"book",
"charter",
"libertine",
"stix",
];
if serif.iter().any(|m| f.contains(m)) {
return "Times-Roman";
}
"Helvetica"
}
pub fn to_pdf(
text: &str,
families: &Families,
layout: &Layout,
page_colour: Option<crate::colour::Rgb>,
near: Option<&std::path::Path>,
) -> Vec<u8> {
use crate::pdf::{document, Font, Page};
let requested = families.main.as_deref();
let embedded = families
.main_file
.resolve(near)
.and_then(|file| embed_file(&file))
.or_else(|| requested.and_then(embed_family));
let main = embedded.clone().unwrap_or_else(|| {
Font::Base14(requested.map(base14_for).unwrap_or("Helvetica").to_string())
});
let embedded_widths = match &main {
Font::TrueType { widths, .. } => Some(widths.clone()),
_ => None,
};
let metrics = find_font("cmr10").and_then(|p| Tfm::open(&p).ok());
let width_of = |word: &str| -> f64 {
if let Some(w) = &embedded_widths {
return word
.chars()
.map(|c| {
let code = c as usize;
let at = code.saturating_sub(32);
let mille = w.get(at).copied().unwrap_or(500);
mille as f64 / 1000.0 * layout.size
})
.sum();
}
match &metrics {
Some(f) => f.width_of(word) * layout.size,
None => word.chars().count() as f64 * layout.size * 0.5,
}
};
let lines = break_lines_measured(text, layout, &width_of);
let per_page = ((layout.height / layout.leading).floor() as usize).max(1);
let mut pages = Vec::new();
for chunk in paginate(&lines, per_page) {
let mut page = Page::letter();
if let Some((r, g, b)) = page_colour {
page.content.push_str(&format!(
"{r} {g} {b} rg\n0 0 {} {} re\nf\n0 0 0 rg\n",
page.width, page.height
));
}
let mut y = layout.height + layout.margin - layout.leading;
for line in chunk {
let mut x = layout.margin;
for (plain, colour) in colour_runs(line) {
if plain.is_empty() {
continue;
}
if let Some((r, g, b)) = &colour {
page.content.push_str(&format!("{r} {g} {b} rg\n"));
}
page.text_in(main.clone(), layout.size, x, y, &plain);
if colour.is_some() {
page.content.push_str("0 g\n");
}
x += width_of(&plain);
}
y -= layout.leading;
}
pages.push(page);
}
document(&pages)
}
fn break_lines_measured(
text: &str,
layout: &Layout,
width_of: &dyn Fn(&str) -> f64,
) -> Vec<String> {
let space = width_of(" ");
let mut lines = Vec::new();
for para in text.split("\n\n") {
for (part_number, part) in para.split(PAGE_BREAK).enumerate() {
if part_number > 0 {
lines.push(PAGE_BREAK.to_string());
}
let mut line = String::new();
let mut width = 0.0f64;
for word in part.split_whitespace() {
let ww = width_of(word);
let need = match line.is_empty() {
true => ww,
false => width + space + ww,
};
if !line.is_empty() && need > layout.measure {
lines.push(std::mem::take(&mut line));
width = ww;
line.push_str(word);
continue;
}
if !line.is_empty() {
line.push(' ');
}
line.push_str(word);
width = need;
}
if !line.is_empty() {
lines.push(line);
}
}
}
lines
}
fn paginate(lines: &[String], per_page: usize) -> Vec<Vec<&str>> {
let mut pages: Vec<Vec<&str>> = Vec::new();
let mut page: Vec<&str> = Vec::new();
for line in lines {
if line.chars().all(|c| c == PAGE_BREAK) && !line.is_empty() {
if !page.is_empty() {
pages.push(std::mem::take(&mut page));
}
continue;
}
if page.len() >= per_page {
pages.push(std::mem::take(&mut page));
}
page.push(line);
}
if !page.is_empty() {
pages.push(page);
}
pages
}
pub const PAGE_BREAK: char = '\u{c}';
type ColourRun = (String, Option<(String, String, String)>);
fn colour_runs(line: &str) -> Vec<ColourRun> {
let mut runs = Vec::new();
let mut current: Option<(String, String, String)> = None;
let mut text = String::new();
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next() {
match ch {
'\u{1}' => {
if !text.is_empty() {
runs.push((std::mem::take(&mut text), current.clone()));
}
let mut spec = String::new();
for c in chars.by_ref() {
if c == '\u{2}' {
break;
}
spec.push(c);
}
let p: Vec<&str> = spec.split(',').collect();
current = match p.len() == 3 {
true => Some((p[0].to_string(), p[1].to_string(), p[2].to_string())),
false => None,
};
}
'\u{3}' => {
if !text.is_empty() {
runs.push((std::mem::take(&mut text), current.clone()));
}
current = None;
}
c => text.push(c),
}
}
if !text.is_empty() {
runs.push((text, current));
}
runs
}
pub fn find_family(family: &str) -> Option<std::path::PathBuf> {
if let Ok(out) = std::process::Command::new("fc-match")
.args(["-f", "%{file}", family])
.output()
{
if out.status.success() {
let p = String::from_utf8_lossy(&out.stdout).trim().to_string();
let path = std::path::Path::new(&p);
if path.exists() && file_matches(path, family) {
return Some(path.to_path_buf());
}
}
}
let wanted = normalise(family);
for dir in [
"/System/Library/Fonts",
"/System/Library/Fonts/Supplemental",
"/Library/Fonts",
"/usr/share/fonts",
"/usr/local/share/fonts",
] {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let ext = path
.extension()
.and_then(|e| e.to_str())
.unwrap_or("")
.to_ascii_lowercase();
if ext != "ttf" && ext != "otf" {
continue;
}
if normalise(&path.file_stem()?.to_string_lossy()).starts_with(&wanted) {
return Some(path);
}
}
}
None
}
fn file_matches(path: &std::path::Path, family: &str) -> bool {
path.file_stem()
.map(|s| normalise(&s.to_string_lossy()).starts_with(&normalise(family)))
.unwrap_or(false)
}
fn normalise(name: &str) -> String {
name.chars()
.filter(|c| c.is_ascii_alphanumeric())
.collect::<String>()
.to_ascii_lowercase()
}
pub fn embed_family(family: &str) -> Option<crate::pdf::Font> {
embed_file(&find_family(family)?)
}
pub fn embed_file(path: &std::path::Path) -> Option<crate::pdf::Font> {
let bytes = std::fs::read(path).ok()?;
let sfnt = crate::sfnt::Sfnt::parse(bytes.clone()).ok()?;
if sfnt.is_cff() {
return None;
}
let head = sfnt.head().ok()?;
let hhea = sfnt.hhea().ok()?;
let cmap = sfnt.cmap().ok()?;
let advances = sfnt.advance_widths().ok()?;
let upem = f64::from(head.units_per_em.max(1));
let scale = |v: f64| (v * 1000.0 / upem).round() as i64;
let mut widths = Vec::with_capacity(224);
for code in 32u32..=255 {
let gid = cmap.get(&code).copied().unwrap_or(0) as usize;
let adv = advances
.get(gid)
.or_else(|| advances.last())
.copied()
.unwrap_or(0);
widths.push(scale(f64::from(adv)));
}
Some(crate::pdf::Font::TrueType {
name: path.file_stem()?.to_string_lossy().replace(' ', ""),
bytes,
widths,
bbox: [
scale(f64::from(head.x_min)),
scale(f64::from(head.y_min)),
scale(f64::from(head.x_max)),
scale(f64::from(head.y_max)),
],
ascent: scale(f64::from(hhea.ascender)),
descent: scale(f64::from(hhea.descender)),
})
}
#[cfg(test)]
mod font_file_tests {
use super::FontFile;
const REAL: &str = "\n Path=/private/tmp/build/scifi2/docs/.fonts/,\n Extension=.ttf,\n RawFeature={fallback=symfb},\n UprightFont=Arimo-VF,\n UprightFeatures={RawFeature={axis={wght=400}}},\n BoldFont=Arimo-VF,\n BoldFeatures={RawFeature={axis={wght=700}}},\n";
#[test]
fn the_options_a_document_ships_its_font_with() {
let spec = FontFile::parse(REAL);
assert_eq!(spec.upright.as_deref(), Some("Arimo-VF"));
assert_eq!(spec.extension.as_deref(), Some(".ttf"));
assert_eq!(
spec.path.as_deref(),
Some("/private/tmp/build/scifi2/docs/.fonts/")
);
}
#[test]
fn a_value_holding_commas_does_not_tear_the_keys_after_it() {
let spec = FontFile::parse("Extension=.ttf,Numbers={Proportional,Lining},UprightFont=X-VF");
assert_eq!(spec.upright.as_deref(), Some("X-VF"));
assert_eq!(spec.extension.as_deref(), Some(".ttf"));
}
#[test]
fn a_stale_path_is_retried_beside_the_document() {
let dir = std::env::temp_dir().join(format!("texrs_ff_{}", std::process::id()));
let fonts = dir.join(".fonts");
std::fs::create_dir_all(&fonts).expect("mkdir");
let file = fonts.join("Arimo-VF.ttf");
std::fs::write(&file, b"not really a font").expect("write");
let spec =
FontFile::parse("Path=/gone/for/good/.fonts/,Extension=.ttf,UprightFont=Arimo-VF");
assert_eq!(spec.resolve(Some(&dir)), Some(file.clone()));
assert_eq!(spec.resolve(None), None);
let direct = format!(
"Path={}/,Extension=.ttf,UprightFont=Arimo-VF",
fonts.display()
);
assert_eq!(FontFile::parse(&direct).resolve(None), Some(file));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn options_that_name_no_file_resolve_to_nothing() {
assert_eq!(
FontFile::parse("").resolve(Some(std::path::Path::new("/tmp"))),
None
);
}
}