use mlua::{Function, Lua, Table, Value, Variadic};
use std::cell::RefCell;
use std::rc::Rc;
pub const NAMES: &[&str] = &[
"",
"find_write_file",
"find_output_file",
"find_image_file",
"find_format_file",
"find_read_file",
"open_read_file",
"find_vf_file",
"read_vf_file",
"find_data_file",
"read_data_file",
"find_font_file",
"read_font_file",
"find_map_file",
"read_map_file",
"find_enc_file",
"read_enc_file",
"find_type1_file",
"read_type1_file",
"find_truetype_file",
"read_truetype_file",
"find_opentype_file",
"read_opentype_file",
"find_cidmap_file",
"read_cidmap_file",
"find_pk_file",
"read_pk_file",
"show_error_hook",
"process_input_buffer",
"process_output_buffer",
"process_jobname",
"start_page_number",
"stop_page_number",
"start_run",
"stop_run",
"define_font",
"pre_output_filter",
"buildpage_filter",
"hpack_filter",
"vpack_filter",
"glyph_not_found",
"glyph_info",
"hyphenate",
"ligaturing",
"kerning",
"pre_linebreak_filter",
"linebreak_filter",
"post_linebreak_filter",
"append_to_vlist_filter",
"mlist_to_hlist",
"finish_pdffile",
"finish_pdfpage",
"pre_dump",
"start_file",
"stop_file",
"show_error_message",
"show_lua_error_hook",
"show_ignored_error_message",
"show_warning_message",
"hpack_quality",
"vpack_quality",
"process_rule",
"insert_local_par",
"contribute_filter",
"call_edit",
"build_page_insert",
"glyph_stream_provider",
"font_descriptor_objnum_provider",
"finish_synctex",
"wrapup_run",
"new_graf",
"page_order_index",
"make_extensible",
"process_pdf_image_content",
"provide_charproc_data",
"input_level_string",
"dvi_output",
];
pub fn id(name: &str) -> Option<usize> {
NAMES.iter().skip(1).position(|n| *n == name).map(|i| i + 1)
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum State {
Unset,
Disabled,
Function,
}
thread_local! {
static SET: RefCell<Vec<State>> = RefCell::new(vec![State::Unset; NAMES.len()]);
}
const REGISTRY_KEY: &str = "texrs.callbacks";
pub(super) fn reset() {
SET.with(|s| s.borrow_mut().iter_mut().for_each(|v| *v = State::Unset));
crate::input_hooks::set_find_read_file(None);
crate::input_hooks::set_open_read_file(None);
crate::input_hooks::set_process_input_buffer(None);
}
pub fn state(name: &str) -> State {
match id(name) {
Some(i) => SET.with(|s| s.borrow()[i]),
None => State::Unset,
}
}
pub fn function(lua: &Lua, name: &str) -> Option<Function> {
let i = id(name)?;
if SET.with(|s| s.borrow()[i]) != State::Function {
return None;
}
let t: Table = lua.named_registry_value(REGISTRY_KEY).ok()?;
t.raw_get::<Option<Function>>(i).ok().flatten()
}
pub(super) fn table(lua: &Lua, arena: &Rc<RefCell<super::node::Arena>>) -> mlua::Result<Table> {
lua.set_named_registry_value(REGISTRY_KEY, lua.create_table()?)?;
crate::node::hooks::clear();
let t = lua.create_table()?;
let arena = Rc::clone(arena);
t.set(
"register",
lua.create_function(move |lua, (name, f): (Value, Value)| {
let fail = |msg: &str| -> mlua::Result<Variadic<Value>> {
Ok(Variadic::from_iter([
Value::Nil,
Value::String(lua.create_string(msg)?),
]))
};
let Value::String(name) = name else {
return fail(
"Invalid arguments to callback.register, first argument must be string.",
);
};
let state = match &f {
Value::Function(_) => State::Function,
Value::Boolean(_) => State::Disabled,
Value::Nil => State::Unset,
_ => State::Function,
};
let Some(i) = id(&name.to_str()?) else {
return fail("No such callback exists.");
};
SET.with(|s| s.borrow_mut()[i] = state);
let reg: Table = lua.named_registry_value(REGISTRY_KEY)?;
reg.raw_set(i, f)?;
hook(lua, &arena, NAMES[i], state == State::Function);
Ok(Variadic::from_iter([Value::Integer(i as i64)]))
})?,
)?;
t.set(
"find",
lua.create_function(|lua, name: Value| {
let fail = |msg: &str| -> mlua::Result<Variadic<Value>> {
Ok(Variadic::from_iter([
Value::Nil,
Value::String(lua.create_string(msg)?),
]))
};
let Value::String(name) = name else {
return fail("Invalid arguments to callback.find.");
};
let Some(i) = id(&name.to_str()?) else {
return fail("No such callback exists.");
};
let reg: Table = lua.named_registry_value(REGISTRY_KEY)?;
Ok(Variadic::from_iter([reg.raw_get::<Value>(i)?]))
})?,
)?;
t.set(
"list",
lua.create_function(|lua, ()| {
let t = lua.create_table()?;
SET.with(|s| {
let s = s.borrow();
for (i, name) in NAMES.iter().enumerate().skip(1) {
t.raw_set(*name, s[i] != State::Unset)?;
}
Ok::<_, mlua::Error>(())
})?;
Ok(t)
})?,
)?;
Ok(t)
}
fn hook(lua: &Lua, arena: &Rc<RefCell<super::node::Arena>>, name: &'static str, on: bool) {
if input_hook(lua, name, on) {
return;
}
if name == "define_font" {
use crate::node::hooks::{Defined, FontDefiner};
let definer: Option<FontDefiner> = on.then(|| {
let lua = lua.clone();
Box::new(
move |eng: &mut crate::expand::Engine,
lx: &mut crate::lexer::Lexer,
file: &str,
size: i64| {
let f = function(&lua, name)?;
let id = eng.fonts.fonts.len();
let answer = super::ctx::enter(eng, lx, || -> mlua::Result<Option<Defined>> {
Ok(match f.call::<Value>((file, size))? {
Value::Table(t) => Some(Defined::Font(Box::new(
super::font::define_for_tex(&lua, id, t)?,
))),
Value::Integer(n) => u16::try_from(n).ok().map(Defined::Existing),
Value::Number(n) => u16::try_from(n as i64).ok().map(Defined::Existing),
_ => None,
})
});
super::notes_to_engine(eng);
answer.unwrap_or_else(|e| {
super::warn(&format!("callback {name}: {}", super::lua_error_text(&e)));
None
})
},
) as FontDefiner
});
crate::node::hooks::set(|h| h.define_font = definer);
return;
}
use crate::node::hooks::{Context, Hooks, ListFilter, Notice};
type Slot = fn(&mut Hooks) -> &mut Option<ListFilter>;
let list_slot: Option<Slot> = match name {
"pre_linebreak_filter" => Some(|h| &mut h.pre_linebreak_filter),
"linebreak_filter" => Some(|h| &mut h.linebreak_filter),
"post_linebreak_filter" => Some(|h| &mut h.post_linebreak_filter),
"hpack_filter" => Some(|h| &mut h.hpack_filter),
"vpack_filter" => Some(|h| &mut h.vpack_filter),
"pre_output_filter" => Some(|h| &mut h.pre_output_filter),
"hyphenate" => Some(|h| &mut h.hyphenate),
"ligaturing" => Some(|h| &mut h.ligaturing),
"kerning" => Some(|h| &mut h.kerning),
_ => None,
};
if let Some(slot) = list_slot {
let filter: Option<ListFilter> = on.then(|| {
let (lua, arena) = (lua.clone(), Rc::clone(arena));
Box::new(move |list: &mut Vec<crate::node::Node>, cx: &Context| {
if let Err(e) = run_list_callback(&lua, &arena, name, list, cx) {
super::warn(&format!("callback {name}: {}", super::lua_error_text(&e)));
}
}) as ListFilter
});
crate::node::hooks::set(|h| *slot(h) = filter);
return;
}
type NoticeSlot = fn(&mut Hooks) -> &mut Option<Notice>;
let notice_slot: Option<NoticeSlot> = match name {
"buildpage_filter" => Some(|h| &mut h.buildpage_filter),
"contribute_filter" => Some(|h| &mut h.contribute_filter),
_ => None,
};
if let Some(slot) = notice_slot {
let notice: Option<Notice> = on.then(|| {
let lua = lua.clone();
Box::new(move |info: &str| {
if let Some(f) = function(&lua, name) {
if let Err(e) = f.call::<()>(info) {
super::warn(&format!("callback {name}: {}", super::lua_error_text(&e)));
}
}
}) as Notice
});
crate::node::hooks::set(|h| *slot(h) = notice);
}
}
fn input_hook(lua: &Lua, name: &'static str, on: bool) -> bool {
use crate::input_hooks as ih;
let report = move |e: mlua::Error| {
super::warn(&format!("callback {name}: {}", super::lua_error_text(&e)))
};
match name {
"find_read_file" => {
let lua = lua.clone();
ih::set_find_read_file(on.then(|| {
Box::new(move |id: i64, asked: &str| {
let f = function(&lua, name)?;
match f.call::<Option<mlua::LuaString>>((id, asked)) {
Ok(found) => found.map(|s| s.to_string_lossy()),
Err(e) => {
report(e);
None
}
}
}) as ih::FindReadFile
}));
}
"open_read_file" => {
let lua = lua.clone();
ih::set_open_read_file(on.then(|| {
Box::new(move |file: &str| {
let f = function(&lua, name)?;
let env = match f.call::<Option<Table>>(file) {
Ok(env) => env?,
Err(e) => {
report(e);
return None;
}
};
let reader: Function = env.get("reader").ok()?;
let mut done = false;
Some(Box::new(move || {
if done {
return None;
}
let line = match reader.call::<Option<mlua::LuaString>>(env.clone()) {
Ok(line) => line.map(|s| s.to_string_lossy()),
Err(e) => {
report(e);
None
}
};
if line.is_none() {
done = true;
if let Ok(close) = env.get::<Function>("close") {
if let Err(e) = close.call::<()>(env.clone()) {
report(e);
}
}
}
line
}) as Box<dyn FnMut() -> Option<String>>)
}) as ih::OpenReadFile
}));
}
"process_input_buffer" => {
let lua = lua.clone();
ih::set_process_input_buffer(on.then(|| {
Box::new(move |line: &str| {
let f = function(&lua, name)?;
match f.call::<Value>(line) {
Ok(Value::String(s)) => Some(s.to_string_lossy()),
Ok(_) => None,
Err(e) => {
report(e);
None
}
}
}) as ih::ProcessInputBuffer
}));
}
_ => return false,
}
true
}
fn run_list_callback(
lua: &Lua,
arena: &Rc<RefCell<super::node::Arena>>,
name: &str,
list: &mut Vec<crate::node::Node>,
cx: &crate::node::hooks::Context,
) -> mlua::Result<()> {
let Some(f) = function(lua, name) else {
return Ok(());
};
if list.is_empty() {
return Ok(());
}
let mut head = super::node::from_engine(&mut arena.borrow_mut(), list)?;
if matches!(name, "pre_linebreak_filter" | "linebreak_filter") {
head = super::node::with_local_par(&mut arena.borrow_mut(), head)?;
}
let head_v = super::node::handle(lua, arena, head)?;
let s = |v: &str| lua.create_string(v).map(Value::String);
let args: Vec<Value> = match name {
"pre_linebreak_filter" | "post_linebreak_filter" => vec![head_v, s(cx.groupcode)?],
"linebreak_filter" => vec![head_v, Value::Boolean(cx.groupcode == "display")],
"hpack_filter" => vec![
head_v,
s(cx.groupcode)?,
Value::Integer(cx.size),
s(cx.packtype)?,
Value::Nil,
],
"vpack_filter" | "pre_output_filter" => vec![
head_v,
s(cx.groupcode)?,
Value::Integer(cx.size),
s(cx.packtype)?,
Value::Integer(cx.maxdepth),
Value::Nil,
],
_ => {
let tail = match head {
Some(h) => Some(arena_tail(arena, h)?),
None => None,
};
vec![head_v, super::node::handle(lua, arena, tail)?]
}
};
let answer: Value = f.call(Variadic::from_iter(args))?;
let new_head = match (name, &answer) {
("hyphenate" | "ligaturing" | "kerning", _) => match head {
Some(h) => Some(arena_first(arena, h)?),
None => None,
},
(_, Value::Boolean(true)) => head,
(_, Value::Boolean(false)) => None,
(_, v) => super::node::index_of(arena, v)?,
};
*list = match new_head {
Some(h) => super::node::list_to_engine(&arena.borrow(), h)?,
None => Vec::new(),
};
Ok(())
}
fn arena_tail(arena: &Rc<RefCell<super::node::Arena>>, head: usize) -> mlua::Result<usize> {
super::node::tail_of(&arena.borrow(), head)
}
fn arena_first(arena: &Rc<RefCell<super::node::Arena>>, at: usize) -> mlua::Result<usize> {
super::node::first_of(&arena.borrow(), at)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_slot_numbers_are_luatexs() {
assert_eq!(id("find_write_file"), Some(1));
assert_eq!(id("find_read_file"), Some(5));
assert_eq!(id("define_font"), Some(35));
assert_eq!(id("pre_linebreak_filter"), Some(45));
assert_eq!(id("dvi_output"), Some(NAMES.len() - 1));
assert_eq!(id(""), None);
assert_eq!(id("no_such_callback"), None);
}
}