1use std::{
2 borrow::Cow,
3 cmp::max,
4 fmt,
5 hash::{Hash, Hasher},
6 rc::Rc,
7 sync::LazyLock,
8};
9
10use regex::Regex;
17use rustc_hash::FxHashMap as HashMap;
18
19use crate::{
20 BoxOps, Digested, DigestedData, Result,
21 binding::content::{fontmap_family_key_syms, fontmap_key_syms, load_font_map, preload_font_map},
22 common::{
23 arena::{self, SymHashMap, SymStr},
24 color::{self, Color},
25 dimension::Dimension,
26 numeric_ops::{NumericOps, UNITY, UNITY_F64, kround},
27 store::Stored,
28 },
29 state::*,
30};
31
32pub mod coverage;
33pub mod standard_metrics;
34pub mod tfm;
35
36type NamedFontClass = Option<(Option<Cow<'static, str>>, Option<Cow<'static, str>>)>;
38
39thread_local! {
40 static NAMED_FONT_CLASS: std::cell::RefCell<HashMap<String, NamedFontClass>> =
42 std::cell::RefCell::new(HashMap::default());
43}
44use standard_metrics::{MetricData, STDMETRICS};
45
46use crate::pin;
47
48pub type Fontmap = Rc<[Option<char>]>;
49
50static DEFFAMILY: &str = "serif";
51static DEFSERIES: &str = "medium";
52static DEFSHAPE: &str = "upright";
53static DEFCOLOR: Color = color::BLACK;
55static DEFOPACITY: &str = "1";
58static DEFENCODING: &str = "OT1";
59pub fn defsize() -> f64 {
64 let v = lookup_float("NOMINAL_FONT_SIZE").map_or(0.0, |f| f.0);
65 if v > 0.0 { v } else { 10.0 }
66}
67
68pub const TEXT_FONTS: [&str; 6] = ["cmr", "cmm", "cmsy", "cmex", "amsa", "amsb"];
69pub const MATH_FONTS: [&str; 6] = ["cmm", "cmsy", "cmex", "amsa", "amsb", "cmr"];
70
71pub const FLAG_FORCE_FAMILY: u8 = 0x1;
72pub const FLAG_FORCE_SERIES: u8 = 0x2;
73pub const FLAG_FORCE_SHAPE: u8 = 0x4;
74pub const FLAG_EMPH: u8 = 0x10;
75
76pub static FONT_TEXT_DEFAULT: LazyLock<Font> = LazyLock::new(Font::text_default);
77static LATIN_LETTER_RE: LazyLock<Regex> =
78 LazyLock::new(|| Regex::new(r"^[\p{Latin}&&\pL]$").unwrap());
79static GREEK_LETTER_RE: LazyLock<Regex> =
80 LazyLock::new(|| Regex::new(r"^[\p{Greek}&&\pL]$").unwrap());
81static UPPER_LETTER_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[\p{Lu}]$").unwrap());
82static DIGIT_LETTER_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[\p{N}]$").unwrap());
83#[rustfmt::skip]
84static FONT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^(xylubt|xyluat|xydash|xycmbt|xycmat|xycirc|xybtip|xybsql|xyatip|ul9|ugq|uaq|txtt|txsyb|txsya|txss|txr|txmi|pzd|pzc|pxsyb|pxsya|pxr|pxmi|put|ptm|psy|ppl|pnc|phv|pcr|pbk|pag|msy|msx|msb|msa|manfnt|linew|line|lcirclew|lcircle|futs|futmi|futm|eus|eur|euf|euex|cmvtt|cmtt|cmtl|cmt|cmsy|cmssqi|cmssq|cmss|cmsltt|cmr|cmmib|cmm|cmfr|cmfib|cmex|cmdunh|cmdh|cmu|cmbsy|cmbrs|cmbrm|cmbr|cm|ccy|ccr|ccm|ccitt|bch|bbold|bbmss|bbm)(sbc|sb|mc|m|bx|bm|bc|b|)(sl|sc|n|it|i|csc|)(\d*)$").unwrap());
85static FONT_FAMILY: LazyLock<HashMap<&'static str, Font>> = LazyLock::new(|| {
97 raw_map!(
98 "cmr" => fontmap!(family => "serif"), "cmss" => fontmap!(family => "sansserif"),
99 "cmtt" => fontmap!(family => "typewriter"), "cmvtt" => fontmap!(family => "typewriter"),
100 "cmt" => fontmap!(family => "serif"),
101 "cmsltt" => fontmap!(family => "typewriter", shape => "slanted"),
102 "cmssq" => fontmap!(family => "sansserif"),
103 "cmssqi" => fontmap!(family => "sansserif", shape => "italic"),
104 "cmdunh" => fontmap!(family => "serif"),
105 "cmu" => fontmap!(family => "serif"),
106 "cmfib" => fontmap!(family => "serif"), "cmfr" => fontmap!(family => "serif"),
107 "cmdh" => fontmap!(family => "serif"), "cm" => fontmap!(family => "serif"),
108 "ptm" => fontmap!(family => "serif"), "ppl" => fontmap!(family => "serif"),
109 "pnc" => fontmap!(family => "serif"), "pbk" => fontmap!(family => "serif"),
110 "phv" => fontmap!(family => "sansserif"), "pag" => fontmap!(family => "serif"),
111 "pcr" => fontmap!(family => "typewriter"), "pzc" => fontmap!(family => "script"),
112 "put" => fontmap!(family => "serif"), "bch" => fontmap!(family => "serif"),
113 "psy" => fontmap!(family => "symbol"), "pzd" => fontmap!(family => "dingbats"),
114 "ccr" => fontmap!(family => "serif"), "ccy" => fontmap!(family => "symbol"),
115 "cct" => fontmap!(family => "serif"),
119 "cmbr" => fontmap!(family => "sansserif"), "cmtl" => fontmap!(family => "typewriter"),
120 "cmbrs" => fontmap!(family => "symbol"), "ul9" => fontmap!(family => "typewriter"),
121 "txr" => fontmap!(family => "serif"), "txss" => fontmap!(family => "sansserif"),
122 "txtt" => fontmap!(family => "typewriter"),
123 "lmr" => fontmap!(family => "serif"), "lmss" => fontmap!(family => "sansserif"),
133 "lmtt" => fontmap!(family => "typewriter"), "lmvtt" => fontmap!(family => "typewriter"),
134 "qpl" => fontmap!(family => "serif"), "qtm" => fontmap!(family => "serif"),
136 "qbk" => fontmap!(family => "serif"), "qcs" => fontmap!(family => "serif"),
137 "qhv" => fontmap!(family => "sansserif"), "qag" => fontmap!(family => "sansserif"),
138 "qcr" => fontmap!(family => "typewriter"), "qzc" => fontmap!(family => "script"),
139 "zi4" => fontmap!(family => "typewriter"), "fi4" => fontmap!(family => "typewriter"),
142 "fvm" => fontmap!(family => "typewriter"), "fve" => fontmap!(family => "serif"),
143 "fvs" => fontmap!(family => "sansserif"),
144 "zsourcecodepro" => fontmap!(family => "typewriter"),
146 "SourceCodePro-TLF" => fontmap!(family => "typewriter"),
147 "FiraMono-TLF" => fontmap!(family => "typewriter"),
148 "FiraSans-TLF" => fontmap!(family => "sansserif"),
149 "txsya" => fontmap!(encoding => "AMSa"), "txsyb" => fontmap!(encoding => "AMSb"),
150 "pxr" => fontmap!(family => "serif"),
151 "pxsya" => fontmap!(encoding => "AMSa"), "pxsyb" => fontmap!(encoding => "AMSb"),
152 "futs" => fontmap!(family => "serif"),
153 "uaq" => fontmap!(family => "serif"), "ugq" => fontmap!(family => "sansserif"),
154 "manfnt" => fontmap!(family => "graphic", encoding => "manfnt"),
156 "line" => fontmap!(family => "graphic", encoding => "line"),
157 "linew" => fontmap!(family => "graphic", encoding => "line", series => "bold"),
158 "lcircle" => fontmap!(family => "graphic", encoding => "lcircle"),
159 "lcirclew" => fontmap!(family => "graphic", encoding => "lcircle", series => "bold"),
160 "xydash" => fontmap!(family => "graphic"), "xyatip" => fontmap!(family => "graphic"),
162 "xybtip" => fontmap!(family => "graphic"), "xybsql" => fontmap!(family => "graphic"),
163 "xycirc" => fontmap!(family => "graphic"), "xycmat" => fontmap!(family => "graphic"),
164 "xycmbt" => fontmap!(family => "graphic"), "xyluat" => fontmap!(family => "graphic"),
165 "xylubt" => fontmap!(family => "graphic"),
166 "eur" => fontmap!(family => "serif"), "eus" => fontmap!(family => "script"),
167 "euf" => fontmap!(family => "fraktur"), "euex" => fontmap!(encoding => "OMX"),
168 "ygoth" => fontmap!(family => "gothic"), "yswab" => fontmap!(family => "schwabacher"),
173 "yfrak" => fontmap!(family => "fraktur"),
174 "ccm" => fontmap!(family => "serif", shape => "italic"),
176 "cmm" => fontmap!(family => "math", shape => "italic", encoding => "OML"),
177 "cmex" => fontmap!(encoding => "OMX"),
178 "cmsy" => fontmap!(encoding => "OMS"),
179 "ccitt" => fontmap!(family => "typewriter", shape => "italic"),
180 "cmbrm" => fontmap!(family => "sansserif", shape => "italic"),
181 "futm" => fontmap!(family => "serif", shape => "italic"),
182 "futmi" => fontmap!(family => "serif", shape => "italic"),
183 "txmi" => fontmap!(family => "serif", shape => "italic"),
184 "pxmi" => fontmap!(family => "serif", shape => "italic"),
185 "bbm" => fontmap!(family => "blackboard"),
187 "bbold" => fontmap!(family => "blackboard"),
188 "bbmss" => fontmap!(family => "blackboard"),
189 "cmmib" => fontmap!(family => "italic", series => "bold"),
191 "cmbsy" => fontmap!(series => "bold", encoding => "OMS"),
192 "msa" => fontmap!(encoding => "AMSa"),
193 "msb" => fontmap!(encoding => "AMSb"),
194 "msx" => fontmap!(encoding => "AMSa"),
196 "msy" => fontmap!(encoding => "AMSb")
197 )
198});
199static FONT_SERIES: LazyLock<HashMap<&'static str, Font>> = LazyLock::new(|| {
201 raw_map!(
202 "" => Font::default(), "m" => fontmap!(series => "medium"),
203 "mc" => fontmap!(series => "medium"),
204 "b" => fontmap!(series => "bold"), "bc" => fontmap!(series => "bold"),
205 "bx" => fontmap!(series => "bold"),
206 "sb" => fontmap!(series => "bold"), "sbc" => fontmap!(series => "bold"),
207 "bm" => fontmap!(series => "bold")
208 )
209});
210
211static FONT_SHAPE: LazyLock<HashMap<&'static str, Font>> = LazyLock::new(|| {
213 raw_map!(
214 "" => Font::default(), "n" => fontmap!(shape => "upright"),
215 "i" => fontmap!(shape => "italic"), "it" => fontmap!(shape => "italic"),
216 "sl" => fontmap!(shape => "slanted"),
217 "sc" => fontmap!(shape => "smallcaps"), "csc" => fontmap!(shape => "smallcaps")
218 )
219});
220
221static FONT_SIZE: LazyLock<HashMap<&'static str, f64>> = LazyLock::new(|| {
225 raw_map!(
226"tiny" => 0.5, "SMALL" => 0.7, "Small" => 0.8, "small" => 0.9,
227"normal" => 1.0, "large" => 1.2, "Large" => 1.44, "LARGE" => 1.728,
228"huge" => 2.074, "Huge" => 2.488,
229"big" => 1.2, "Big" => 1.6, "bigg" => 2.1, "Bigg" => 2.6)
230});
231
232static SCRIPT_STYLE_MAP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
233 raw_map!(
234 "display" => "script", "text" => "script",
235 "script" => "scriptscript", "scriptscript" => "scriptscript")
236});
237
238static FRAC_STYLE_MAP: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
239 raw_map!(
240 "display" => "text", "text" => "script",
241 "script" => "scriptscript", "scriptscript" => "scriptscript")
242});
243
244static STYLE_SIZE: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
245 raw_map!(
246 "display" => 10, "text" => 10, "script" => 7, "scriptscript" => 5)
247});
248
249static MATH_STYLE_STEP: LazyLock<HashMap<&'static str, HashMap<&'static str, i32>>> =
257 LazyLock::new(|| {
258 raw_map!(
259 "display" => raw_map!(
260 "display" => 0, "text" => 1, "script" => 2, "scriptscript" => 3),
261 "text"=> raw_map!("display" => -1, "text" => 0, "script" => 1, "scriptscript" => 2),
262 "script"=> raw_map!("display" => -2, "text" => -1, "script" => 0, "scriptscript" => 1),
263 "scriptscript" => raw_map!("display" => -3, "text" => -2, "script" => -1, "scriptscript" => 0))
264 });
265static STEP_MATH_STYLE: LazyLock<HashMap<&'static str, HashMap<i32, &'static str>>> =
266 LazyLock::new(|| {
267 raw_map!(
268"display" => raw_map!(-3 => "display", -2 => "display", -1 => "display",
269 0 => "display", 1 => "text", 2 => "script", 3 => "scriptscript"),
270"text" => raw_map!(-3 => "display", -2 => "display", -1 => "display",
271 0 => "text", 1 => "script", 2 => "scriptscript", 3 => "scriptscript"),
272"script" => raw_map!(-3 => "display", -2 => "display", -1 => "text",
273 0 => "script", 1 => "scriptscript", 2 => "scriptscript", 3 => "scriptscript"),
274"scriptscript" => raw_map!(-3 => "display", -2 => "text", -1 => "script",
275 0 => "scriptscript", 1 => "scriptscript", 2 => "scriptscript", 3 => "scriptscript"))
276 });
277
278fn lookup_metric_name(family: &str, series: &str, shape: &str) -> Option<&'static str> {
285 match (family, series, shape) {
286 ("serif", "medium", "upright") => Some("cmr"),
287 ("serif", "medium", "slanted") => Some("cmsl"),
288 ("serif", "medium", "italic") => Some("cmti"),
289 ("serif", "medium", "uprightitalic") => Some("cmu"),
290 ("serif", "bold", "upright") => Some("cmbx"),
291 ("serif", "medum", "smallcaps") => Some("cmcsc"), ("sansserif", "medium", "upright") => Some("cmss"),
293 ("sansserif", "medium", "italic") => Some("cmssi"),
294 ("sansserif", "bold", "upright") => Some("cmssbx"),
295 ("typewriter", "medium", "upright") => Some("cmtt"),
296 ("typewriter", "medium", "slanted") => Some("cmsltt"),
297 ("math", "medium", "italic") => Some("cmmi"),
298 ("math", "medium", "upright") => Some("cmr"),
299 ("math", "bold", "italic") => Some("cmmib"),
300 _ => None,
301 }
302}
303
304static METRIC_FALLBACKS: [&str; 7] = ["cmr", "cmmi", "cmsy", "cmex", "msam", "msbm", "ifgeo"];
308
309#[rustfmt::skip]
312static MATH_ATOM_TYPE: LazyLock<HashMap<&'static str, usize>> = LazyLock::new(|| {
313 raw_map!(
314 "ID" => 0,
315 "BIGOP" => 1, "SUMOP" => 1, "INTOP" => 1, "OPERATOR" => 1, "LIMITOP" => 1, "DIFFOP" => 1,
316 "ADDOP" => 2, "MULOP" => 2, "BINOP" => 2, "COMPOSEOP" => 2, "MIDDLE" => 2, "VERTBAR" => 2,
317 "RELOP" => 3, "METARELOP" => 3, "ARROW" => 3,
318 "OPEN" => 4, "CLOSE" => 5,
319 "PUNCT" => 6, "PERIOD" => 6,
320 "ARRAY" => 7, "MODIFIER" => 7
321 )
322});
323
324#[rustfmt::skip]
328static MATH_BEARINGS: [[i8; 8]; 8] = [
329 [ 0, 1, -2, -3, 0, 0, 0, -1],
330 [ 1, 1, 0, -3, 0, 0, 0, -1],
331 [-2, -2, 0, 0, -2, 0, 0, -2],
332 [-3, -3, 0, 0, -3, 0, 0, -3],
333 [ 0, 0, 0, 0, 0, 0, 0, 0],
334 [ 0, 1, -2, -3, 0, 0, 0, -1],
335 [-1, -1, 0, -1, -1, -1, -1, -1],
336 [-1, 1, -2, -3, -1, 0, -1, -1],
337];
338
339pub fn lookup_font_family(code: &str) -> Option<&'static Font> { FONT_FAMILY.get(code) }
346
347pub fn is_unicode_encoding(encoding: &str) -> bool { encoding == "TU" }
352
353pub fn lookup_font_series(code: &str) -> Option<&'static Font> { FONT_SERIES.get(code) }
355
356pub fn lookup_font_shape(code: &str) -> Option<&'static Font> { FONT_SHAPE.get(code) }
358
359pub fn nfss_family_code(family: &str) -> Option<&'static str> {
368 match family {
369 "serif" => Some("cmr"),
370 "sansserif" => Some("cmss"),
371 "typewriter" => Some("cmtt"),
372 "script" => Some("pzc"),
373 "symbol" => Some("psy"),
374 "dingbats" => Some("pzd"),
375 "fraktur" => Some("euf"),
376 "gothic" => Some("ygoth"),
377 "schwabacher" => Some("yswab"),
378 "blackboard" => Some("bbm"),
379 _ => None,
380 }
381}
382
383pub fn nfss_series_code(series: &str) -> Option<&'static str> {
386 match series {
387 "medium" => Some("m"),
388 "bold" => Some("bx"),
389 _ => None,
390 }
391}
392
393pub fn nfss_shape_code(shape: &str) -> Option<&'static str> {
398 match shape {
399 "upright" | "normal" => Some("n"),
400 "italic" => Some("it"),
401 "slanted" => Some("sl"),
402 "smallcaps" => Some("sc"),
403 _ => None,
404 }
405}
406
407pub fn format_points(points: f64) -> String {
410 let text = format!("{points:.2}");
411 let text = text.trim_end_matches('0').trim_end_matches('.');
412 text.to_string()
413}
414
415pub fn tex_font_file_name(
421 family: &str,
422 series: &str,
423 shape: &str,
424 points: f64,
425) -> Option<(String, Option<String>)> {
426 let base = lookup_metric_name(family, series, shape)?;
427 Some(if points.fract() == 0.0 {
428 (format!("{base}{points}"), None)
429 } else {
430 (
431 format!("{base}10"),
432 Some(format!("{}pt", format_points(points))),
433 )
434 })
435}
436
437pub fn lookup_tex_font(fontname: &str, seriescode: &str, shapecode: &str) -> Font {
439 let mut props = Font::default();
440 if let Some(ffam) = lookup_font_family(fontname) {
441 props = props.merge_ref(ffam);
442 }
443 if let Some(fser) = lookup_font_series(seriescode) {
444 props = props.merge_ref(fser);
445 }
446 if let Some(fsh) = lookup_font_shape(shapecode) {
447 props = props.merge_ref(fsh);
448 }
449 props
450}
451
452pub fn get_metric_for_name(name: &str) -> &'static MetricData {
455 let base = if let Some(idx) = name.find(|c: char| c.is_ascii_digit()) {
456 &name[..idx]
457 } else {
458 name
459 };
460 if let Some(m) = STDMETRICS.get(name) {
462 return m;
463 }
464 if let Some(m) = STDMETRICS.get(base) {
466 return m;
467 }
468 let base_bytes = base.as_bytes();
474 if base_bytes.len() + 2 <= 32 {
475 let mut buf = [0u8; 32];
476 buf[..base_bytes.len()].copy_from_slice(base_bytes);
477 buf[base_bytes.len()] = b'1';
478 buf[base_bytes.len() + 1] = b'0';
479 if let Ok(s) = std::str::from_utf8(&buf[..base_bytes.len() + 2])
480 && let Some(m) = STDMETRICS.get(s)
481 {
482 return m;
483 }
484 }
485 STDMETRICS
487 .get("cmr")
488 .expect("STDMETRICS must contain 'cmr'")
489}
490
491pub fn font_parameters_for_name(name: &str) -> &'static [f64] {
499 let base = name.trim_end_matches(|c: char| c.is_ascii_digit());
500 let size = if base.len() < name.len() {
501 &name[base.len()..]
502 } else {
503 "10"
504 };
505 [name, &format!("{base}10"), &format!("cmr{size}"), "cmr10"]
506 .into_iter()
507 .filter_map(|candidate| STDMETRICS.get(candidate))
508 .map(|metric| metric.parameters)
509 .find(|parameters| !parameters.is_empty())
510 .unwrap_or(&[])
511}
512
513pub const FONT_MEM_SIZE: usize = 8_000_000;
517
518pub fn decode_fontname(name: &str, at_opt: Option<f64>, scaled_opt: Option<f64>) -> Option<Font> {
519 if let Some(cap) = FONT_RE.captures(name) {
520 let mut props = Font {
522 series: Some(Cow::Borrowed(DEFSERIES)),
523 shape: Some(Cow::Borrowed(DEFSHAPE)),
524 encoding: Some(Cow::Borrowed("OT1")),
525 ..Font::default()
526 };
527 let fam = cap.get(1).map_or("", |m| m.as_str());
528 let ser = cap.get(2).map_or("", |m| m.as_str());
529 let shp = cap.get(3).map_or("", |m| m.as_str());
530 let size_str = cap.get(4).map_or("", |m| m.as_str());
531 if let Some(ffam) = lookup_font_family(fam) {
532 props = props.merge_ref(ffam);
533 }
534 if let Some(fser) = lookup_font_series(ser) {
535 props = props.merge_ref(fser);
536 }
537 if let Some(fsh) = lookup_font_shape(shp) {
538 props = props.merge_ref(fsh);
539 }
540 let mut size = if let Some(at) = at_opt {
541 at
542 } else {
543 let size_f64 = size_str.parse::<f64>().unwrap_or(1.0);
544 if size_f64 == 0.0 { 1.0 } else { size_f64 } };
546 if let Some(scaled) = scaled_opt {
547 size *= scaled;
548 }
549 props.size = Some(size);
550 if props.encoding.is_none() {
552 props.encoding = Some(Cow::Borrowed("OT1"));
553 }
554 Some(props)
559 } else {
560 None
561 }
562}
563
564#[derive(Clone, Copy, Debug, PartialEq, Eq)]
567pub enum LettersClass {
568 Variable,
570 Fixed,
572}
573
574#[derive(Clone, Default)]
582pub struct Font {
583 pub family: Option<Cow<'static, str>>,
584 pub series: Option<Cow<'static, str>>,
585 pub shape: Option<Cow<'static, str>>,
586 pub size: Option<f64>,
587 pub color: Option<Color>,
588 pub bg: Option<Color>,
589 pub opacity: Option<Cow<'static, str>>,
590 pub encoding: Option<Cow<'static, str>>,
591 pub language: Option<Cow<'static, str>>,
592 pub mathstyle: Option<Cow<'static, str>>,
593 pub mathstylestep: Option<i32>,
594 pub name: Option<Cow<'static, str>>,
595 pub nfss_font: Option<std::sync::Arc<Font>>,
603 pub emph: Option<bool>,
604 pub scripted: Option<bool>,
605 pub fraction: Option<bool>,
606 pub forceseries: Option<bool>,
609 pub forcefamily: Option<bool>,
610 pub forceshape: Option<bool>,
611 pub forcebold: Option<bool>,
612 pub scale: Option<f64>,
613 pub flags: Option<u8>,
614}
615
616impl Hash for Font {
617 fn hash<H: Hasher>(&self, hasher: &mut H) {
621 self.family.hash(hasher);
622 self.series.hash(hasher);
623 self.shape.hash(hasher);
624 self.size.map(|size| (size * 1000.0) as i64).hash(hasher);
625 Some(self.color.unwrap_or(DEFCOLOR)).hash(hasher);
627 self.bg.hash(hasher);
628 self.opacity.hash(hasher);
629 self.encoding.hash(hasher);
630 self.language.hash(hasher);
631 self.mathstyle.hash(hasher);
632 self.mathstylestep.hash(hasher);
633 self.name.hash(hasher);
634 self.emph.hash(hasher);
635 self.scripted.hash(hasher);
636 self.forceseries.hash(hasher);
637 self.forcefamily.hash(hasher);
638 self.forceshape.hash(hasher);
639 self.scale.map(|scale| (scale * 1000.0) as i64).hash(hasher);
640 self.flags.hash(hasher);
641 }
642}
643impl PartialEq for Font {
644 fn eq(&self, other: &Self) -> bool {
645 self.family == other.family
646 && self.series == other.series
647 && self.shape == other.shape
648 && self.size == other.size
649 && !is_diff_font_color(self.color.as_ref(), other.color.as_ref())
650 && self.bg == other.bg
651 && self.opacity == other.opacity
652 && self.encoding == other.encoding
653 && self.language == other.language
654 && self.mathstyle == other.mathstyle
655 && self.mathstylestep == other.mathstylestep
656 && self.name == other.name
657 && self.emph == other.emph
658 && self.scripted == other.scripted
659 && self.fraction == other.fraction
660 && self.forceseries == other.forceseries
661 && self.forcefamily == other.forcefamily
662 && self.forceshape == other.forceshape
663 && self.forcebold == other.forcebold
664 && self.scale == other.scale
665 && self.flags == other.flags
666 }
667}
668impl Eq for Font {}
669impl Font {
670 pub fn perl_equals(&self, other: &Font) -> bool {
680 self.family == other.family
681 && self.series == other.series
682 && self.shape == other.shape
683 && self.size == other.size
684 && !is_diff_font_color(self.color.as_ref(), other.color.as_ref())
685 && self.bg == other.bg
686 && self.opacity == other.opacity
687 && self.encoding.as_deref().unwrap_or(DEFENCODING)
688 == other.encoding.as_deref().unwrap_or(DEFENCODING)
689 && self.language == other.language
690 && self.mathstyle == other.mathstyle
691 && self.flags.unwrap_or(0) == other.flags.unwrap_or(0)
692 }
693}
694impl fmt::Display for Font {
697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
698 write!(f, "{}", self.family.as_ref().unwrap_or(&Cow::Borrowed("")))
699 }
700}
701
702impl fmt::Debug for Font {
703 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
704 let star = Cow::Borrowed("*");
705 write!(f, "Font[")?;
706 write!(f, "{}", self.family.as_ref().unwrap_or(&star))?;
707 write!(f, ",")?;
708 write!(f, "{}", self.series.as_ref().unwrap_or(&star))?;
709 write!(f, ",")?;
710 write!(f, "{}", self.shape.as_ref().unwrap_or(&star))?;
711 write!(f, ",")?;
712 let size_str = self
713 .size
714 .as_ref()
715 .map(|x| x.to_string())
716 .unwrap_or_else(|| String::from('*'));
717 write!(f, "{}", size_str)?;
718 write!(f, ",")?;
719 if let Some(ref c) = self.color {
720 write!(f, "{c}")?;
721 } else {
722 write!(f, "*")?;
723 }
724 write!(f, ",")?;
725 if let Some(ref b) = self.bg {
726 write!(f, "{b}")?;
727 } else {
728 write!(f, "*")?;
729 }
730 write!(f, ",")?;
731 write!(f, "{}", self.opacity.as_ref().unwrap_or(&star))?;
732 write!(f, ",")?;
733 let scale_str = self
734 .scale
735 .as_ref()
736 .map(|x| x.to_string())
737 .unwrap_or_else(|| String::from('*'));
738 write!(f, "{}", scale_str)?;
739 write!(f, ",")?;
740 write!(f, "{}", self.mathstyle.as_ref().unwrap_or(&star))?;
741 write!(f, "]")
764 }
765}
766
767impl Font {
768 pub fn text_default() -> Self {
769 Font {
770 family: Some(Cow::Borrowed(DEFFAMILY)),
771 series: Some(Cow::Borrowed(DEFSERIES)),
772 shape: Some(Cow::Borrowed(DEFSHAPE)),
773 size: Some(defsize()),
774 color: None, bg: None, opacity: Some(Cow::Borrowed(DEFOPACITY)),
777 encoding: Some(Cow::Borrowed(DEFENCODING)),
778 language: None, mathstyle: None,
780 mathstylestep: None,
781 emph: None,
782 name: None,
783 nfss_font: None,
784 scripted: None,
785 fraction: None,
786 forceseries: None,
787 forcefamily: None,
788 forceshape: None,
789 forcebold: None,
790 scale: None,
791 flags: None,
792 }
793 }
794 pub fn math_default() -> Self {
795 Font {
796 family: Some(Cow::Borrowed("math")),
797 series: Some(Cow::Borrowed(DEFSERIES)),
798 shape: Some(Cow::Borrowed("italic")),
799 size: Some(defsize()),
800 color: None, bg: None, opacity: Some(Cow::Borrowed(DEFOPACITY)),
803 encoding: None, language: None, mathstyle: Some(Cow::Borrowed("text")),
806 mathstylestep: None,
807 emph: None,
808 name: None,
809 nfss_font: None,
810 scripted: None,
811 fraction: None,
812 forceseries: None,
813 forcefamily: None,
814 forceshape: None,
815 forcebold: None,
816 scale: None,
817 flags: None,
818 }
819 }
820
821 pub fn to_hashable(&self) -> u64 {
822 let mut hasher = rustc_hash::FxHasher::default();
830 Hash::hash(self, &mut hasher);
831 hasher.finish()
832 }
833
834 pub fn stringify(&self) -> String {
837 let fam = self
838 .family
839 .as_deref()
840 .map(|f| if f == "math" { "serif" } else { f });
841 let mut parts: Vec<&str> = Vec::new();
842 if let Some(f) = fam
843 && f != DEFFAMILY
844 {
845 parts.push(f);
846 }
847 if let Some(ref ser) = self.series
848 && ser.as_ref() != DEFSERIES
849 {
850 parts.push(ser);
851 }
852 if let Some(ref shp) = self.shape
853 && shp.as_ref() != DEFSHAPE
854 {
855 parts.push(shp);
856 }
857 let size_str;
859 if let Some(siz) = self.size
860 && (siz - defsize()).abs() > 0.001
861 {
862 size_str = siz.to_string();
863 parts.push(&size_str);
864 }
865 let color_str;
866 if let Some(ref col) = self.color
867 && *col != DEFCOLOR
868 {
869 color_str = col.to_attribute();
870 parts.push(&color_str);
871 }
872 let bg_str;
873 if let Some(ref bkg) = self.bg {
874 bg_str = bkg.to_attribute();
876 parts.push(&bg_str);
877 }
878 if let Some(ref opa) = self.opacity
879 && opa.as_ref() != DEFOPACITY
880 {
881 parts.push(opa);
882 }
883 if let Some(ref ms) = self.mathstyle {
884 parts.push(ms);
885 }
886 let flags_str;
887 if let Some(flags) = self.flags
888 && flags != 0
889 {
890 flags_str = flags.to_string();
891 parts.push(&flags_str);
892 }
893 format!("Font[{}]", parts.join(","))
894 }
895
896 pub fn font_match(&self, other: &Font) -> bool {
899 fn check<T: PartialEq>(a: &Option<T>, b: &Option<T>) -> bool {
900 !(a.is_some() && b.is_some() && a != b)
901 }
902 check(&self.family, &other.family)
903 && check(&self.series, &other.series)
904 && check(&self.shape, &other.shape)
905 && check(&self.size, &other.size)
906 && !is_diff_font_color(self.color.as_ref(), other.color.as_ref())
908 && check(&self.bg, &other.bg)
909 && check(&self.opacity, &other.opacity)
910 && check(&self.encoding, &other.encoding)
911 && check(&self.language, &other.language)
912 && check(&self.mathstyle, &other.mathstyle)
913 }
914
915 pub fn make_concrete(&self, concrete: &Font) -> Self {
918 Font {
919 family: self.family.clone().or_else(|| concrete.family.clone()),
920 series: self.series.clone().or_else(|| concrete.series.clone()),
921 shape: self.shape.clone().or_else(|| concrete.shape.clone()),
922 size: self.size.or(concrete.size),
923 color: self.color.or(concrete.color),
924 bg: self.bg.or(concrete.bg),
925 opacity: self.opacity.clone().or_else(|| concrete.opacity.clone()),
926 encoding: self.encoding.clone().or_else(|| concrete.encoding.clone()),
927 language: self.language.clone().or_else(|| concrete.language.clone()),
928 mathstyle: self
929 .mathstyle
930 .clone()
931 .or_else(|| concrete.mathstyle.clone()),
932 flags: Some(self.flags.unwrap_or(0) | concrete.flags.unwrap_or(0)),
933 mathstylestep: self.mathstylestep.or(concrete.mathstylestep),
934 name: self.name.clone().or_else(|| concrete.name.clone()),
935 nfss_font: self
936 .nfss_font
937 .clone()
938 .or_else(|| concrete.nfss_font.clone()),
939 emph: self.emph.or(concrete.emph),
940 scripted: self.scripted.or(concrete.scripted),
941 fraction: self.fraction.or(concrete.fraction),
942 forceseries: self.forceseries.or(concrete.forceseries),
943 forcefamily: self.forcefamily.or(concrete.forcefamily),
944 forceshape: self.forceshape.or(concrete.forceshape),
945 forcebold: self.forcebold.or(concrete.forcebold),
946 scale: self.scale.or(concrete.scale),
947 }
948 }
949
950 pub fn merge_purestyle(&self, changes: &Font) -> Self {
953 let mut new = self.clone();
954 if let Some(scale) = changes.scale
955 && let Some(ref mut sz) = new.size
956 {
957 *sz *= scale;
958 }
959 if changes.color.is_some() {
960 new.color.clone_from(&changes.color);
961 }
962 if changes.bg.is_some() {
963 new.bg.clone_from(&changes.bg);
964 }
965 if changes.opacity.is_some() {
966 new.opacity.clone_from(&changes.opacity);
967 }
968 if let Some(step) = changes.mathstylestep {
969 let cur_style: &str = new.mathstyle.as_deref().unwrap_or("display");
970 if let Some(step_map) = STEP_MATH_STYLE.get(cur_style)
971 && let Some(new_style) = step_map.get(&step)
972 {
973 new.mathstyle = Some(Cow::Borrowed(new_style));
974 }
975 }
976 new
977 }
978
979 pub fn math_bearing(&self, thisbox: &Digested, prevbox: &Digested) -> f64 {
982 let r0 = prevbox
983 .get_property("role")
984 .and_then(|s| match s.into_owned() {
985 Stored::String(sym) => Some(arena::with(sym, |s| s.to_string())),
986 _ => None,
987 })
988 .unwrap_or_else(|| "ID".to_string());
989 let r1 = thisbox
990 .get_property("role")
991 .and_then(|s| match s.into_owned() {
992 Stored::String(sym) => Some(arena::with(sym, |s| s.to_string())),
993 _ => None,
994 })
995 .unwrap_or_else(|| "ID".to_string());
996 let t0 = *MATH_ATOM_TYPE.get(r0.as_str()).unwrap_or(&0);
997 let t1 = *MATH_ATOM_TYPE.get(r1.as_str()).unwrap_or(&0);
998 let bearing = MATH_BEARINGS[t0][t1];
999 let style = self
1000 .get_mathstyle()
1001 .map(|s| s.to_string())
1002 .unwrap_or_else(|| "text".to_string());
1003 if bearing == 0 || (bearing < 0 && style != "display" && style != "text") {
1004 return 0.0;
1005 }
1006 let reg_cs = match bearing.unsigned_abs() {
1008 1 => T_CS!("\\thinmuskip"),
1009 2 => T_CS!("\\medmuskip"),
1010 3 => T_CS!("\\thickmuskip"),
1011 _ => return 0.0,
1012 };
1013 if let Ok(Some(def)) = lookup_definition(®_cs)
1014 && let Some(val) = def.value_of(Vec::new())
1015 {
1016 let skip = val.value_of();
1021 let mu_width = self.get_mu_width() as f64;
1022 return (skip as f64 / UNITY_F64 * mu_width).trunc();
1023 }
1024 0.0
1025 }
1026
1027 pub fn is_sticky(&self) -> bool {
1028 if let Some(ref family) = self.family {
1029 family == "serif" || family == "sansserif" || family == "typewriter"
1030 } else {
1031 false
1032 }
1033 }
1034
1035 pub fn get_family(&self) -> Option<&Cow<'_, str>> { self.family.as_ref() }
1037 pub fn get_series(&self) -> Option<&Cow<'_, str>> { self.series.as_ref() }
1038 pub fn get_shape(&self) -> Option<&Cow<'_, str>> { self.shape.as_ref() }
1039 pub fn get_size(&self) -> Option<f64> { self.size }
1040 pub fn get_color(&self) -> Option<&Color> { self.color.as_ref() }
1041 pub fn get_background(&self) -> Option<&Color> { self.bg.as_ref() }
1042 pub fn get_opacity(&self) -> Option<&Cow<'_, str>> { self.opacity.as_ref() }
1043 pub fn get_encoding(&self) -> Option<&Cow<'_, str>> { self.encoding.as_ref() }
1044 pub fn get_language(&self) -> Option<&Cow<'_, str>> { self.language.as_ref() }
1045 pub fn get_mathstyle(&self) -> Option<&Cow<'_, str>> { self.mathstyle.as_ref() }
1046 pub fn get_flags(&self) -> Option<u8> { self.flags }
1047
1048 pub fn merge(&self, other: Font) -> Self { self.merge_ref(&other) }
1053
1054 pub fn merge_ref(&self, other: &Font) -> Self {
1059 if self.nfss_font.is_some()
1065 && other.name.is_none()
1066 && (other.family.is_some()
1067 || other.series.is_some()
1068 || other.shape.is_some()
1069 || other.encoding.is_some()
1070 || other.forcebold.is_some()
1071 || other.emph == Some(true))
1072 {
1073 return self.nfss_restored().merge_ref(other);
1074 }
1075 let mut series = other.series.clone();
1077 let mut force_series = other.forceseries;
1078 if other.forcebold == Some(true) {
1079 series = Some(Cow::Borrowed("bold"));
1080 force_series = Some(true);
1081 }
1082 let unbold = other.forcebold == Some(false);
1087 if unbold {
1088 series = Some(Cow::Borrowed("medium"));
1089 }
1090
1091 let mut flags: u8 = 0;
1093 if other.forcefamily == Some(true) {
1094 flags |= FLAG_FORCE_FAMILY;
1095 }
1096 if force_series == Some(true) {
1097 flags |= FLAG_FORCE_SERIES;
1098 }
1099 if other.forceshape == Some(true) {
1100 flags |= FLAG_FORCE_SHAPE;
1101 }
1102
1103 let oflags = self.flags.unwrap_or(0);
1104 let family = if other.family.is_none() || (oflags & FLAG_FORCE_FAMILY != 0) {
1106 self.family.clone()
1107 } else {
1108 other.family.clone()
1109 };
1110 let series = if !unbold && (series.is_none() || (oflags & FLAG_FORCE_SERIES != 0)) {
1111 self.series.clone()
1112 } else {
1113 series
1114 };
1115 let mut shape = if other.shape.is_none() || (oflags & FLAG_FORCE_SHAPE != 0) {
1116 self.shape.clone()
1117 } else {
1118 other.shape.clone()
1119 };
1120 let mut size = other.size.or(self.size);
1121 let color = other.color.or(self.color);
1122 let bg = if other.bg.is_some() {
1125 other.bg
1126 } else {
1127 self.bg
1128 };
1129 let opacity = other.opacity.clone().or_else(|| self.opacity.clone());
1130 let encoding = other.encoding.clone().or_else(|| self.encoding.clone());
1131 let language = other.language.clone().or_else(|| self.language.clone());
1132 let mut mathstyle = other.mathstyle.clone().or_else(|| self.mathstyle.clone());
1133 flags |= self.flags.unwrap_or(0);
1134 if unbold {
1135 flags &= !FLAG_FORCE_SERIES;
1136 }
1137
1138 if let Some(scale) = other.scale
1140 && let Some(ref mut sz) = size
1141 {
1142 *sz *= scale;
1143 }
1144
1145 let style_scale = if let Some(sz) = self.size {
1147 let key: &str = self.mathstyle.as_deref().unwrap_or("display");
1148 sz / *STYLE_SIZE.get(key).unwrap_or(&10) as f64
1149 } else {
1150 1.0
1151 };
1152
1153 if other.size.is_some() {
1154 } else if other.mathstyle.is_some() {
1156 let ms: &str = mathstyle.as_deref().unwrap_or("display");
1158 size = Some(style_scale * *STYLE_SIZE.get(ms).unwrap_or(&10) as f64);
1159 } else if other.scripted == Some(true) {
1160 let ms: &str = mathstyle.as_deref().unwrap_or("display");
1162 mathstyle = SCRIPT_STYLE_MAP.get(ms).map(|c| Cow::Borrowed(*c));
1163 let new_ms: &str = mathstyle.as_deref().unwrap_or("display");
1164 size = Some(style_scale * *STYLE_SIZE.get(new_ms).unwrap_or(&10) as f64);
1165 } else if other.fraction == Some(true) {
1166 let ms: &str = mathstyle.as_deref().unwrap_or("display");
1168 mathstyle = FRAC_STYLE_MAP.get(ms).map(|c| Cow::Borrowed(*c));
1169 let new_ms: &str = mathstyle.as_deref().unwrap_or("display");
1170 size = Some(style_scale * *STYLE_SIZE.get(new_ms).unwrap_or(&10) as f64);
1171 }
1172
1173 if other.emph == Some(true) {
1175 shape = if shape.as_deref() == Some("italic") {
1176 Some(Cow::Borrowed("upright"))
1177 } else {
1178 Some(Cow::Borrowed("italic"))
1179 };
1180 flags |= FLAG_EMPH;
1181 }
1182 if mathstyle.is_some() {
1184 flags &= !FLAG_EMPH;
1185 }
1186
1187 let newfont = Font {
1188 family,
1189 series,
1190 shape,
1191 size,
1192 color,
1193 bg,
1194 opacity,
1195 encoding,
1196 language,
1197 mathstyle,
1198 flags: Some(flags),
1199 mathstylestep: other.mathstylestep.or(self.mathstylestep),
1201 name: other.name.clone().or_else(|| self.name.clone()),
1202 nfss_font: self.nfss_font.clone(),
1203 emph: None,
1204 scripted: None,
1205 fraction: None,
1206 forceseries: if flags & FLAG_FORCE_SERIES != 0 {
1207 Some(true)
1208 } else {
1209 None
1210 },
1211 forcefamily: if flags & FLAG_FORCE_FAMILY != 0 {
1212 Some(true)
1213 } else {
1214 None
1215 },
1216 forceshape: if flags & FLAG_FORCE_SHAPE != 0 {
1217 Some(true)
1218 } else {
1219 None
1220 },
1221 forcebold: None,
1222 scale: None,
1223 };
1224 newfont
1230 }
1231
1232 pub fn specialize(&self, text: &str) -> Self {
1241 let mut new = self.clone();
1242 if text.is_empty() {
1243 return new; }
1245 let (deffamily, defseries, defshape) = self.specialize_defaults();
1246 if LATIN_LETTER_RE.is_match(text) {
1247 new.specialize_as_latin_letter();
1249 } else if GREEK_LETTER_RE.is_match(text) {
1250 if UPPER_LETTER_RE.is_match(text) {
1252 if new.family.is_none() || (new.family.as_ref().unwrap() == "math") {
1254 new.family = Some(deffamily);
1255 if new.shape.is_some() && (new.shape != Some(DEFSHAPE.into())) {
1256 new.shape = Some(defshape); }
1258 }
1259 } else {
1260 new.specialize_as_lowercase_greek(self, deffamily, defseries);
1262 }
1263 } else if DIGIT_LETTER_RE.is_match(text) {
1264 if new.family.is_none() || (new.family.as_ref().unwrap() == "math") {
1266 new.family = Some(deffamily);
1267 new.shape = Some(defshape); }
1269 } else {
1270 new.family = Some(deffamily);
1272 new.shape = Some(defshape); if new.series.is_some() && (new.series.as_ref().unwrap() != DEFSERIES) {
1274 new.series = Some(defseries);
1275 } }
1277 new
1278 }
1279
1280 fn specialize_defaults(&self) -> (Cow<'static, str>, Cow<'static, str>, Cow<'static, str>) {
1283 let deffamily = if self.forcefamily.unwrap_or(false) {
1284 self.family.clone().unwrap_or_else(|| DEFFAMILY.into())
1285 } else {
1286 DEFFAMILY.into()
1287 };
1288 let defseries = if self.forceseries.unwrap_or(false) {
1289 self.series.clone().unwrap_or_else(|| DEFSERIES.into())
1290 } else {
1291 DEFSERIES.into()
1292 };
1293 let defshape = if self.forceshape.unwrap_or(false) {
1294 self.shape.clone().unwrap_or_else(|| DEFSHAPE.into())
1295 } else {
1296 DEFSHAPE.into()
1297 };
1298 (deffamily, defseries, defshape)
1299 }
1300
1301 fn specialize_as_latin_letter(&mut self) {
1303 if self.shape.is_none() && self.family.is_none() {
1304 self.shape = Some("italic".into());
1305 }
1306 }
1307
1308 fn specialize_as_lowercase_greek(
1311 &mut self,
1312 orig: &Font,
1313 deffamily: Cow<'static, str>,
1314 defseries: Cow<'static, str>,
1315 ) {
1316 if self.family.is_none() || (self.family.as_deref() != Some(DEFFAMILY)) {
1317 self.family = Some(deffamily);
1318 }
1319 if self.shape.is_none() || !orig.forceshape.unwrap_or(false) {
1321 self.shape = Some("italic".into());
1322 }
1323 if self.series.is_some() && (self.series != Some(DEFSERIES.into())) {
1324 self.series = Some(defseries);
1325 }
1326 }
1327
1328 pub fn specialize_letters(&self, text: &str, class: LettersClass) -> Self {
1341 if !(GREEK_LETTER_RE.is_match(text) && UPPER_LETTER_RE.is_match(text)) {
1342 return self.specialize(text);
1343 }
1344 let mut new = self.clone();
1345 match class {
1346 LettersClass::Variable => new.specialize_as_latin_letter(),
1347 LettersClass::Fixed => {
1348 let (deffamily, defseries, _) = self.specialize_defaults();
1349 new.specialize_as_lowercase_greek(self, deffamily, defseries);
1350 },
1351 }
1352 new
1353 }
1354
1355 pub fn distance(&self, other: &Font) -> i8 {
1356 let mut distance: i8 = 0;
1357 let fam = self
1359 .family
1360 .as_deref()
1361 .map(|f| if f == "math" { "serif" } else { f });
1362 let ofam = other
1363 .family
1364 .as_deref()
1365 .map(|f| if f == "math" { "serif" } else { f });
1366 if is_diff_opt_str(fam, ofam) {
1367 distance += 1;
1368 }
1369 if is_diff_opt_str(self.series.as_deref(), other.series.as_deref()) {
1370 distance += 1;
1371 }
1372 if is_diff_opt_str(self.shape.as_deref(), other.shape.as_deref()) {
1373 distance += 1;
1374 }
1375 if is_diff_f64(self.size, other.size) {
1376 distance += 1;
1377 }
1378 if is_diff_font_color_ref(self.color.as_ref(), other.color.as_ref()) {
1382 distance += 1;
1383 }
1384 if is_diff_color(self.bg.as_ref(), other.bg.as_ref()) {
1385 distance += 1;
1386 }
1387 if is_diff_opt_str(self.opacity.as_deref(), other.opacity.as_deref()) {
1388 distance += 1;
1389 }
1390 if is_diff_opt_str(self.language.as_deref(), other.language.as_deref()) {
1393 distance += 1;
1394 }
1395 let flags = self.flags.unwrap_or(0);
1397 let oflags = other.flags.unwrap_or(0);
1398 if (flags & FLAG_EMPH) ^ (oflags & FLAG_EMPH) != 0 {
1399 distance += 1;
1400 }
1401 distance
1402 }
1403
1404 pub fn font_attribute_string(&self) -> String {
1409 let mut parts = Vec::new();
1410 if let Some(ref fam) = self.family {
1411 let f = if fam == "math" { "serif" } else { fam.as_ref() };
1412 if f != DEFFAMILY {
1413 parts.push(f.to_string());
1414 }
1415 }
1416 if let Some(ref ser) = self.series
1417 && ser.as_ref() != DEFSERIES
1418 {
1419 parts.push(ser.to_string());
1420 }
1421 if let Some(ref shp) = self.shape
1422 && shp.as_ref() != DEFSHAPE
1423 {
1424 parts.push(shp.to_string());
1425 }
1426 parts.join(" ")
1427 }
1428
1429 pub fn relative_to(&self, other: &Font) -> HashMap<String, (String, Font)> {
1438 let family = match self.family {
1439 Some(ref fam) => {
1440 if fam == "math" {
1441 Some(Cow::Borrowed("serif"))
1442 } else {
1443 Some(fam.clone())
1444 }
1445 },
1446 None => None,
1447 };
1448 let other_family = match other.family {
1449 Some(ref fam) => {
1450 if fam == "math" {
1451 Some(Cow::Borrowed("serif"))
1452 } else {
1453 Some(fam.clone())
1454 }
1455 },
1456 None => None,
1457 };
1458 let mut diffs = vec![];
1459 let mut font_properties = Font::default();
1460 if is_diff(family.as_ref(), other_family.as_ref()) {
1461 diffs.push(family.clone().unwrap());
1462 font_properties.family = family;
1463 }
1464 if is_diff(self.series.as_ref(), other.series.as_ref()) {
1465 let series = self.series.clone().unwrap();
1466 diffs.push(series);
1467 font_properties.series.clone_from(&self.series);
1468 }
1469 if is_diff(self.shape.as_ref(), other.shape.as_ref()) {
1470 let shape = self.shape.clone().unwrap();
1471 diffs.push(shape);
1472 font_properties.shape.clone_from(&self.shape);
1473 }
1474 let mut result = HashMap::default();
1475
1476 if !diffs.is_empty() {
1477 let font_value = diffs.join(" ");
1478 result.insert(s!("font"), (font_value, font_properties));
1479 }
1480
1481 if is_diff_f64(self.size.as_ref().copied(), other.size.as_ref().copied()) {
1482 result.insert(
1483 "fontsize".to_string(),
1484 (
1485 relative_font_size(self.size.unwrap(), other.size.unwrap()),
1486 Font {
1487 size: self.size,
1488 ..Font::default()
1489 },
1490 ),
1491 );
1492 }
1493 if is_diff_font_color_ref(self.color.as_ref(), other.color.as_ref()) {
1496 let effective_color = self.color.unwrap_or(DEFCOLOR);
1497 result.insert(
1498 "color".to_string(),
1499 (effective_color.to_attribute(), Font {
1500 color: Some(effective_color),
1501 ..Font::default()
1502 }),
1503 );
1504 }
1505 if is_diff_color(self.bg.as_ref(), other.bg.as_ref()) {
1506 result.insert(
1507 "backgroundcolor".to_string(),
1508 (self.bg.as_ref().unwrap().to_attribute(), Font {
1509 bg: self.bg,
1510 ..Font::default()
1511 }),
1512 );
1513 }
1514 if is_diff(self.opacity.as_ref(), other.opacity.as_ref()) {
1515 result.insert(
1516 "opacity".to_string(),
1517 (self.opacity.as_ref().unwrap().to_string(), Font {
1518 opacity: self.opacity.clone(),
1519 ..Font::default()
1520 }),
1521 );
1522 }
1523 if is_diff(self.language.as_ref(), other.language.as_ref()) {
1531 result.insert(
1532 "xml:lang".to_string(),
1533 (self.language.as_ref().unwrap().to_string(), Font {
1534 language: self.language.clone(),
1535 ..Font::default()
1536 }),
1537 );
1538 }
1539 let flags = self.flags.unwrap_or(0);
1541 let oflags = other.flags.unwrap_or(0);
1542 if self.mathstyle.is_none()
1543 && flags != 0
1544 && (flags & FLAG_EMPH) != 0
1545 && (oflags == 0 || (oflags & FLAG_EMPH) == 0)
1546 {
1547 result.insert(
1548 "element".to_string(),
1549 ("ltx:emph".to_string(), Font::default()),
1550 );
1551 }
1552 result
1554 }
1555
1556 pub fn purestyle_changes(&self, other: &Font) -> Font {
1557 let mathstyle = self.get_mathstyle();
1558 let othermathstyle = other.get_mathstyle();
1559 let othercolor = other.get_color();
1560 let mut changes = Font {
1561 scale: Some(other.get_size().unwrap() / self.get_size().unwrap()),
1562 bg: other.bg,
1563 opacity: other.opacity.clone(), ..Font::default()
1565 };
1566 if is_diff_font_color(othercolor, Some(&DEFCOLOR)) {
1567 changes.color = Some(othercolor.copied().unwrap_or(DEFCOLOR));
1568 }
1569
1570 if let Some(ms) = mathstyle
1571 && let Some(os) = othermathstyle
1572 {
1573 let ms_str: &str = ms;
1574 let os_str: &str = os;
1575 changes.mathstylestep = Some(*MATH_STYLE_STEP.get(ms_str).unwrap().get(os_str).unwrap());
1576 }
1577 changes
1578 }
1579
1580 fn nfss_restored(&self) -> Font {
1583 let mut base = self.clone();
1584 base.name = None;
1585 base.nfss_font = None;
1586 if let Some(nfss) = &self.nfss_font {
1587 base.family = nfss.family.clone();
1588 base.series = nfss.series.clone();
1589 base.shape = nfss.shape.clone();
1590 base.size = nfss.size;
1591 base.encoding = nfss.encoding.clone();
1592 }
1593 base
1594 }
1595
1596 pub fn measuring_tfm(&self) -> Option<Rc<tfm::Tfm>> {
1601 let name = self.name.as_deref()?;
1602 let family = self.family.as_deref().unwrap_or("serif");
1603 let series = self.series.as_deref().unwrap_or("medium");
1604 let shape = self.shape.as_deref().unwrap_or("upright");
1605 if lookup_metric_name(family, series, shape).is_some() {
1606 return None;
1607 }
1608 let named = NAMED_FONT_CLASS.with(|cache| {
1609 cache
1610 .borrow_mut()
1611 .entry(name.to_string())
1612 .or_insert_with(|| decode_fontname(name, None, None).map(|f| (f.family, f.encoding)))
1613 .clone()
1614 })?;
1615 if named != (self.family.clone(), self.encoding.clone()) {
1616 return None;
1617 }
1618 tfm::tfm_for(name)
1619 }
1620
1621 pub fn get_metric(&self, c_opt: Option<char>) -> &MetricData {
1626 let family = self.family.as_deref().unwrap_or("serif");
1627 let series = self.series.as_deref().unwrap_or("medium");
1628 let shape = self.shape.as_deref().unwrap_or("upright");
1629 let size = self.size.unwrap_or_else(defsize) as i64;
1630 let mut ch_buf = [0u8; 4];
1634 let ch_key = c_opt.map(|c| c.encode_utf8(&mut ch_buf) as &str);
1635 if let Some(name) = lookup_metric_name(family, series, shape) {
1636 let fullname = format!("{name}{size}");
1637 if let Some(metric) = STDMETRICS.get(fullname.as_str())
1638 && ch_key.is_none_or(|k| metric.sizes.contains_key(k))
1639 {
1640 return metric;
1641 }
1642 let metric = get_metric_for_name(name);
1644 if ch_key.is_none_or(|k| metric.sizes.contains_key(k)) {
1645 return metric;
1646 }
1647 }
1648 if let Some(k) = ch_key {
1650 for name in METRIC_FALLBACKS {
1651 let fullname = format!("{name}{size}");
1652 let metric = STDMETRICS
1653 .get(fullname.as_str())
1654 .unwrap_or_else(|| get_metric_for_name(name));
1655 if metric.sizes.contains_key(k) {
1656 return metric;
1657 }
1658 }
1659 }
1660 get_metric_for_name("cmr")
1661 }
1662
1663 pub fn get_em_width(&self) -> i64 {
1664 let size = self.get_size().unwrap_or_else(defsize);
1665 let m = self.get_metric(None);
1666 (size * m.emwidth).trunc() as i64
1667 }
1668 pub fn get_ex_height(&self) -> i64 {
1669 let size = self.get_size().unwrap_or_else(defsize);
1670 let m = self.get_metric(None);
1671 (size * m.exheight).trunc() as i64
1672 }
1673 pub fn get_mu_width(&self) -> i64 {
1674 let size = self.get_size().unwrap_or_else(defsize);
1675 let m = self.get_metric(None);
1676 (size * m.emwidth / 18.0).trunc() as i64
1677 }
1678
1679 pub fn compute_string_size(
1680 &self,
1681 text: &str,
1682 _options: SymHashMap<Stored>,
1683 ) -> (Dimension, Dimension, Dimension) {
1684 if text.is_empty()
1685 || self
1686 .get_family()
1687 .map(|fam| fam == "nullfont")
1688 .unwrap_or(false)
1689 {
1690 return (
1691 Dimension::default(),
1692 Dimension::default(),
1693 Dimension::default(),
1694 );
1695 }
1696 let size = self.get_size().unwrap_or_else(defsize);
1697 let ismath = self.get_family().map(|fam| fam == "math").unwrap_or(false);
1698 let (mut w, mut h, mut d) = (0, 0, 0);
1699 let mut chars_iter = text.chars().peekable();
1702 let mut ch_buf = [0u8; 4];
1707 let mut kern_buf = [0u8; 8];
1708 while let Some(ch) = chars_iter.next() {
1709 let metric = self.get_metric(Some(ch));
1710 let ch_key = ch.encode_utf8(&mut ch_buf);
1711 let entry_opt = metric.sizes.get(ch_key);
1712 let (cw, ch_sz, cd, ci) = if let Some(entry) = entry_opt {
1713 *entry
1714 } else {
1715 (0.75 * UNITY_F64, 0.7 * UNITY_F64, 0.2 * UNITY_F64, 0.0)
1716 };
1717 w += (cw * size).trunc() as i64;
1718 if let Some(&next_ch) = chars_iter.peek() {
1720 let first_len = ch.encode_utf8(&mut kern_buf).len();
1721 let second_len = next_ch.encode_utf8(&mut kern_buf[first_len..]).len();
1722 let kern_key = std::str::from_utf8(&kern_buf[..first_len + second_len]).unwrap();
1723 if let Some(kern) = metric.kerns.get(kern_key) {
1724 w += (size * kern).trunc() as i64;
1725 }
1726 }
1727 if ismath && ci != 0.0 {
1729 w += (size * ci).trunc() as i64;
1730 }
1731 h = max(h, (ch_sz * size).trunc() as i64);
1732 d = max(d, (cd * size).trunc() as i64);
1733 }
1734 if w == 0 {
1737 w = 1;
1738 }
1739 (Dimension::new(w), Dimension::new(h), Dimension::new(d))
1740 }
1741
1742 pub fn get_nominal_size(&self) -> (Dimension, Dimension, Dimension) {
1745 let size = self.get_size().unwrap_or_else(defsize);
1746 let u = size * UNITY_F64;
1747 (
1748 Dimension::new_f64(0.75 * u),
1749 Dimension::new_f64(0.7 * u),
1750 Dimension::new_f64(0.2 * u),
1751 )
1752 }
1753
1754 pub fn compute_boxes_size(
1774 &self,
1775 boxes: &[Digested],
1776 options: SymHashMap<Stored>,
1777 ) -> Result<(Dimension, Dimension, Dimension)> {
1778 if let [single] = boxes
1790 && !matches!(single.data(), DigestedData::List(_))
1791 {
1792 let mut bx_clone = single.clone();
1793 let (w, h, d, ..) = bx_clone.get_size(None)?;
1794 return Ok((w, h, d));
1795 }
1796 let mode_str = match options.get("mode") {
1798 Some(Stored::String(s)) => arena::with(*s, |s| s.to_string()),
1799 _ => "restricted_horizontal".to_string(),
1800 };
1801 let vattach = match options.get("vattach") {
1803 Some(Stored::String(s)) => arena::with(*s, |s| s.to_string()),
1804 _ => "baseline".to_string(),
1805 };
1806 let para_width: Option<i64> = if mode_str.ends_with("horizontal") {
1812 match options.get("width") {
1813 Some(Stored::Dimension(d)) => Some(d.value_of()),
1814 Some(Stored::Int(i)) => Some(*i),
1815 _ => None,
1816 }
1817 } else {
1818 None
1819 };
1820 let baseline: i64 = match options.get("baseline") {
1822 Some(Stored::Dimension(d)) => d.value_of(),
1823 Some(Stored::Int(i)) => *i,
1824 _ => 12 * UNITY,
1825 };
1826 let mut maxwidth: i64 = 0;
1827 let mut lines: Vec<[i64; 4]> = Vec::new();
1830 if mode_str.ends_with("vertical") {
1831 for bx in boxes {
1837 if bx.get_property_bool("isPenalty") {
1839 if lines.is_empty() && vattach == "top" {
1840 lines.push([-1, 0, 0, 0]);
1841 }
1842 continue;
1843 }
1844 if bx.has_property("isEmpty") {
1845 continue;
1846 }
1847 if matches!(bx.data(), DigestedData::List(_))
1849 && bx
1850 .get_property("mode")
1851 .map(|v| v.to_string())
1852 .unwrap_or_default()
1853 == "horizontal"
1854 && let Some(w) = bx.get_property("width").and_then(|v| match &*v {
1855 Stored::Dimension(d) => Some(d.value_of()),
1856 Stored::Int(i) => Some(*i),
1857 _ => None,
1858 })
1859 {
1860 if w > maxwidth {
1861 maxwidth = w;
1862 }
1863 let sub_baseline = bx
1864 .get_property("baseline")
1865 .and_then(|v| match &*v {
1866 Stored::Dimension(d) => Some(d.value_of()),
1867 Stored::Int(i) => Some(*i),
1868 _ => None,
1869 })
1870 .unwrap_or(baseline);
1871 let items = bx.unlist();
1872 if items.is_empty() {
1873 lines.push([sub_baseline, w, 0, 0]);
1876 } else {
1877 lines.extend(self.linebreak_paragraph(&items, w, sub_baseline)?);
1878 }
1879 continue;
1880 }
1881 let (w, h, d) = self.compute_boxes_size_box(bx)?;
1894 let bs = if bx.get_property_bool("isHorizontalRule") {
1895 -2
1896 } else if bx.get_property_bool("isVerticalSpace") {
1897 -1
1898 } else {
1899 baseline
1900 };
1901 let leading_skip = bs == -1 && lines.is_empty() && vattach == "top";
1904 if w != 0 || h != 0 || d != 0 || leading_skip {
1905 lines.push([bs, w, h, d]);
1906 }
1907 }
1908 } else if let Some(w) = para_width {
1909 if w > maxwidth {
1911 maxwidth = w;
1912 }
1913 let flat: Vec<&Digested> = boxes
1914 .iter()
1915 .filter(|b| !b.has_property("isEmpty"))
1916 .collect();
1917 let flat_owned: Vec<Digested> = flat.into_iter().cloned().collect();
1918 lines = self.linebreak_paragraph(&flat_owned, w, baseline)?;
1919 } else {
1920 let filtered: Vec<&Digested> = boxes
1922 .iter()
1923 .filter(|b| !b.has_property("isEmpty"))
1924 .collect();
1925 let words = self.compute_boxes_size_words(&filtered)?;
1926 lines = Self::compute_boxes_size_lines(None, baseline, &words);
1927 }
1928 let size = self.get_size().unwrap_or_else(defsize) as i64;
1930 let mathaxis = size * UNITY / 4;
1931 static SIZE_TRACE: LazyLock<bool> = LazyLock::new(|| std::env::var("LXML_SIZE_TRACE").is_ok());
1932 if *SIZE_TRACE {
1933 eprintln!(
1934 "SIZE mode={mode_str} vattach={vattach} baseline={} nboxes={} lines={:?}",
1935 baseline as f64 / 65536.0,
1936 boxes.len(),
1937 lines
1938 .iter()
1939 .map(|l| [
1940 l[0] as f64 / 65536.0,
1941 l[1] as f64 / 65536.0,
1942 l[2] as f64 / 65536.0,
1943 l[3] as f64 / 65536.0
1944 ])
1945 .collect::<Vec<_>>()
1946 );
1947 }
1948 let skip_option = |key: &str| match options.get(key) {
1949 Some(Stored::Dimension(d)) => Some(d.value_of()),
1950 Some(Stored::Int(i)) => Some(*i),
1951 _ => None,
1952 };
1953 let interline = (skip_option("lineskip"), skip_option("lineskiplimit"));
1954 let (mut wd, mut ht, mut dp) =
1955 Self::compute_boxes_size_stack(&vattach, mathaxis, &lines, interline);
1956 if wd != 0 && maxwidth != 0 && !matches!(options.get("natural_width"), Some(Stored::Bool(true)))
1959 {
1960 wd = maxwidth;
1961 }
1962 if let Some(th) = options.get("totalheight").and_then(|v| match v {
1964 Stored::Dimension(d) => Some(d.value_of()),
1965 Stored::Int(i) => Some(*i),
1966 _ => None,
1967 }) {
1968 let diff = th - ht - dp;
1969 if diff > 0 {
1970 match vattach.as_str() {
1971 "bottom" => ht += diff,
1972 "middle" => {
1973 ht += diff / 2;
1974 dp += diff / 2;
1975 },
1976 _ => dp += diff,
1977 }
1978 }
1979 }
1980 Ok((Dimension::new(wd), Dimension::new(ht), Dimension::new(dp)))
1981 }
1982
1983 fn linebreak_paragraph(
1987 &self,
1988 boxes: &[Digested],
1989 width: i64,
1990 baseline: i64,
1991 ) -> Result<Vec<[i64; 4]>> {
1992 let flat = Self::flatten_paragraph(boxes);
1993 let flat_refs: Vec<&Digested> = flat.iter().collect();
1994 let words = self.compute_boxes_size_words(&flat_refs)?;
1995 Ok(Self::compute_boxes_size_lines(
1996 Some(width),
1997 baseline,
1998 &words,
1999 ))
2000 }
2001
2002 fn flatten_paragraph(boxes: &[Digested]) -> Vec<Digested> {
2006 let mut queue: std::collections::VecDeque<Digested> = boxes.iter().cloned().collect();
2007 let mut out: Vec<Digested> = Vec::new();
2008 while let Some(bx) = queue.pop_front() {
2009 if matches!(bx.data(), DigestedData::List(_))
2011 && !is_finished_paragraph(&bx)
2012 && bx
2013 .get_property("mode")
2014 .map(|v| v.to_string())
2015 .unwrap_or_default()
2016 == "horizontal"
2017 {
2018 for ib in bx.unlist().into_iter().rev() {
2019 queue.push_front(ib);
2020 }
2021 } else if matches!(bx.data(), DigestedData::Whatsit(_))
2022 && let Some(repl) = flatten_for_sizing(&bx)
2023 {
2024 for ib in repl.into_iter().rev() {
2025 queue.push_front(ib);
2026 }
2027 } else {
2028 out.push(bx);
2029 }
2030 }
2031 out
2032 }
2033
2034 fn compute_boxes_size_box(&self, bx: &Digested) -> Result<(i64, i64, i64)> {
2037 let mut bx_clone = bx.clone();
2039 let (w, h, d, ..) = bx_clone.get_size(None)?;
2040 Ok((w.value_of(), h.value_of(), d.value_of()))
2041 }
2042
2043 fn declares_height_or_depth(bx: &Digested) -> bool {
2045 ["height", "depth"].iter().any(|key| {
2046 bx.get_property(key)
2047 .is_some_and(|v| matches!(&*v, Stored::Dimension(d) if d.value_of() != 0))
2048 })
2049 }
2050
2051 fn compute_boxes_size_words(&self, boxes: &[&Digested]) -> Result<Vec<[f64; 4]>> {
2055 let mut words: Vec<[f64; 4]> = Vec::new();
2056 let mut prevbox: Option<&Digested> = None;
2057 let mut prevspace: f64 = 0.0;
2058 let size = self.get_size().unwrap_or_else(defsize) as i64;
2060 let (mut wd, mut ht, mut dp): (f64, i64, i64) = (0.0, 0, 0);
2061 for bx in boxes {
2062 let (w, h, d) = self.compute_boxes_size_box(bx)?;
2063 if bx.get_property_bool("isBreak") {
2065 if bx.get_property_bool("isVerticalSpace") {
2069 ht = max(ht, h);
2070 dp = max(dp, d);
2071 }
2072 if wd != 0.0 || ht != 0 || dp != 0 || prevspace > 0.0 {
2073 words.push([prevspace, wd, ht as f64, dp as f64]);
2074 wd = 0.0;
2075 ht = 0;
2076 dp = 0;
2077 prevspace = -1.0;
2078 } else {
2079 prevspace = -1.0;
2080 }
2081 }
2082 else if bx.get_property_bool("isSpace")
2087 && !bx.get_property_bool("isVerticalSpace")
2088 && !Self::declares_height_or_depth(bx)
2089 {
2090 if wd != 0.0 || ht != 0 || dp != 0 || prevspace < 0.0 {
2091 words.push([prevspace, wd, ht as f64, dp as f64]);
2092 wd = 0.0;
2093 ht = 0;
2094 dp = 0;
2095 prevspace = w as f64;
2096 } else {
2097 prevspace += w as f64;
2098 }
2099 }
2100 else if is_finished_paragraph(bx) {
2104 if wd != 0.0 || ht != 0 || dp != 0 {
2105 words.push([prevspace, wd, ht as f64, dp as f64]);
2106 }
2107 if h != 0 || d != 0 {
2108 words.push([-1.0, w as f64, h as f64, d as f64]);
2109 }
2110 wd = 0.0;
2111 ht = 0;
2112 dp = 0;
2113 prevspace = -1.0;
2114 }
2115 else if bx.get_property_bool("isIdeographic") {
2117 if wd != 0.0 {
2118 words.push([prevspace, wd, ht as f64, dp as f64]);
2119 }
2120 words.push([0.0, w as f64, h as f64, d as f64]);
2121 wd = 0.0;
2122 ht = 0;
2123 dp = 0;
2124 prevspace = 0.0;
2125 }
2126 else {
2128 wd += w as f64;
2129 ht = max(ht, h);
2130 dp = max(dp, d);
2131 if let Some(pb) = prevbox
2133 && matches!(pb.data(), DigestedData::TBox(_))
2134 && matches!(bx.data(), DigestedData::TBox(_))
2135 {
2136 let prevchar = pb.get_string()?.chars().last();
2137 let curchar = bx.get_string()?.chars().next();
2138 let metric = self.get_metric(curchar);
2139 if let Some(family) = self.get_family()
2141 && family == "math"
2142 {
2143 wd += self.math_bearing(bx, pb);
2144 }
2145 if let Some(prevc) = prevchar
2147 && let Some(curc) = curchar
2148 {
2149 let kern_key = String::from(prevc) + &String::from(curc);
2150 if let Some(kern) = metric.kerns.get(kern_key.as_str()) {
2151 wd += size as f64 * kern;
2152 }
2153 }
2154 }
2155 }
2156 prevbox = Some(bx);
2158 }
2159 if wd != 0.0 || ht != 0 || dp != 0 || prevspace != 0.0 {
2161 words.push([prevspace, wd, ht as f64, dp as f64]);
2162 }
2163 Ok(words)
2164 }
2165
2166 fn compute_boxes_size_lines(
2170 wrapwidth: Option<i64>,
2171 baseline: i64,
2172 words: &[[f64; 4]],
2173 ) -> Vec<[i64; 4]> {
2174 let mut lines: Vec<[i64; 4]> = Vec::new();
2175 let fuzz = UNITY as f64; let (mut wd, mut ht, mut dp): (f64, i64, i64) = (0.0, 0, 0);
2177 for item in words {
2178 let (space, w, h, d) = (item[0], item[1], item[2] as i64, item[3] as i64);
2179 if space == -1.0 || wrapwidth.is_some_and(|ww| wd + space * 0.5 + w > ww as f64 + fuzz) {
2181 if wd != 0.0 {
2182 lines.push([baseline, kround(wd), ht, dp]);
2183 }
2184 wd = w;
2185 ht = h;
2186 dp = d;
2187 } else {
2188 wd += space + w;
2189 ht = max(ht, h);
2190 dp = max(dp, d);
2191 }
2192 }
2193 if wd != 0.0 || ht != 0 || dp != 0 {
2194 lines.push([baseline, kround(wd), ht, dp]);
2195 }
2196 lines
2197 }
2198
2199 fn compute_boxes_size_stack(
2203 vattach: &str,
2204 mathaxis: i64,
2205 lines: &[[i64; 4]],
2206 (lineskip, lineskiplimit): (Option<i64>, Option<i64>),
2207 ) -> (i64, i64, i64) {
2208 let nlines = lines.len();
2209 if nlines == 0 {
2210 return (0, 0, 0);
2211 }
2212 let leading_skip = vattach == "top" && lines[0][0] == -1;
2215 if nlines == 1 && !leading_skip {
2216 let [_bs, w, h, d] = lines[0];
2217 return (w, h, d);
2218 }
2219 let register = |cs: &str| {
2221 lookup_definition(&T_CS!(cs))
2222 .ok()
2223 .flatten()
2224 .and_then(|def| def.value_of(Vec::new()))
2225 .map(|v| v.value_of())
2226 .unwrap_or(0)
2227 };
2228 let lineskip = lineskip.unwrap_or_else(|| register("\\lineskip"));
2229 let lineskiplimit = lineskiplimit.unwrap_or(0);
2233 let mut wd: i64 = 0;
2234 let mut prevdepth: i64 = -99999;
2235 let mut th: i64 = 0;
2236 for line in lines {
2237 let [bs, w, h, d] = *line;
2238 wd = max(w, wd);
2239 th += h + d;
2240 if prevdepth >= 0 && bs >= 0 {
2243 let gap = bs - prevdepth - h;
2244 th += if gap >= lineskiplimit { gap } else { lineskip };
2245 }
2246 prevdepth = if bs >= 0 {
2252 d
2253 } else if bs == -1 {
2254 prevdepth
2255 } else {
2256 -99999
2257 };
2258 }
2259 let (ht, dp) = match vattach {
2260 "middle" => (th / 2 + mathaxis, th / 2 - mathaxis),
2261 "bottom" => {
2262 let d = lines[nlines - 1][3];
2263 (th - d, d)
2264 },
2265 _ if leading_skip => (0, th),
2266 _ => {
2268 let h = lines[0][2];
2269 (h, th - h)
2270 },
2271 };
2272 (wd, ht, dp)
2273 }
2274}
2275
2276fn flatten_for_sizing(_w: &Digested) -> Option<Vec<Digested>> { None }
2282
2283fn is_diff(x: Option<&Cow<str>>, y: Option<&Cow<str>>) -> bool {
2284 x.is_some() && (y.is_none() || (x != y))
2285}
2286
2287fn is_diff_opt_str(x: Option<&str>, y: Option<&str>) -> bool {
2288 x.is_some() && (y.is_none() || (x != y))
2289}
2290
2291fn is_diff_f64(x: Option<f64>, y: Option<f64>) -> bool { x.is_some() && (y.is_none() || (x != y)) }
2292
2293fn is_diff_color(x: Option<&Color>, y: Option<&Color>) -> bool {
2294 x.is_some() && (y.is_none() || (x != y))
2295}
2296
2297fn is_diff_font_color(x: Option<&Color>, y: Option<&Color>) -> bool {
2300 let cx = x.unwrap_or(&DEFCOLOR);
2301 let cy = y.unwrap_or(&DEFCOLOR);
2302 if cx == cy {
2303 return false;
2304 }
2305 cx.to_rgb() != cy.to_rgb()
2306}
2307
2308fn is_diff_font_color_ref(x: Option<&Color>, y: Option<&Color>) -> bool {
2315 let cx = x.unwrap_or(&DEFCOLOR);
2316 let cy = y.unwrap_or(&DEFCOLOR);
2317 cx != cy
2318}
2319
2320pub fn match_font(font1: &str, font2: &str) -> bool {
2324 if let Some(inner) = font1
2326 .strip_prefix("Font[")
2327 .and_then(|s| s.strip_suffix(']'))
2328 {
2329 let comps: Vec<&str> = inner.split(',').collect();
2330 let re_str = format!(
2331 "^Font\\[{}\\]$",
2332 comps
2333 .iter()
2334 .map(|c| if *c == "*" {
2335 "[^,]+".to_string()
2336 } else {
2337 regex::escape(c)
2338 })
2339 .collect::<Vec<_>>()
2340 .join(",")
2341 );
2342 if let Ok(re) = Regex::new(&re_str) {
2343 return re.is_match(font2);
2344 }
2345 }
2346 false
2347}
2348
2349pub fn font_match_xpaths(font: &str) -> String {
2352 if let Some(inner) = font.strip_prefix("Font[").and_then(|s| s.strip_suffix(']')) {
2353 let comps: Vec<&str> = inner.split(',').collect();
2354 let mut frags: Vec<String> = Vec::new();
2356 if !comps.is_empty() && comps[0] != "*" {
2357 frags.push(format!("[{},", comps[0]));
2358 }
2359 if comps.len() > 1 && comps[1] != "*" {
2360 frags.push(format!(",{},", comps[1]));
2361 }
2362 if comps.len() > 2 && comps[2] != "*" {
2363 frags.push(format!(",{},", comps[2]));
2364 }
2365 let mut parts: Vec<String> = vec!["@_font".to_string()];
2366 for frag in frags {
2367 parts.push(format!("contains(@_font,'{frag}')"));
2368 }
2369 parts.join(" and ")
2370 } else {
2371 "@_font".to_string()
2372 }
2373}
2374
2375fn push_fontmap_char(result: &mut String, c: char, _code: u8) {
2389 if c == '\u{1E9E}' {
2391 result.push_str("SS");
2392 return;
2393 }
2394 if is_combining_mark(c) {
2397 result.push('\u{00A0}');
2398 }
2399 result.push(c);
2400}
2401
2402pub fn is_combining_mark(c: char) -> bool {
2404 matches!(c as u32,
2405 0x0300..=0x036F | 0x1AB0..=0x1AFF | 0x1DC0..=0x1DFF | 0x20D0..=0x20FF | 0xFE20..=0xFE2F )
2411}
2412
2413pub fn decode_char_code(code: i64, cs: Option<&str>) -> Option<SymStr> {
2419 if let Ok(byte) = u8::try_from(code) {
2420 return decode_str(byte, None, false);
2421 }
2422 let c = u32::try_from(code).ok().and_then(char::from_u32)?;
2423 if let Some(cs) = cs
2424 && !unicode_engine_profile()
2425 {
2426 crate::Warn!(
2427 "unexpected",
2428 cs,
2429 format!(
2430 "Character code \"{code:X} ({code}) is above 255: kept as U+{code:04X} {c}, \
2431 where pdfTeX reports \"Bad character code\""
2432 )
2433 );
2434 }
2435 Some(arena::pin_char(c))
2436}
2437
2438pub fn decode_str(code: u8, encoding_opt: Option<String>, implicit: bool) -> Option<SymStr> {
2441 if let Some(s) = lookup_multichar_override(code, encoding_opt.as_deref()) {
2443 return Some(arena::pin(s));
2444 }
2445 if let Some(c) = decode(code, encoding_opt, implicit) {
2446 if c == '\u{1E9E}' {
2448 return Some(pin!("SS"));
2449 }
2450 if is_combining_mark(c) {
2453 return Some(arena::pin(format!("\u{00A0}{c}")));
2454 }
2455 Some(arena::pin_char(c))
2456 } else {
2457 None
2458 }
2459}
2460
2461fn lookup_multichar_override(code: u8, encoding_opt: Option<&str>) -> Option<String> {
2464 let mut font = None;
2465 let encoding = match encoding_opt {
2466 Some(enc) if !enc.is_empty() => enc.to_string(),
2467 _ => {
2468 font = lookup_font();
2469 font
2470 .as_ref()
2471 .and_then(|f| f.get_encoding().map(|e| e.to_string()))?
2472 },
2473 };
2474 if encoding.is_empty() {
2475 return None;
2476 }
2477 let _ = preload_font_map(&encoding);
2491 with_value_sym(decoding_map(&encoding, font.as_deref()).1, |val_opt| {
2492 if let Some(Stored::HashString(map)) = val_opt {
2493 map.get(&code.to_string()).cloned()
2494 } else {
2495 None
2496 }
2497 })
2498}
2499
2500fn decoding_map(encoding: &str, font: Option<&Font>) -> (Option<Fontmap>, SymStr) {
2509 let map = load_font_map(encoding);
2511 if let Some(family) = font.and_then(|font| font.get_family()) {
2512 let (family_map_key, family_multichar_key) = fontmap_family_key_syms(encoding, family);
2513 let family_map: Option<Fontmap> = with_value_sym(family_map_key, |v| v.and_then(|s| s.into()));
2514 if family_map.is_some() {
2515 return (family_map, family_multichar_key);
2516 }
2517 }
2518 (map, fontmap_key_syms(encoding).multichar)
2519}
2520
2521pub fn decode(code: u8, encoding_opt: Option<String>, implicit: bool) -> Option<char> {
2522 let mut font = None;
2523 let encoding = match encoding_opt {
2524 Some(enc) => Cow::Owned(enc),
2525 None => {
2526 font = lookup_font();
2540 if let Some(ref font) = font {
2541 match font.get_encoding() {
2542 None => Cow::Borrowed("OT1"),
2543 Some(encoding) => encoding.clone(),
2544 }
2545 } else {
2546 Cow::Borrowed("OT1")
2547 }
2548 },
2549 };
2550
2551 decode_with_map(code, &encoding, font.as_deref(), implicit)
2552}
2553
2554pub fn decode_in_font(code: u8, encoding: &str, font: &Font, implicit: bool) -> Option<char> {
2559 decode_with_map(code, encoding, Some(font), implicit)
2560}
2561
2562fn decode_with_map(code: u8, encoding: &str, font: Option<&Font>, implicit: bool) -> Option<char> {
2563 let map = if encoding.is_empty() {
2564 None
2565 } else {
2566 decoding_map(encoding, font).0
2567 };
2568
2569 if implicit {
2570 if let Some(map) = map {
2571 if code < 128 {
2572 match map.get(code as usize) {
2573 None => None,
2574 Some(c) => *c,
2575 }
2576 } else {
2577 Some(code.into())
2578 }
2579 } else {
2580 Some(code.into())
2581 }
2582 } else if let Some(map) = map {
2583 match map.get(code as usize) {
2584 None => None,
2585 Some(c) => *c,
2586 }
2587 } else {
2588 None
2589 }
2590}
2591
2592pub fn decode_string(string: SymStr, encoding_opt: Option<&str>, implicit: bool) -> SymStr {
2593 let empty_sym = pin!("");
2594 if string == empty_sym {
2595 return empty_sym;
2596 }
2597 let mut font = None;
2598 let encoding = match encoding_opt {
2599 None => {
2600 font = lookup_font();
2601 if let Some(ref font) = font {
2602 font.get_encoding().unwrap_or(&Cow::Borrowed(""))
2603 } else {
2604 ""
2605 }
2606 },
2607 Some(encoding) => encoding,
2608 };
2609
2610 let (map, multichar_key) = if encoding.is_empty() {
2615 (None, None)
2616 } else {
2617 let (map, multichar_key) = decoding_map(encoding, font.as_deref());
2618 (map, Some(multichar_key))
2619 };
2620
2621 let multichar_map: Option<HashMap<String, String>> = if let Some(multichar_key) = multichar_key {
2623 with_value_sym(multichar_key, |val_opt| {
2624 if let Some(Stored::HashString(m)) = val_opt {
2625 Some(m.clone())
2626 } else {
2627 None
2628 }
2629 })
2630 } else {
2631 None
2632 };
2633
2634 let mut result_string = DECODED.take();
2637 result_string.clear();
2638 let unchanged = arena::with(string, |str| {
2639 for c in str.chars() {
2640 if implicit {
2641 if let Some(ref map_ref) = map {
2642 match u8::try_from(c) {
2644 Ok(code) if code < 128 => {
2645 if let Some(ref mc) = multichar_map
2647 && let Some(mc_str) = mc.get(&code.to_string())
2648 {
2649 result_string.push_str(mc_str);
2650 continue;
2651 }
2652 if let Some(Some(mapc_val)) = map_ref.get(code as usize) {
2653 push_fontmap_char(&mut result_string, *mapc_val, code);
2654 }
2655 },
2656 _ => result_string.push(c),
2657 }
2658 } else {
2659 result_string.push(c)
2660 }
2661 } else if let Some(ref map_ref) = map {
2662 let Ok(code) = u8::try_from(c) else {
2664 continue;
2665 };
2666 if let Some(ref mc) = multichar_map
2668 && let Some(mc_str) = mc.get(&code.to_string())
2669 {
2670 result_string.push_str(mc_str);
2671 continue;
2672 }
2673 if let Some(Some(mapc_val)) = map_ref.get(code as usize) {
2674 push_fontmap_char(&mut result_string, *mapc_val, code);
2675 }
2676 }
2677 }
2678 result_string == str
2679 });
2680 let decoded = if unchanged {
2681 string
2682 } else {
2683 arena::pin(result_string.as_str())
2684 };
2685 DECODED.set(result_string);
2686 decoded
2687}
2688
2689thread_local! {
2690 static DECODED: std::cell::Cell<String> = const { std::cell::Cell::new(String::new()) };
2692}
2693
2694pub fn rationalize_font_size(size: &str) -> f64 {
2696 if let Some(symbolic) = FONT_SIZE.get(size) {
2697 *symbolic * defsize()
2698 } else {
2699 size.parse::<f64>().unwrap_or_else(|_| defsize())
2701 }
2702}
2703
2704pub fn relative_font_size(newsize: f64, oldsize: f64) -> String {
2706 s!("{}%", (0.5 + 100.0 * newsize / oldsize).floor())
2707}
2708
2709fn is_finished_paragraph(bx: &Digested) -> bool {
2716 matches!(bx.data(), DigestedData::List(_))
2717 && bx.has_property("width")
2718 && bx
2719 .get_property("mode")
2720 .is_some_and(|mode| mode.to_string() == "horizontal")
2721}
2722
2723#[cfg(test)]
2724mod tests {
2725 use super::*;
2726
2727 #[test]
2728 fn relative_font_size_same_is_100() {
2729 assert_eq!(relative_font_size(10.0, 10.0), "100%");
2730 assert_eq!(relative_font_size(12.0, 12.0), "100%");
2731 }
2732
2733 #[test]
2734 fn relative_font_size_doubled_is_200() {
2735 assert_eq!(relative_font_size(20.0, 10.0), "200%");
2736 }
2737
2738 #[test]
2739 fn relative_font_size_half_is_50() {
2740 assert_eq!(relative_font_size(5.0, 10.0), "50%");
2741 }
2742
2743 #[test]
2748 fn defsize_preserves_fractional_nominal_font_size() {
2749 use crate::{
2750 common::float::Float,
2751 state::{State, StateOptions, assign_value, set_state},
2752 };
2753 set_state(State::new(StateOptions::default()));
2754 assert_eq!(defsize(), 10.0, "defsize defaults to 10 when unset");
2756 assign_value("NOMINAL_FONT_SIZE", Float(10.95), None);
2758 assert_eq!(
2759 defsize(),
2760 10.95,
2761 "defsize preserves the fractional 11pt size"
2762 );
2763 assign_value("NOMINAL_FONT_SIZE", Float(12.0), None);
2765 assert_eq!(defsize(), 12.0, "12pt reads back as 12.0");
2766 }
2767
2768 #[test]
2781 fn encoding_is_font_identity_but_not_distance_or_output() {
2782 use crate::state::{State, StateOptions, set_state};
2783 set_state(State::new(StateOptions::default()));
2784
2785 let base = Font::default();
2786 let mut t1 = base.clone();
2787 t1.encoding = Some(Cow::Borrowed("T1"));
2788 let mut ot1 = base.clone();
2789 ot1.encoding = Some(Cow::Borrowed("OT1"));
2790
2791 assert_ne!(
2793 t1, ot1,
2794 "fonts differing only in encoding must not be equal"
2795 );
2796 assert_ne!(
2797 t1.to_hashable(),
2798 ot1.to_hashable(),
2799 "differently-encoded fonts must get distinct `_font` ids"
2800 );
2801
2802 assert_eq!(
2804 t1.distance(&ot1),
2805 0,
2806 "encoding alone must not count as a font-switch distance"
2807 );
2808
2809 let rel = t1.relative_to(&ot1);
2812 assert!(
2813 rel.is_empty(),
2814 "relative_to must not emit @encoding (it leaks onto foreign xhtml); got {rel:?}"
2815 );
2816 }
2817
2818 #[test]
2819 fn match_font_exact_wildcard_tail() {
2820 assert!(match_font("Font[*,*,*,*]", "Font[rm,med,up,10]"));
2825 }
2826
2827 #[test]
2828 fn match_font_exact_match() {
2829 assert!(match_font("Font[rm,med,up,10]", "Font[rm,med,up,10]"));
2830 assert!(!match_font("Font[rm,med,up,10]", "Font[sf,med,up,10]"));
2831 }
2832
2833 #[test]
2834 fn match_font_partial_wildcard() {
2835 assert!(match_font("Font[*,med,up,10]", "Font[rm,med,up,10]"));
2837 assert!(match_font("Font[*,med,up,10]", "Font[sf,med,up,10]"));
2838 assert!(!match_font("Font[*,bold,up,10]", "Font[rm,med,up,10]"));
2840 }
2841
2842 #[test]
2843 fn match_font_malformed_input() {
2844 assert!(!match_font("not_a_font", "Font[rm,med,up,10]"));
2846 }
2847
2848 #[test]
2849 fn font_match_xpaths_all_wildcards_is_attr_only() {
2850 let xp = font_match_xpaths("Font[*,*,*,*]");
2851 assert_eq!(xp, "@_font");
2853 }
2854
2855 #[test]
2856 fn font_match_xpaths_includes_specified_components() {
2857 let xp = font_match_xpaths("Font[rm,bold,*,*]");
2858 assert!(xp.contains("@_font"));
2860 assert!(xp.contains("contains"));
2861 assert!(xp.contains("rm"));
2862 assert!(xp.contains("bold"));
2863 }
2864
2865 #[test]
2866 fn font_match_xpaths_malformed_is_empty_or_fallback() {
2867 let xp = font_match_xpaths("garbage");
2868 let _ = xp;
2872 }
2873}