Skip to main content

retex_lua/
luaotfload.rs

1//! A native replacement for luaotfload.
2//!
3//! The LaTeX kernel loads luaotfload in `\everyjob` with
4//! `require('luaotfload-main')` and `luaotfload.main()`. Here that module is
5//! provided natively: `main()` makes the same `luatexbase` registrations as
6//! luaotfload (so logs show the same lines), and the registered functions
7//! are implemented in Rust on top of `retex-font`:
8//!
9//! * `luaotfload.define_font` loads OpenType fonts with luaotfload's
10//!   request syntax and metrics,
11//! * `luaotfload.node_processor` shapes glyph runs (ligatures, kerning) in
12//!   node mode.
13//!
14//! The registration sequence and messages were taken from the log of a
15//! lualatex run.
16
17use std::cell::RefCell;
18use std::collections::HashMap;
19use std::rc::Rc;
20use std::sync::Arc;
21
22use mlua::{Lua, Value};
23use retex_engine::Engine;
24use retex_engine::fonts::{CharMetrics, FontData, FontInfo, FontKind};
25use retex_engine::nodes::NodeRef;
26use retex_font::LoadedFont;
27
28use crate::with_engine;
29
30/// Host-side state of the font loader.
31#[derive(Default)]
32pub struct FontState {
33    loader: Option<retex_font::FontLoader>,
34    /// Engine font id of each loaded font (by `LoadedFont` identity, and
35    /// whether the request was `scaled`): luaotfload returns the id of a
36    /// font already loaded for an equivalent request (e.g. `Latin Modern
37    /// Math/B` when there is no bold) instead of a new font. Observed: a
38    /// `scaled` request (a computed size) and an `at` request for the same
39    /// size give two fonts.
40    ids: HashMap<(usize, bool), u32>,
41    /// Whether the installed luaotfload is older than 3.29 (read once
42    /// from `luaotfload.sty`): those versions give fonts their design
43    /// size (so `\fontname` has no `at` clause at that size), 3.29 gives
44    /// them 0 (observed with 3.28 and 3.29).
45    legacy_design_size: Option<bool>,
46    /// Whether the log tells that the font name database was loaded.
47    db_announced: bool,
48}
49
50/// The Lua glue: the module table and `main`, which performs luaotfload's
51/// registrations through `luatexbase` in the order lualatex shows them.
52const MAIN_LUA: &str = r#"
53local native = ...
54local lb = luatexbase
55local function noop(...) return ... end
56local function log(cat, msg)
57  texio.write_nl("log", "luaotfload | " .. cat .. " : " .. msg)
58end
59luaotfload = luaotfload or {}
60luaotfload.define_font = native.define_font
61luaotfload.node_processor = native.node_processor
62luaotfload.version = luaotfload.version or "3.29"
63-- Letterspacing options (microtype replaces keepligature).
64luaotfload.letterspace = luaotfload.letterspace or
65  { keepligature = true, keeptogether = false, keepwordspacing = false }
66luaotfload.features = luaotfload.features or { defaults = {}, global = {} }
67local aux = luaotfload.aux or {}
68luaotfload.aux = aux
69for _, k in ipairs{"provides_script", "provides_language", "provides_feature",
70    "get_math_dimension", "font_has_glyph", "slot_of_name", "gid_of_name"} do
71  aux[k] = native["aux_" .. k]
72end
73aux.sprint_math_dimension = function(f, name)
74  tex.sprint(-2, tostring(aux.get_math_dimension(f, name)))
75end
76-- The parts of the fontloader's `fonts` table that packages touch.
77fonts = fonts or {}
78fonts.names = fonts.names or {}
79fonts.names.set_location_precedence = fonts.names.set_location_precedence or function() end
80fonts.hashes = fonts.hashes or {}
81fonts.hashes.identifiers = fonts.hashes.identifiers or setmetatable({}, {
82  __index = function(_, id) if type(id) == "number" then return font.getfont(id) end end })
83-- The fontloader's parameters (unrounded) and characters of a font, by
84-- id, kept once asked for; nil for fonts it did not load (polyglossia's
85-- punctuation spacing reads the parameters).
86local function font_hash(get)
87  return setmetatable({}, { __index = function(t, id)
88    if type(id) ~= "number" then return nil end
89    local v = get(id)
90    if v ~= nil then rawset(t, id, v) end
91    return v
92  end })
93end
94fonts.hashes.parameters = fonts.hashes.parameters or font_hash(native.font_parameters)
95fonts.hashes.characters = fonts.hashes.characters or font_hash(function(id)
96  if native.font_parameters(id) then return font.getfont(id).characters end
97end)
98fonts.hashes.quads = fonts.hashes.quads or {}
99local initialized = false
100luaotfload.main = function()
101  if initialized then
102    log("load", "Luaotfload initialization requested but is already loaded, ignoring.")
103    return
104  end
105  initialized = true
106  lb.provides_module({ name = "luaotfload", date = "2024-12-03", version = "3.29",
107    description = "Lua based OpenType font support" })
108  lb.provides_module({ name = "lualibs", date = "2023-07-13", version = "2.76",
109    description = "ConTeXt Lua standard libraries." })
110  lb.provides_module({ name = "lualibs-extended", date = "2023-07-13", version = "2.76",
111    description = "ConTeXt Lua libraries -- extended collection." })
112  -- lualibs' global `utf` (luamml uses it).
113  if not utf then utf = native.lualibs_utf() end
114  local cache = native.cache_dir()
115  log("conf", 'Root cache directory is "' .. cache .. '".')
116  -- As luaotfload does before loading the fontloader, which wants the
117  -- attribute with index zero to be zero.
118  tex.attribute[0] = 0
119  -- luaotfload's set-up holds six Lua references (observed in the
120  -- numbers box displays show for Lua data).
121  native.reserve_lua_refs(6)
122  local loader = kpse.find_file("fontloader-2023-12-28.lua", "lua") or "fontloader-2023-12-28.lua"
123  log("init", 'Loading fontloader "fontloader-2023-12-28.lua" from kpse-resolved path "' .. loader .. '".')
124  -- As the fontloader does: node properties are flushed with their
125  -- nodes and inherited by copies, for good.
126  node.direct.set_properties_mode(true, true)
127  function node.direct.set_properties_mode() end
128  lb.new_attribute("luaotfload@noligature")
129  log("init", "Context OpenType loader version 3.134")
130  -- luaotfload's node processor runs the pre_shaping_filter and
131  -- post_shaping_filter callbacks around the shaping. They are only
132  -- called once something is added to them.
133  if not lb.callbacktypes.pre_shaping_filter then
134    lb.create_callback("pre_shaping_filter", "list")
135    lb.create_callback("post_shaping_filter", "reverselist")
136  end
137  local shape = native.node_processor
138  local dispatch = shape
139  local call_callback = lb.call_callback
140  local function with_shaping_filters(head, groupcode, _, _, direction)
141    if not direction then
142      direction = tex.get("textdirection")
143    else
144      direction = direction == "TRT" and 1 or 0
145    end
146    local result = call_callback("pre_shaping_filter", head, groupcode, direction)
147    if result == false then
148      return false
149    elseif result ~= true then
150      head = result
151    end
152    result = shape(head, groupcode)
153    if result == false then
154      node.flush_list(head)
155      return nil
156    elseif result ~= true then
157      head = result
158    end
159    result = call_callback("post_shaping_filter", head, groupcode, direction)
160    if result == false then
161      node.flush_list(head)
162      return nil
163    elseif result == true then
164      return head
165    else
166      return result
167    end
168  end
169  local add_to_callback = lb.add_to_callback
170  function lb.add_to_callback(name, ...)
171    if name == "pre_shaping_filter" or name == "post_shaping_filter" then
172      dispatch = with_shaping_filters
173    end
174    return add_to_callback(name, ...)
175  end
176  local function node_processor(head, groupcode, size, packtype, direction)
177    return dispatch(head, groupcode, size, packtype, direction)
178  end
179  lb.add_to_callback("pre_linebreak_filter", node_processor, "luaotfload.node_processor")
180  lb.add_to_callback("hpack_filter", node_processor, "luaotfload.node_processor")
181  lb.add_to_callback("glyph_stream_provider", noop, "luaotfload.glyph_stream")
182  -- Font colours (`color=RRGGBB[AA]`): a font with one adds the colour
183  -- handler to the callbacks below, which brackets its glyphs with
184  -- colour stack 0 whatsits (observed; the alpha part is not supported).
185  local colors = {}
186  local color_handler
187  -- The colour literal for `value`, a colour in hex (RRGGBB, the alpha
188  -- of RRGGBBAA left out) or a name: the `luaotfload.parse_color`
189  -- callback (LaTeX's l3color) makes it if set, else hex is converted.
190  local function color_literal(value)
191    local hex = value:match("^%x%x%x%x%x%x$") or value:match("^(%x%x%x%x%x%x)%x%x$")
192    local ok, s = pcall(lb.call_callback, "luaotfload.parse_color", hex or value)
193    if ok and type(s) == "string" then return s end
194    if not hex then return nil end
195    local function c(i)
196      local v = tonumber(hex:sub(i, i + 1), 16) / 255
197      return (string.format("%.3f", v):gsub("0+$", ""):gsub("%.$", ""))
198    end
199    return c(1) .. " " .. c(3) .. " " .. c(5) .. " rg"
200  end
201  local function define_font(name, size, id)
202    local f = native.define_font(name, size, id)
203    if type(f) == "number" and type(name) == "string" then
204      local value = name:match("[:;]color={?([^;}]+)}?")
205      local literal = value and not colors[f] and color_literal(value)
206      if literal then
207        colors[f] = literal
208        if not color_handler then
209          color_handler = luaotfload.color_handler
210          lb.add_to_callback("post_linebreak_filter", color_handler, "luaotfload.color_handler")
211          lb.add_to_callback("hpack_filter", color_handler, "luaotfload.color_handler")
212          lb.add_to_callback("post_mlist_to_hlist_filter", color_handler, "luaotfload.color_handler")
213        end
214      end
215    end
216    return f
217  end
218  local GLYPH, HLIST, VLIST, WHATSIT = node.id("glyph"), node.id("hlist"), node.id("vlist"), node.id("whatsit")
219  local LINE = 1
220  local function stack(command, data)
221    local w = node.new("whatsit", "pdf_colorstack")
222    w.stack = 0
223    w.command = command
224    if data then w.data = data end
225    return w
226  end
227  -- Colours the glyphs of `head` starting with colour `current`; returns
228  -- the new head and the colour at its end. Paragraph lines are coloured
229  -- on their own; other boxes and whatsits end a coloured run.
230  local function colorize(head, current)
231    local n = head
232    while n do
233      local id = n.id
234      if id == GLYPH then
235        local c = colors[n.font]
236        if c ~= current then
237          local w = not c and stack(2) or stack(current and 0 or 1, c)
238          head = node.insert_before(head, n, w)
239          current = c
240        end
241      elseif id == HLIST and n.subtype == LINE then
242        if current then
243          head = node.insert_before(head, n, stack(2))
244          current = nil
245        end
246        local list, last = colorize(n.list, nil)
247        if last then
248          list = node.insert_after(list, node.tail(list), stack(2))
249        end
250        n.list = list
251      elseif id == HLIST or id == VLIST or id == WHATSIT then
252        if current then
253          head = node.insert_before(head, n, stack(2))
254          current = nil
255        end
256      end
257      n = n.next
258    end
259    return head, current
260  end
261  function luaotfload.color_handler(head)
262    if not head then return head end
263    local h, last = colorize(head, nil)
264    if last then
265      h = node.insert_after(h, node.tail(h), stack(2))
266    end
267    return h
268  end
269  lb.add_to_callback("define_font", define_font, "luaotfload.define_font")
270  lb.new_attribute("luaotfload_color_attribute")
271  log("conf", 'Root cache directory is "' .. cache .. '".')
272  lb.add_to_callback("find_opentype_file", noop, "luaotfload.harf.strip_prefix")
273  lb.add_to_callback("find_truetype_file", noop, "luaotfload.harf.strip_prefix")
274  lb.remove_from_callback("glyph_stream_provider", "luaotfload.glyph_stream")
275  lb.add_to_callback("glyph_stream_provider", noop, "luaotfload.harf.glyphstream")
276  lb.add_to_callback("post_linebreak_filter", noop, "luaotfload.harf.finalize_vlist")
277  lb.add_to_callback("hpack_filter", noop, "luaotfload.harf.finalize_hlist")
278  lb.add_to_callback("wrapup_run", noop, "luaotfload.cleanup_files")
279  lb.add_to_callback("finish_pdffile", noop, "luaotfload.harf.finalize_unicode")
280  -- Box displays show the character as UTF-8 (observed: "^^@" for 0
281  -- and ^^^^^^ notation beyond Unicode).
282  lb.add_to_callback("glyph_info", function(n)
283    -- mode=harf glyphs show their text (a ligature's characters).
284    local text = native.harf_glyph_text(n.font, n.char)
285    if text then return text end
286    local c = n.char
287    if c == 0 then return "^^@" end
288    if c > 0x10FFFF then return string.format("^^^^^^%06x", c) end
289    return utf8.char(c)
290  end, "luaotfload.glyphinfo")
291  lb.new_attribute("luaotfload.letterspace_done")
292  lb.create_callback("luaotfload.patch_font", "simple", noop)
293  lb.create_callback("luaotfload.patch_font_unsafe", "simple", noop)
294  lb.add_to_callback("luaotfload.patch_font", noop, "luaotfload.aux.set_sscale_dimens")
295  lb.add_to_callback("luaotfload.patch_font", noop, "luaotfload.aux.set_font_index")
296  lb.add_to_callback("luaotfload.patch_font", noop, "luaotfload.aux.patch_cambria_domh")
297  lb.add_to_callback("luaotfload.patch_font_unsafe", noop, "luaotfload.aux.fixup_fontdata")
298  lb.add_to_callback("luaotfload.patch_font", noop, "luaotfload.aux.set_capheight")
299  lb.add_to_callback("luaotfload.patch_font", noop, "luaotfload.aux.set_xheight")
300  lb.add_to_callback("luaotfload.patch_font", noop, "luaotfload.rewrite_fontname")
301  -- The colour interface of luaotfload's colors module, set up by
302  -- main() (l3backend checks for set_transparent_colorstack before
303  -- hooking into parse_color).
304  function luaotfload.add_colorscheme() end
305  function luaotfload.set_colorhandler() end
306  function luaotfload.set_transparenthandler() end
307  function luaotfload.set_transparent_colorstack() end
308  lb.create_callback("luaotfload.split_color", "exclusive", noop)
309  lb.create_callback("luaotfload.parse_color", "exclusive", noop)
310  lb.create_callback("luaotfload.parse_transparent", "exclusive", noop)
311  return true
312end
313return luaotfload
314"#;
315
316/// lualibs' `utf` table: the functions packages call, with the behaviour
317/// observed in lualatex (`utf.byte` gives the first code point only and
318/// nothing for an empty string; `utf.sub` counts characters as
319/// `string.sub` counts bytes).
320const UTF_LUA: &str = r#"
321local u = {}
322u.char = utf8.char
323u.len = utf8.len
324function u.byte(s)
325  if s and #s > 0 then return utf8.codepoint(s, 1) end
326end
327function u.sub(s, i, j)
328  local n = utf8.len(s) or 0
329  i = i or 1
330  j = j or -1
331  if i < 0 then i = math.max(n + i + 1, 1) elseif i == 0 then i = 1 end
332  if j < 0 then j = n + j + 1 elseif j > n then j = n end
333  if i > j then return "" end
334  local b = utf8.offset(s, i)
335  local e = utf8.offset(s, j + 1)
336  return s:sub(b, (e or #s + 1) - 1)
337end
338function u.characters(s)
339  return s:gmatch(utf8.charpattern)
340end
341function u.values(s)
342  local f = s:gmatch(utf8.charpattern)
343  return function()
344    local c = f()
345    if c then return utf8.codepoint(c) end
346  end
347end
348return u
349"#;
350
351/// Installs the `luaotfload-main` module (in `package.preload`).
352pub fn install(lua: &Lua) -> mlua::Result<()> {
353    lua.set_app_data(Rc::new(RefCell::new(FontState::default())));
354    let native = lua.create_table()?;
355    native.set(
356        "define_font",
357        lua.create_function(|lua, (name, size, _id): (mlua::String, i64, Option<i64>)| {
358            let name = name.to_str()?.to_owned();
359            let t0 = std::time::Instant::now();
360            let before = with_engine(lua, |e| e.fonts.fonts.len())?;
361            let r = define_font(lua, &name, size as i32);
362            retex_engine::timing::FONTS.with(|a| a.add(t0));
363            // A new font holds Lua references, as in LuaTeX (observed in
364            // the numbers box displays show for Lua data).
365            with_engine(lua, |e| {
366                for _ in before..e.fonts.fonts.len() {
367                    e.nodes.lua_refs.font_defined(true);
368                }
369            })?;
370            r
371        })?,
372    )?;
373    native.set(
374        "reserve_lua_refs",
375        lua.create_function(|lua, n: i64| {
376            with_engine(lua, |e| {
377                for _ in 0..n {
378                    e.nodes.lua_refs.take();
379                }
380            })
381        })?,
382    )?;
383    native.set(
384        "node_processor",
385        lua.create_function(|lua, (head, _group): (Value, Value)| {
386            let h = match &head {
387                Value::UserData(u) => u
388                    .borrow::<crate::nodelib::LNode>()
389                    .ok()
390                    .map(|n| NodeRef(n.0)),
391                _ => None,
392            };
393            if let Some(h) = h {
394                let nh = with_engine(lua, |e| process_list(e, h))?;
395                if nh != h {
396                    return Ok(Value::UserData(
397                        lua.create_userdata(crate::nodelib::LNode(nh.0))?,
398                    ));
399                }
400            }
401            Ok(Value::Boolean(true))
402        })?,
403    )?;
404    native.set(
405        "harf_glyph_text",
406        lua.create_function(|lua, (font, c): (i64, i64)| {
407            let text = with_engine(lua, |e| {
408                let f = u32::try_from(font)
409                    .ok()
410                    .filter(|&f| e.font_exists(f as i32))?;
411                let lf = loaded_font(e, f)?;
412                if lf.request.mode != retex_font::request::Mode::Harf {
413                    return None;
414                }
415                let t = lf.tex.tounicode(u32::try_from(c).ok()?);
416                (t.len() > 1).then(|| t.into_iter().filter_map(char::from_u32).collect::<String>())
417            })?;
418            Ok(text)
419        })?,
420    )?;
421    native.set(
422        "font_parameters",
423        lua.create_function(|lua, id: i64| {
424            let Some(lf) = with_engine(lua, |e| {
425                u32::try_from(id)
426                    .ok()
427                    .filter(|&f| e.font_exists(f as i32))
428                    .and_then(|f| loaded_font(e, f))
429            })?
430            else {
431                return Ok(None);
432            };
433            let t = &lf.tex;
434            let p = lua.create_table()?;
435            for (k, v) in retex_font::texfont::LOADER_PARAMS
436                .iter()
437                .zip(t.loader_params)
438            {
439                let spacing = matches!(*k, "space_stretch" | "space_shrink" | "extra_space");
440                let v = if spacing && v == 0.0 {
441                    // Monospaced fonts: integer zeros (observed).
442                    Value::Integer(0)
443                } else {
444                    Value::Number(v)
445                };
446                match k.parse::<i64>() {
447                    Ok(n) => p.set(n, v)?,
448                    Err(_) => p.set(*k, v)?,
449                }
450            }
451            let factor = t.size_f64 / f64::from(t.units_per_em);
452            for k in ["factor", "hfactor", "vfactor"] {
453                p.set(k, factor)?;
454            }
455            for k in ["size", "scaledpoints", "textsize"] {
456                p.set(k, t.size)?;
457            }
458            p.set("units", t.units_per_em)?;
459            p.set("extrafactor", 1)?;
460            for k in ["mathsize", "mode", "width"] {
461                p.set(k, 0)?;
462            }
463            Ok(Some(p))
464        })?,
465    )?;
466    native.set(
467        "cache_dir",
468        lua.create_function(|lua, ()| with_engine(lua, names_cache_dir))?,
469    )?;
470    let utf = lua
471        .load(UTF_LUA)
472        .set_name("=lualibs-unicode")
473        .into_function()?;
474    native.set("lualibs_utf", utf)?;
475    crate::otfaux::install(lua, &native)?;
476    let loader = lua.create_function(move |lua, ()| {
477        // Like `require` of the real module: it fails where luaotfload
478        // cannot be found (l3build sandboxes without the search tree).
479        let kpse: mlua::Table = lua.globals().get("kpse")?;
480        let find: mlua::Function = kpse.get("find_file")?;
481        if find.call::<Value>(("luaotfload-main.lua", "lua"))?.is_nil() {
482            return Err(mlua::Error::runtime("module 'luaotfload-main' not found"));
483        }
484        let f = lua
485            .load(MAIN_LUA)
486            .set_name("=luaotfload-main")
487            .into_function()?;
488        let native: mlua::Table = lua.named_registry_value("retex.luaotfload.native")?;
489        f.call::<Value>(native)
490    })?;
491    lua.set_named_registry_value("retex.luaotfload.native", native)?;
492    let package: mlua::Table = lua.globals().get("package")?;
493    let preload: mlua::Table = package.get("preload")?;
494    preload.set("luaotfload-main", loader)?;
495    // retex stands in for luahbtex, whose `luaharfbuzz` module packages
496    // probe for (expl3's \c_sys_engine_exec_str is `luahbtex` when
497    // `require 'luaharfbuzz'` succeeds). Shaping is native, so the module
498    // only has the version information; its classes are empty.
499    let harfbuzz = lua
500        .load(
501            r#"local hb = { shapers = function() return "graphite2", "ot", "fallback" end,
502                            version = function() return "12.3.2" end }
503               for _, k in ipairs{"Blob", "Buffer", "Direction", "Face", "Feature", "Font",
504                                  "Language", "Script", "Tag", "Variation", "ot", "unicode"} do
505                 hb[k] = {}
506               end
507               return function() return hb end"#,
508        )
509        .set_name("=[luaharfbuzz]")
510        .call::<mlua::Function>(())?;
511    preload.set("luaharfbuzz", harfbuzz)?;
512    Ok(())
513}
514
515/// The directory of luaotfload's font names database: in the first
516/// directory of `TEXMFCACHE` that can be written (observed: with
517/// `TEXMFCACHE=$TEXMFSYSVAR:$TEXMFVAR`, the default, and a system tree
518/// that is not writable, `TEXMFVAR`), and that `openout_any` accepts.
519fn names_cache_dir(e: &mut retex_engine::Engine) -> String {
520    let Some(k) = e.kpse.as_ref() else {
521        return String::new();
522    };
523    let k = k.borrow();
524    let writable = |dir: &str| {
525        let probe = std::path::Path::new(dir).join(format!(".retex-probe-{}", std::process::id()));
526        let ok = std::fs::File::create(&probe).is_ok();
527        let _ = std::fs::remove_file(&probe);
528        ok
529    };
530    let root = k
531        .var_value("TEXMFCACHE")
532        .unwrap_or_default()
533        .split(':')
534        .find(|d| {
535            !d.is_empty() && k.name_ok(d, retex_kpath::Access::Write, true).is_ok() && writable(d)
536        })
537        .map(str::to_owned)
538        .or_else(|| k.var_value("TEXMFVAR"))
539        .unwrap_or_default();
540    format!("{root}/luatex-cache/generic/names")
541}
542
543/// Whether the `luaotfload.sty` found is older than version 3.29 (its
544/// `\ProvidesPackage` line, `[2024/02/14 v3.28 …]`).
545fn legacy_luaotfload(e: &mut Engine) -> bool {
546    let Some(path) = e.kpse.as_ref().and_then(|k| {
547        k.borrow_mut()
548            .find_file("luaotfload.sty", retex_kpath::FileFormat::Tex)
549    }) else {
550        return false;
551    };
552    let Ok(text) = std::fs::read(path) else {
553        return false;
554    };
555    let text = String::from_utf8_lossy(&text);
556    let Some(at) = text.find("\\ProvidesPackage{luaotfload}") else {
557        return false;
558    };
559    let rest = &text[at..];
560    let Some(v) = rest.find(" v").map(|i| &rest[i + 2..]) else {
561        return false;
562    };
563    let ver: String = v
564        .chars()
565        .take_while(|c| c.is_ascii_digit() || *c == '.')
566        .collect();
567    let mut parts = ver.split('.').map(|p| p.parse::<u32>().unwrap_or(0));
568    let (major, minor) = (parts.next().unwrap_or(0), parts.next().unwrap_or(0));
569    (major, minor) < (3, 29) && major > 0
570}
571
572/// Loads a font for the `define_font` callback and registers it with the
573/// engine. Returns the engine font id, or nil if the font cannot be loaded.
574fn define_font(lua: &Lua, name: &str, size: i32) -> mlua::Result<Value> {
575    let state = lua
576        .app_data_ref::<Rc<RefCell<FontState>>>()
577        .map(|s| s.clone())
578        .ok_or_else(|| mlua::Error::runtime("font state missing"))?;
579    // An anonymous request is a TeX metric file if there is one (the
580    // first step of luaotfload's "tex,path,name" anonymous lookup).
581    if let Ok(req) = retex_font::FontRequest::parse(name)
582        && let retex_font::FontSource::Any(base) = &req.source
583    {
584        let id = with_engine(lua, |e| {
585            let f = e.load_tfm_font(base.as_bytes(), size, name.as_bytes());
586            if let Some(f) = f {
587                e.check_lua_loaded_font(f);
588            }
589            f
590        })?;
591        if let Some(i) = id {
592            return Ok(Value::Integer(i64::from(i)));
593        }
594    }
595    // luaotfload loads its font name database for the first font that is
596    // no TeX metric file (also for file lookups) and says so in the log.
597    {
598        if !state.borrow().db_announced {
599            state.borrow_mut().db_announced = true;
600            let dir = with_engine(lua, names_cache_dir)?;
601            let texio: mlua::Table = lua.globals().get("texio")?;
602            let write: mlua::Function = texio.get("write_nl")?;
603            write.call::<()>((
604                "log",
605                format!(
606                    "luaotfload | db : Font names database loaded from {dir}/luaotfload-names.luc.gz"
607                ),
608            ))?;
609        }
610    }
611    let loaded: Result<Arc<LoadedFont>, String> = with_engine(lua, |e| {
612        let mut st = state.borrow_mut();
613        if st.loader.is_none() {
614            let k = e
615                .kpse
616                .clone()
617                .ok_or_else(|| "kpathsea unavailable".to_owned())?;
618            st.loader = Some(retex_font::FontLoader::new(k));
619        }
620        st.loader
621            .as_mut()
622            .expect("loader initialized")
623            .load(name, size)
624            .map_err(|e| e.to_string())
625    })?;
626    let Ok(font) = loaded else {
627        // luaotfload falls back to TeX metric files (e.g. `cmr10`).
628        let plain = name.strip_prefix("file:").unwrap_or(name);
629        let plain = plain.split(':').next().unwrap_or(plain).to_owned();
630        let id = with_engine(lua, |e| {
631            let f = e.load_tfm_font(plain.as_bytes(), size, name.as_bytes());
632            if let Some(f) = f {
633                e.check_lua_loaded_font(f);
634            }
635            f
636        })?;
637        return Ok(id.map_or(Value::Nil, |i| Value::Integer(i64::from(i))));
638    };
639    let key = (Arc::as_ptr(&font) as usize, size < 0);
640    if let Some(&id) = state.borrow().ids.get(&key) {
641        return Ok(Value::Integer(i64::from(id)));
642    }
643    let known = state.borrow().legacy_design_size;
644    let legacy = match known {
645        Some(l) => l,
646        None => with_engine(lua, legacy_luaotfload)?,
647    };
648    state.borrow_mut().legacy_design_size = Some(legacy);
649    let id = with_engine(lua, |e| {
650        let tex = &font.tex;
651        let design_size = if legacy {
652            retex_font::texfont::design_size(&font.file).round() as i32
653        } else {
654            tex.design_size
655        };
656        let mut params = vec![0; tex.params.len() + 1];
657        for (i, p) in tex.params.iter().enumerate() {
658            params[i + 1] = *p;
659        }
660        let mut chars = HashMap::with_capacity_and_hasher(
661            tex.num_chars(),
662            retex_engine::hash::FastHash::default(),
663        );
664        for (code, m) in tex.chars() {
665            chars.insert(
666                code,
667                CharMetrics {
668                    width: m.width,
669                    height: m.height,
670                    depth: m.depth,
671                    italic: m.italic,
672                    index: u32::from(m.glyph),
673                },
674            );
675        }
676        let info = FontInfo {
677            name: tex.name.clone().into_bytes(),
678            size: tex.size,
679            design_size,
680            checksum: 0,
681            params,
682            chars,
683            hyphen_char: i32::MIN,
684            skew_char: i32::MIN,
685            kind: FontKind::OpenType,
686            handle: 0,
687            char_codes: Default::default(),
688            ignore_ligatures: 0,
689            data: Some(FontData(Rc::new(font.clone()))),
690            lig_kern: Default::default(),
691            right_boundary: None,
692            expansion: None,
693            size_spec: i32::MIN,
694            vf: None,
695            math_chars: {
696                let mc = tex.math_chars(&font.file);
697                (!mc.is_empty()).then(|| Rc::new(convert_math_chars(mc)))
698            },
699            math_constants: tex.math.as_ref().map(|m| {
700                Rc::new(
701                    m.iter()
702                        .map(|(k, v)| ((*k).to_owned(), v.to_sp()))
703                        .collect(),
704                )
705            }),
706        };
707        e.register_font(info)
708    })?;
709    state.borrow_mut().ids.insert(key, id);
710    Ok(Value::Integer(i64::from(id)))
711}
712
713/// Converts the font crate's math data to the engine's, rounding the
714/// dimensions to scaled points.
715fn convert_math_chars(
716    mc: HashMap<u32, retex_font::texfont::MathChar>,
717) -> HashMap<u32, retex_engine::fonts::MathCharInfo> {
718    use retex_engine::fonts::{ExtPart, MathCharInfo};
719    let parts = |v: &Option<Vec<retex_font::texfont::MathPart>>| {
720        v.as_ref().map(|ps| {
721            ps.iter()
722                .map(|p| ExtPart {
723                    code: p.code,
724                    start: retex_font::texfont::round_sp(p.start),
725                    end: retex_font::texfont::round_sp(p.end),
726                    advance: retex_font::texfont::round_sp(p.advance),
727                    extender: p.extender,
728                })
729                .collect::<Rc<[ExtPart]>>()
730        })
731    };
732    mc.into_iter()
733        .map(|(c, m)| {
734            (
735                c,
736                MathCharInfo {
737                    next: m.next,
738                    top_accent: m.top_accent.map(retex_font::texfont::round_sp),
739                    vert: parts(&m.vert),
740                    horiz: parts(&m.horiz),
741                },
742            )
743        })
744        .collect()
745}
746
747/// The OpenType font behind engine font `f`, if any.
748pub fn loaded_font(e: &Engine, f: u32) -> Option<Arc<LoadedFont>> {
749    let data = e.font(f).data.as_ref()?;
750    data.0.downcast_ref::<Arc<LoadedFont>>().cloned()
751}
752
753pub use crate::otfnodes::process_list;
754
755#[cfg(test)]
756mod tests {
757    #[test]
758    fn lualibs_utf() {
759        let lua = mlua::Lua::new();
760        let utf: mlua::Table = lua.load(super::UTF_LUA).eval().expect("utf");
761        lua.globals().set("utf", utf).expect("set");
762        let r: String = lua
763            .load(
764                r##"local o = {}
765                   local function add(...) o[#o + 1] = table.concat({...}, ",") end
766                   add(utf.char(65, 0x3B1), utf.byte("\u{3B1}b"), select("#", utf.byte("")))
767                   add(utf.len("\u{3B1}b"), utf.sub("\u{3B1}\u{3B2}c", 2, 3),
768                       utf.sub("\u{3B1}\u{3B2}c", 2), utf.sub("\u{3B1}\u{3B2}c", -1))
769                   for c in utf.characters("a\u{3B1}") do add(c) end
770                   for c in utf.values("a\u{3B1}") do add(c) end
771                   return table.concat(o, "|")"##,
772            )
773            .eval()
774            .expect("run");
775        // Observed in lualatex.
776        assert_eq!(r, "A\u{3B1},945,0|2,\u{3B2}c,\u{3B2}c,c|a|\u{3B1}|97|945");
777    }
778}