Skip to main content

dxf/
fonts.rs

1// fonts -- which font of the repository stands in for a text style's font (decision 31: SHX fonts belong to Autodesk,
2// and there are no Microsoft fonts in the repository).  A substitute names a family (the caller has the bytes) and how
3// wide the original runs: the advance of the sample "a..z A..Z 0..9" over its cap height, from the original's metrics
4// (Helvetica / Arial, Times, Courier: their published advance widths; SHX fonts: estimates from their glyph grids,
5// docs/RENDER2D.md "DXF").  render2d::dxf turns that into a width factor against the substitute's own advance.
6
7/// a family of the fonts in the repository
8#[non_exhaustive]
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
10pub enum Family {
11    /// Inter (styles/netlab/assets): sans-serif, for Arial, Helvetica, Calibri, Verdana, Tahoma and every SHX font
12    Sans,
13    /// Inter SemiBold: bold sans-serif (Arial Black, "... Bold")
14    SansBold,
15    /// DejaVu Serif (lib/doc_view/assets): Times, Georgia, Cambria, Garamond, Book Antiqua
16    Serif,
17    SerifBold,
18    /// DejaVu Sans Mono: Courier, Consolas, Lucida Console, Source Code Pro, monotxt.shx
19    Mono,
20    MonoBold,
21    /// Selawik (styles/winui/assets): Segoe UI
22    Ui,
23}
24
25/// a font's stand-in
26#[non_exhaustive]
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub struct Substitute {
29    pub family: Family,
30    /// the original's advance of the sample "a..z A..Z 0..9" (62 characters) in cap heights; 0: keep the substitute's width
31    pub sample_advance: f64,
32    /// an SHX font (single strokes) or a shape file
33    pub shx: bool,
34}
35
36/// the sample whose advance sets the width factor of a substitute
37pub const SAMPLE: &str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
38
39// the originals' advances of SAMPLE in cap heights, from the advance widths of the Adobe font metrics (Arial and Times
40// New Roman have Helvetica's and Times' widths, Courier New Courier's):
41//   Helvetica: lower case 12.726 em, upper case 17.613, digits 5.560 -> 35.899 em / cap height 0.718 = 50.00
42//   Times:     lower case 11.943 em, upper case 17.332, digits 5.000 -> 34.275 em / cap height 0.662 = 51.78
43//   Courier:   62 x 0.600 = 37.2 em / cap height 0.571 (Courier New) = 65.15
44// SHX fonts (estimates, the fonts are not here): txt.shx draws on a grid of 6 units of cap height with an advance of 6
45// for most characters (4 for the narrow ones) -> about 0.95 cap heights each, 58.9; simplex / romans (Hershey's simplex
46// Roman: cap height 21, upper case about 20, lower case 18, digits 20) -> 0.92 each, 57.0; isocp / iso* (ISO 3098
47// type B lettering) -> 0.8 each, 49.6; monotxt -> 1.0 each, 62.0
48const HELVETICA: f64 = 50.0;
49const TIMES: f64 = 51.78;
50const COURIER: f64 = 65.15;
51const SHX_TXT: f64 = 58.9;
52const SHX_SIMPLEX: f64 = 57.0;
53const SHX_ISO: f64 = 49.6;
54const SHX_MONO: f64 = 62.0;
55
56/// the stand-in of a style's font file (3) or TrueType family (its XDATA), compared without case and path: TrueType
57/// names by their family, everything else (".shx", no extension, unknown) as an SHX font
58pub fn font_substitute(file: &str, family: Option<&str>) -> Substitute {
59    // the file's name without folders and without its extension
60    let base = file.rsplit(['/', '\\']).next().unwrap_or(file);
61    let lower: alloc::string::String = base.chars().map(|c| c.to_ascii_lowercase()).collect();
62    let (stem, ext) = match lower.rfind('.') {
63        Some(i) => (&lower[..i], &lower[i + 1..]),
64        None => (lower.as_str(), ""),
65    };
66    let fam: alloc::string::String = family.unwrap_or("").chars().map(|c| c.to_ascii_lowercase()).collect();
67    let ttf = matches!(ext, "ttf" | "otf" | "ttc") || (!fam.is_empty() && ext != "shx");
68    if !ttf {
69        let (w, family) = match stem {
70            "txt" | "txt_" => (SHX_TXT, Family::Sans),
71            "monotxt" => (SHX_MONO, Family::Mono),
72            s if s.starts_with("iso") => (SHX_ISO, Family::Sans),
73            _ => (SHX_SIMPLEX, Family::Sans),
74        };
75        return Substitute { family, sample_advance: w, shx: true };
76    }
77    let name = if fam.is_empty() { stem } else { fam.as_str() };
78    let has = |k: &str| name.contains(k);
79    // (Windows' file names of bold cuts: arialbd, timesbd, courbd, verdanab, calibrib, consolab, ariblk)
80    let bold = has("bold") || has("black") || has("heavy") || ["bd", "bi", "ab", "ib", "blk"].iter().any(|e| stem.ends_with(e));
81    let mono = ["cour", "consol", "lucon", "lucida console", "mono", "code", "menlo", "inconsolata"].iter().any(|k| has(k));
82    let serif = ["times", "georgia", "cambria", "garamond", "book", "roman", "palatino", "century", "bodoni", "bell"].iter().any(|k| has(k)) || (has("serif") && !has("sans"));
83    let (family, w) = if mono {
84        (if bold { Family::MonoBold } else { Family::Mono }, COURIER)
85    } else if serif {
86        (if bold { Family::SerifBold } else { Family::Serif }, TIMES)
87    } else if has("segoe") || stem.starts_with("seg") {
88        (Family::Ui, 0.0)
89    } else {
90        (if bold { Family::SansBold } else { Family::Sans }, HELVETICA)
91    };
92    // narrow and wide cuts of the sans fonts
93    let w = if has("narrow") || stem == "arialn" || stem.starts_with("arialn") { w * 0.82 } else { w };
94    Substitute { family, sample_advance: w, shx: false }
95}