![]() |
The smart font: dispatching characters to subfonts | ![]() |
Whenever one of the font related environment variables changes, the typesetter recomputes the current font in edit_env_rep::update_font (
Typeset/Env/env_semantics.cpp
). In text mode it calls the six argument version of smart_font with the values of font, font-family, font-series and font-shape; in mathematical mode and in program mode it calls the ten argument version, which receives both the mathematical (resp. program) font and the surrounding text font:
font edit_env_rep::make_current_font (int sz) {
switch (mode) {
case 2:
return smart_font (get_string (MATH_FONT), get_string (MATH_FONT_FAMILY),
get_string (MATH_FONT_SERIES), get_string (MATH_FONT_SHAPE),
get_string (FONT), get_string (FONT_FAMILY),
get_string (FONT_SERIES), "mathitalic",
sz, (int) (magn*dpi));
…
}
int sz= get_script_size (fn_size, index_level);
fn= make_current_font (sz);
… // OpenType MATH: script percentages and the ssty feature
string feat= get_string (FONT_FEATURES);
if (N(feat) != 0) fn= apply_features (fn, feat);
string eff= get_string (FONT_EFFECTS);
if (N(eff) != 0) fn= apply_effects (fn, eff); |
In scripts, a font with an OpenType MATH table is made again at the size given by the percentages of its table (unless math-font-sizes is set), and an untuned one is wrapped in a feature_font for its script size alternates (ssty); see mathematics from the MATH table and OpenType features.
Notice that the names of the environment variables are slightly misleading at this level: font is passed as the family argument of smart_font and font-family (rm, ss, tt, …) as the variant.
If the new style fonts are disabled (the global new_fonts is false), this falls back on the rule based find_font. Otherwise the font which is actually used is the text font tf, tv, tw, ts, adapted as follows: if the text family is roman, it is replaced by the mathematical family family; the mathematical variants ms and mt select the variants ss and tt; a mathematical series other than medium replaces the text series, so that a family with a real bold math face uses it; and if the mathematical shape is right, the shape becomes the special shape mathupright. The result is the six argument smart_font applied to the adapted text font. In mathematical mode ts is mathitalic, so that the main font is the upright text font and the smart font takes care of the mathematical conventions (see below). Mathematical fonts proper are therefore usually specified inside the family list of font, using conditional entries such as math=… or mathlarge=….
For the variant rm, this is just smart_font_bis (family, variant, series, shape, sz, dpi, dpi). For other variants, the routine first checks with logical_font and search_font whether the variant is provided by the same physical font as the rm variant. If not, it creates both smart fonts and magnifies the variant so that its x-height (yx) matches the one of the rm variant, unless the ratio is within 2.5% of one. This is why a sans serif or typewriter font taken from another family blends with the main text.
Builds (or retrieves from the font cache) the smart font with the given horizontal and vertical resolutions. Its name has the form family-variant-series-shape-sz-vdpi-smart (with both resolutions when they differ). The routine:
handles a few special cases: families starting with tc (legacy symbols of
std-symbol.ts
) go directly to find_font, and the families sys-chinese, sys-japanese and sys-korean are replaced by cjk=name,roman where name is the system default (default_chinese_font_name and friends in
Graphics/Fonts/font.cpp
);
normalizes the family list with tex_gyre_fix, kepler_fix, math_fix and profile_fix (see below);
replaces the shapes mathitalic and mathshape by right for the main font;
computes the main family with main_family and the base font closest_font (mfam, variant, series, sh, sz, vdpi);
computes the error font error_font (closest_font ("roman", "ss", "medium", "right", sz, vdpi));
constructs a smart_font_rep.
All other routines in
smart_font.cpp
which need a font with a different family, variant, series or shape call smart_font_bis again, so subfonts are often smart fonts themselves.
The family argument of a smart font is a comma separated list. Each entry is either a plain family name or a conditional entry of the form conditions=family. Examples from the style packages in
packages/customize/fonts/
and from the code are:
mathlarge=TeX Gyre Pagella,Linux Libertine mathlarge=TeX Gyre Pagella,cal=TeX Gyre Termes,bold-cal=TeX Gyre Termes,frak=TeX Gyre Pagella,Fira cjk=Apple SD Gothic Neo,roman |
The main family (main_family) is the first unconditional entry, or the family of the first entry if all entries are conditional. The conditions are a space separated list, all of which must hold; each condition is a |-separated list of alternatives, one of which must hold. The alternatives are tested in smart_font_rep::resolve (string c, string fam, int attempt) and may be:
a feature of the requested logical font, as computed by logical_font (family, variant, series, rshape); for instance bold, italic or mathitalic;
a Unicode range name as returned by get_unicode_range: ascii, latin, greek, cyrillic, cjk (which also accepts hangul and hiragana), hiragana, hangul, mathsymbols, mathextra, mathletters, or one of the pseudo ranges mathlarge, mathbigop (big operators) and mathrubber (wide accents and extensible delimiters), see in_unicode_range;
the name of a mathematical alphabet as returned by substitute_math_letter (c, 2), such as cal, bold-cal, frak, bbb, bold-math or ss: the condition holds for the corresponding Unicode mathematical alphanumeric symbols;
the character itself;
a character collection defined in init_collections: digit, lowercase-latin, uppercase-latin, latin, the corresponding -bold collections (characters <b-a> and so on), lowercase-greek, uppercase-greek, greek, their bold versions, and basic-letters (digits, Latin and Greek letters, plain and bold);
a collection name preceded by !, which holds for the characters not in that collection;
a code point range c1:c2, where c1 and c2 are characters.
If all conditions hold, family is tried for the character in the same way as an unconditional entry; otherwise the entry is skipped.
In mathematical shapes (math_fix), the condition math is removed from conditional entries, so that math=TeX Gyre Termes becomes the plain entry TeX Gyre Termes in mathematics and is ignored in text. The routines tex_gyre_fix and kepler_fix rename the short names bonum, pagella, schola, termes to the TeX Gyre families and append or remove the suffix Math according to whether a medium mathematical shape is requested, so that the dedicated OpenType math fonts are used in formulas and the text fonts elsewhere.
The last fix, profile_fix, generalizes this to the profiled OpenType math fonts (
math_font_profiles.cpp
). For each unconditional entry, in a mathematical shape a text family is replaced by the math font of its profile when that font is installed, and in a text shape a math family by its text companion; the variants ss and tt are replaced by the sans serif and typewriter companions which the profile declares, and the result is translated into its master (font_database_master), since the selection is driven by masters. A profiled font, or the text companion of one, which is installed but absent from the database is registered on the fly (register_profiled_font). See math font profiles, shipped fonts and the database.
struct smart_font_rep: font_rep {
string mfam; // main family
string family; // full family list
string variant;
string series;
string shape; // requested shape
string rshape; // "right" for the math shapes, otherwise shape
int sz;
int hdpi;
int dpi;
int math_kind; // 0: no math, 1: mathitalic, 2: mathupright, 3: mathshape
int italic_nr; // subfont for isolated italic letters
bool ot_math; // main font: untuned OpenType math font
array<font> fn; // the subfonts
smart_map sm; // shared character -> subfont table
array<int> origins; // debug switch "fonts": route of each subfont
…
}; |
The smart_map is a resource whose name is the concatenation of family, variant, series and shape (get_smart_map). Since the size and resolution are not part of the key, all smart fonts which only differ by size or zoom share one smart map, and characters are resolved only once per logical font. The map stores:
An array of trees describing the subfonts, such as ("main"), ("error"), ("TeX Gyre Pagella" "rm" "medium" "right" "1"), ("virtual" "tradi-long") or ("poor-bold"). Entries SUBFONT_MAIN= 0 and SUBFONT_ERROR= 1 always exist.
The inverse table, from specification to number.
For every subfont, the kind of rewriting (REWRITE_*, see below) which must be applied to strings before they are passed to it.
A table of 256 integers for the one-byte (Cork) characters, with -1 for “not yet resolved”.
A hash table for the universal symbols <…>, with default -1.
add_font (fn, rewr) registers a subfont specification and returns its number; add_char (fn, c) registers the font if needed and records that c is rendered by it. If a character is added twice, the smaller subfont number wins.
The actual fonts live in the array fn of each smart_font_rep. They are created on demand by smart_font_rep::initialize_font (nr) from the specification sm->fn_spec[nr]. Since the map is shared, a smart font may find in its map a subfont number for which its own fn array has no font yet; every user of a subfont number therefore checks N(fn) <= nr || is_nil (fn[nr]) and calls initialize_font first.
The constructor installs the main font and the error font (both horizontally magnified by adjust_subfont if hdpi != dpi) and copies the mathematical parameters of the base font (copy_math_pars). For the shapes mathitalic, mathupright and mathshape it does more. The flag ot_math is set when the base font has the math type MATH_TYPE_OPENTYPE (an OpenType math font without hand-tuned tables) and its profile does not say that the letters come from the text italic (key letters):
For the historical TeX families recognized by is_math_family (roman, concrete, Euler, ENR), the main font is replaced, except for mathupright, by a subfont ("math" mfam variant series "right") with rewriting REWRITE_MATH; this subfont is obtained from the rule based font selection (get_math_font, with the variant mr, ms or mt), which typically yields a math_font (see compound and math fonts).
For all other families, math_kind is set to 1, 2 or 3. For mathitalic and mathshape an italic subfont ("fast-italic") is created; its number is stored in italic_nr and its mathematical parameters are used for the smart font. When ot_math is set, the subfont of mathitalic is ("ot-italic") instead: it is the main font itself, with the rewriting REWRITE_MATH_ITALIC, which maps the Latin letters to the mathematical italic alphabet of Unicode (U+1D434 and following, with the Planck constant U+210E for h), so that the italic corrections and the cut-in kerns of the font apply to them. Then a fixed list of subfonts is pre-registered, so that they get the same numbers in all smart maps: special, emu-bracket, other, regular, the mathematical alphabets bold-math, italic-math, bold-italic-math, cal, bold-cal, frak, bold-frak, bbb, tt, ss, bold-ss, italic-ss, bold-italic-ss, and italic-roman.
The heart of the smart font is the routine
Starting at pos, scan the longest run of characters which are rendered by the same subfont. On return pos points after the run, nr is the subfont number (or -1) and r is the run, already rewritten according to sm->fn_rewr[nr].
For every character, the subfont is first looked up in chv (one byte characters) or cht (universal symbols, delimited with tm_char_forwards); if the entry is -1, the full resolution algorithm resolve (c) is run, which fills the table. A few special rules apply while building a run:
If math_kind is 1 or 3, an ASCII letter which has no alphabetic neighbour in the string is sent to the italic subfont italic_nr. This is how the variable \(x\) is rendered in italic while the operator name sin (a single string of three letters) stays upright.
If the second one-byte character of a run belongs to a subfont with rewriting REWRITE_SPECIAL, the run is cut, so that strings like --- are rewritten character by character.
If the second universal symbol of a run belongs to the same subfont, the run is only extended if the subfont supports the two-symbol string as a whole; otherwise the symbols are processed separately.
All the public routines of the smart font are written in terms of advance:
void
smart_font_rep::draw_fixed (renderer ren, string s, SI x, SI y) {
int i=0, n= N(s);
while (i < n) {
int nr;
string r= s;
metric ey;
advance (s, i, r, nr);
if (nr >= 0) {
fn[nr]->draw_fixed (ren, r, x, y);
if (i < n) {
fn[nr]->get_extents (r, ey);
x += ey->x2;
}
}
}
} |
get_extents combines the metrics of the successive runs: the logical widths are added, the vertical logical and ink extents are merged. get_xpositions fills the array of cursor positions; when a run was rewritten (so that the rewritten string r has a different length than the original run), the positions inside the run are set to the start of the run and only the end position is taken from the subfont. The kerning variants with an extra argument xk are implemented in the same way.
The slopes and corrections used by the mathematical typesetter are delegated to the subfont of the first run (get_left_slope, get_left_correction, get_lsub_correction, get_lsup_correction) or of the last run (get_right_slope, get_right_correction, get_rsub_correction, get_rsup_correction, get_wide_correction), and so are the height dependent script corrections get_lsub_correction_at, …, get_rsup_correction_at. The questions which concern a single glyph (get_top_accent, is_extended_shape, get_feature_variant) go to the subfont of the first character; get_rubber_variant and get_wide_variant go to the subfont which renders the numbered sizes of the character (rubber_subfont probes <name-0>), since the unnumbered name may be routed elsewhere. make_rubber_font hands the building of the extensible font to the main font when it carries a MATH table. supports always returns true: a smart font renders every character, if necessary with the error font.
When the debug switch fonts is on (DEBUG_FONTS), draw_fixed calls debug_draw instead of the subfont, which draws each run in the colour of its route (debug_origin, computed once per subfont from its specification); debug_info reports the route of one character from the routing tables, without resolving anything, for the font inspector. See inspecting the font system.
Several clients need the actual glyph of a symbol rather than a drawing operation: virtual fonts compile their glyphs from bitmaps of the base font, emulated fonts transform bitmaps, and the renderers draw glyphs through renderer_rep::draw (int char_code, font_glyphs fn, SI x, SI y). The smart font forwards these requests to the subfont of the first run:
glyph smart_font_rep::get_glyph (string s)
get_glyph returns the bitmap of the (first) symbol of s, index_glyph returns its index in a table of glyphs and metrics, or -1. The default implementations in font_rep print a warning (or fail if get_glyph_fatal is set), so a font which is used as the base of a virtual or emulated font must implement them.
advance_glyph moves to the next glyph boundary, taking the ligatures of the subfont into account; emulated fonts use it to draw glyph by glyph.
The drawing itself is not done by the smart font but by the leaf fonts. Note that draw_fixed draws at the font's own resolution; the public font_rep::draw (
Graphics/Fonts/font.cpp
) takes care of zooming. When the renderer has a zoom factor different from one and is not a printer, draw creates (and caches in zoomed_fn) a magnified version of the font and draws with it. For a smart font, magnify (zoomx, zoomy) returns smart_font_bis with the scaled resolutions, so that all subfonts, including virtual and emulated ones, are rebuilt at the screen resolution. Bitmap based constructions are therefore always computed at the right resolution.
Some subfonts do not use the TeXmacs encoding of the characters they render. The rewriting kind of each subfont is stored in fn_rewr, and rewrite (s, kind) is applied to each run in advance:
No change.
Characters of the form <#…> are converted into the corresponding TeXmacs names (rewrite_math, via strict_cork_to_utf8 and utf8_to_cork), for the old TeX math fonts.
Conversion to the T2A encoding of the TeX Cyrillic fonts (code_point_to_cyrillic_subset_in_t2a).
Unicode mathematical alphanumeric symbols are replaced by the plain letters, digits or Greek letters they are derived from (rewrite_letters, using the tables built by init_unicode_substitution); the subfont is the corresponding alphabet (bold, calligraphic, double struck, …).
The fixed table built by is_special: - becomes <minus>, | becomes <mid>, ' becomes <#2B9>, ‘ becomes <backprime>, <hat> and <tilde> become spacing accents, the invisible symbols <noplus>, <nocomma>, …, * and the invisible big operators <big-.-1>, <big-.-2> become empty, and big operators like <big-sum-1> become the Unicode symbol <sum> when it exists.
<name> becomes <emu-name>, for the virtual font emu-bracket.
<bbb-X> becomes X.
Greek letters are mapped to the mathematical italic Greek alphabet (U+1D6E2 and following, substitute_italic_greek).
<upalpha> or <up-alpha> becomes <alpha> (substitute_upright_greek).
<up-x> and <it-x> become x (substitute_upright, substitute_italic).
Latin letters are mapped to the mathematical italic alphabet (U+1D434 and following, with U+210E for h; substitute_math_italic), for the subfont ot-italic of an OpenType math font.
The empty string. Used for characters which must not be drawn: the null delimiters such as <left-.> and <right-nobracket>, and the ideographic space <#3000> when the fonts do not provide it.
Rewriting is applied to the whole run, which is why get_xpositions has to handle runs whose rewritten length differs from the original length.
The first element of a subfont specification determines how initialize_font creates it. The following kinds exist:
The base font and the error font of the constructor.
The generic case: closest_font (fam, var, ser, sh, sz, ndpi, attempt), where ndpi is computed by adjusted_dpi so that the x-height (characteristic ex in the font database) of the fallback font matches the one of the main family.
Old style TeX fonts for the historical families, obtained through find_closest and the rule based find_font (get_math_font, get_greek_font, get_cyrillic_font).
A whole smart font for another family, used for Greek and bold letters in mathematical italic shape.
The same smart font in upright shape.
The same family in italic shape.
Mathematical alphabets: smart fonts for the same family with variant tt, ss, calligraphic, gothic or outline and the appropriate series and shape. These are again resolved through the font database, and are emulated if the variant does not exist.
Smart fonts for shape mathitalic (for other: family roman, at an adjusted resolution), used for symbols which no Unicode font provides and which are only found in the old TeX fonts.
The main font itself, with the corresponding rewriting.
unicode_font ("STIXTwoMath-Regular", sz, dpi), the math font shipped with TeXmacs, for the symbols which the main font lacks and whose emulation could only be exported as a bitmap (see the resolution algorithm).
virtual_font (this, name, sz, hdpi, dpi, false): a virtual font whose base is the smart font itself (see virtual fonts).
Same, for emu-bracket.
A virtual font with base the main font in extend mode, stacked on top of emu-fundamental:
font vfn= fn[SUBFONT_MAIN];
if (a[1] != "emu-fundamental")
vfn= virtual_font (vfn, "emu-fundamental", sz, hdpi, dpi, true);
fn[nr]= virtual_font (vfn, a[1], sz, hdpi, dpi, true); |
poor_bold_font of the medium series of the same smart font.
poor_bbb_font of the upright smart font.
rubber_font (fn[nr]): the extensible version of another subfont (see emulated fonts).
After creation, initialize_font checks that the new subfont is not the smart font itself (same res_name), and aborts with "substitution font loop detected" otherwise.