diff --git a/src/pob.rs b/src/pob.rs index 969dc74..50858dd 100644 --- a/src/pob.rs +++ b/src/pob.rs @@ -10,10 +10,7 @@ use crate::{ draw_commands::DrawCommandRecorder, fonts::Fonts, input::{InputState, key_as_str, mousebutton_as_str}, - pob::{ - api::call_callback, - subscript::{NativeMultiValue, SubscriptManager, SubscriptResult}, - }, + pob::subscript::{SubscriptManager, SubscriptResult}, renderer::textures::TextureManager, stage::{StageEvent, StageFrameOutput, StageTransition}, util::change_working_directory, @@ -149,7 +146,7 @@ impl PathOfBuilding { lua.load(script_dir.join("Launch.lua")).exec()?; { profiling::scope!("OnInit"); - call_callback::<(), ()>(lua, "OnInit", ())?; + api::on_init(lua)?; } Ok(()) } @@ -175,18 +172,14 @@ impl PathOfBuilding { self.ctx_mut().input_state.set_key_pressed(&key, true); if let Some(key) = key_as_str(key) { - call_callback::<(&str, bool), ()>( - &self.lua, - "OnKeyDown", - (key.as_str(), false), - )?; + api::on_key_down(&self.lua, key.as_str(), false)?; } } StageEvent::KeyUp { key } => { self.ctx_mut().input_state.set_key_pressed(&key, false); if let Some(key) = key_as_str(key) { - call_callback::<&str, ()>(&self.lua, "OnKeyUp", key.as_str())?; + api::on_key_up(&self.lua, key.as_str())?; } } StageEvent::ModifiersChanged { state } => { @@ -194,46 +187,34 @@ impl PathOfBuilding { } StageEvent::CharacterInput { ch } => { let ch = if ch.is_ascii() { ch } else { '?' }; - call_callback::(&self.lua, "OnChar", ch)?; + api::on_char(&self.lua, ch)?; } StageEvent::MouseDown { button } => { let is_double_click = self.ctx_mut().input_state.set_mouse_pressed(button, true); if let Some(button) = mousebutton_as_str(button) { - call_callback::<(&str, bool), ()>( - &self.lua, - // PoB treats mouse buttons as keys - "OnKeyDown", - (button.as_str(), is_double_click), - )?; + // PoB treats mouse buttons as keys + api::on_key_down(&self.lua, button.as_str(), is_double_click)?; } } StageEvent::MouseUp { button } => { self.ctx_mut().input_state.set_mouse_pressed(button, false); if let Some(button) = mousebutton_as_str(button) { - call_callback::<&str, ()>( - &self.lua, - // PoB treats mouse buttons as keys - "OnKeyUp", - button.as_str(), - )?; + // PoB treats mouse buttons as keys + api::on_key_up(&self.lua, button.as_str())?; } } StageEvent::MouseWheel { delta } => { if delta > 0.0 { - call_callback::<(&str, bool), ()>(&self.lua, "OnKeyDown", ("WHEELUP", false))?; - call_callback::<&str, ()>(&self.lua, "OnKeyUp", "WHEELUP")?; + api::on_key_down(&self.lua, "WHEELUP", false)?; + api::on_key_up(&self.lua, "WHEELUP")?; } else if delta < 0.0 { - call_callback::<(&str, bool), ()>( - &self.lua, - "OnKeyDown", - ("WHEELDOWN", false), - )?; - call_callback::<&str, ()>(&self.lua, "OnKeyUp", "WHEELDOWN")?; + api::on_key_down(&self.lua, "WHEELDOWN", false)?; + api::on_key_up(&self.lua, "WHEELDOWN")?; } } - StageEvent::Exit => call_callback(&self.lua, "OnExit", ())?, + StageEvent::Exit => api::on_exit(&self.lua)?, StageEvent::MouseMoved { pos } => { self.ctx_mut().set_mouse_pos(pos); } @@ -297,7 +278,7 @@ impl PathOfBuilding { { profiling::scope!("lua_OnFrame"); - call_callback::<(), ()>(&self.lua, "OnFrame", ())?; + api::on_frame(&self.lua)?; } let ctx = self.lua.app_data_ref::().unwrap(); @@ -334,14 +315,10 @@ impl PathOfBuilding { for event in subscript_events { match event { SubscriptResult::SubscriptFinished { id, return_values } => { - call_callback::<(u64, NativeMultiValue), ()>( - &self.lua, - "OnSubFinished", - (id, return_values), - )?; + api::on_sub_finished(&self.lua, id, return_values)?; } SubscriptResult::SubscriptError { id, error } => { - call_callback::<(u64, String), ()>(&self.lua, "OnSubError", (id, error))?; + api::on_sub_error(&self.lua, id, error)?; } } } @@ -373,7 +350,7 @@ impl PathOfBuilding { /// Calls PoB's `CanExit` handler. Used for unsaved changes prompt. pub fn can_exit(&self) -> bool { - call_callback::<(), bool>(&self.lua, "CanExit", ()).unwrap_or(false) + api::can_exit(&self.lua).unwrap_or(false) } /// Attaches the render-target window to the context diff --git a/src/pob/api.rs b/src/pob/api.rs index 4882f2f..9c8f0fb 100644 --- a/src/pob/api.rs +++ b/src/pob/api.rs @@ -1,19 +1,17 @@ -pub use crate::pob::api::callback::{call_callback, get_callback}; -use crate::{ - pob::Context, - pob::api::{ - callback::{get_custom_callback, set_custom_callback, set_main_object}, +use crate::pob::{ + api::{ + callback::{call_callback, get_custom_callback, set_custom_callback, set_main_object}, clipboard::{copy, paste}, compression::{deflate, inflate}, console::{console_clear, console_execute, console_print_table, console_printf}, + general::{exit, get_time, open_url, render_init, restart, strip_escapes, take_screenshot}, image_handle::register_image_handle_api, - input::{get_cursor_pos, is_key_down}, + input::{get_cursor_pos, is_key_down, set_cursor_pos, show_cursor}, lua::{load_module, protected_call, protected_load_module}, paths::{ get_runtime_path, get_script_path, get_user_path, get_work_dir, make_dir, remove_dir, set_work_dir, }, - rendering::PoBString, search_handle::new_search_handle, subscript::{abort_subscript, is_subscript_running, launch_subscript}, window::{ @@ -21,14 +19,15 @@ use crate::{ set_foreground, set_window_title, }, }, + subscript::NativeMultiValue, }; -use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic}; -use std::time::{SystemTime, UNIX_EPOCH}; +use mlua::{Lua, MultiValue, Result as LuaResult}; mod callback; mod clipboard; mod compression; mod console; +mod general; mod image_handle; mod input; mod lua; @@ -69,8 +68,6 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> { globals.set("Restart", lua.create_function(restart)?)?; globals.set("OpenURL", lua.create_function(open_url)?)?; globals.set("RenderInit", lua.create_function(render_init)?)?; - - let take_screenshot = |_: &Lua, ()| -> LuaResult<()> { Ok(()) }; // stub globals.set("TakeScreenshot", lua.create_function(take_screenshot)?)?; // compression @@ -89,6 +86,8 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> { // input globals.set("GetCursorPos", lua.create_function(get_cursor_pos)?)?; + globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?; + globals.set("ShowCursor", lua.create_function(show_cursor)?)?; globals.set("IsKeyDown", lua.create_function(is_key_down)?)?; // window @@ -121,53 +120,32 @@ pub fn register_globals(lua: &Lua) -> LuaResult<()> { )?; globals.set("AbortSubScript", lua.create_function(abort_subscript)?)?; - // NOTE: not used by PoB - let set_cursor_pos = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; - let show_cursor = |_: &Lua, ()| -> LuaResult<()> { unimplemented!() }; - globals.set("SetCursorPos", lua.create_function(set_cursor_pos)?)?; - globals.set("ShowCursor", lua.create_function(show_cursor)?)?; - // rendering rendering::register_globals(lua)?; Ok(()) } -fn get_time(_l: &Lua, _: ()) -> LuaResult { - Ok(SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap() - .as_millis()) +// Registers Lua callback functions that can be called from Rust +macro_rules! define_callbacks { + ($($fn_name:ident => $lua_name:literal ($($arg:ident : $arg_ty:ty),*) -> $ret_ty:ty;)*) => { + $( + pub fn $fn_name(lua: &Lua, $($arg: $arg_ty),*) -> LuaResult<$ret_ty> { + call_callback(lua, $lua_name, ($($arg,)*)) + } + )* + }; } -fn strip_escapes(_: &Lua, text: String) -> LuaResult { - Ok(PoBString(&text).strip_escapes()) -} - -fn exit(l: &Lua, exit_msg: Option) -> LuaResult<()> { - if let Some(exit_msg) = exit_msg { - println!("{exit_msg}"); - } - let mut ctx = l.app_data_mut::().unwrap(); - ctx.should_exit = true; - Ok(()) -} - -fn restart(l: &Lua, _: ()) -> LuaResult<()> { - let mut ctx = l.app_data_mut::().unwrap(); - ctx.needs_restart = true; - Ok(()) -} - -fn open_url(l: &Lua, url: String) -> LuaResult { - match open::that(url) { - Ok(()) => ().into_lua_multi(l), - Err(_) => "Unable to open url!".into_lua_multi(l), - } -} - -fn render_init(l: &Lua, features: Variadic) -> LuaResult<()> { - let mut ctx = l.app_data_mut::().unwrap(); - ctx.is_dpi_aware = features.iter().any(|feat| feat == "DPI_AWARE"); - Ok(()) +define_callbacks! { + on_init => "OnInit"() -> (); + on_exit => "OnExit"() -> (); + on_frame => "OnFrame"() -> (); + can_exit => "CanExit"() -> bool; + on_key_down => "OnKeyDown"(key: &str, double_click: bool) -> (); + on_key_up => "OnKeyUp"(key: &str) -> (); + on_char => "OnChar"(ch: char) -> (); + on_sub_call => "OnSubCall"(name: String, args: NativeMultiValue) -> MultiValue; + on_sub_finished => "OnSubFinished"(id: u64, return_values: NativeMultiValue) -> (); + on_sub_error => "OnSubError"(id: u64, error_msg: String) -> (); } diff --git a/src/pob/api/callback.rs b/src/pob/api/callback.rs index 6cfd72d..bb9fb47 100644 --- a/src/pob/api/callback.rs +++ b/src/pob/api/callback.rs @@ -1,45 +1,49 @@ +//! During initialization, PoB calls `set_main_object` with a callback table. Functions defined in +//! this table are used to call back into Lua from Rust. +//! +//! Custom callback functions can be added with `set_custom_callback` and retrieved with +//! `get_custom_callback`. Functions defined in the main object are shadowed by custom functions +//! with the same name. use mlua::{FromLuaMulti, Function, IntoLuaMulti, Lua, Result as LuaResult, Table, Value}; -// During initialization, PoB calls `SetMainObject` with a callback table. -// Functions defined in this table are used to call back into Lua from Rust. -// Custom callback functions can be added with `SetCallback` and retrieved -// with `GetCallback`. const CALLBACK_REGISTRY_NAME: &str = "uicallbacks"; -pub fn get_callback(lua: &Lua, name: &str) -> LuaResult { - let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?; - let callback_function: Value = callback_table.get(name)?; - if callback_function.is_function() { - // function defined through `SetCallback` - return Ok(callback_function.as_function().unwrap().clone()); - } - // look for function in `MainObject` - let main_object: Table = callback_table.get("MainObject")?; - let callback_function: Value = main_object.get(name)?; - if callback_function.is_function() { - // these functions expect `MainObject` as first argument so we bind it here - return callback_function.as_function().unwrap().bind(main_object); - } - Err(anyhow::anyhow!("Function '{name}' not found").into()) -} - pub fn set_main_object(l: &Lua, main_object: Table) -> LuaResult<()> { let callback_table = l.create_table()?; callback_table.set("MainObject", main_object)?; - l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table)?; - Ok(()) + l.set_named_registry_value(CALLBACK_REGISTRY_NAME, callback_table) } pub fn set_custom_callback(l: &Lua, (name, func): (String, Function)) -> LuaResult<()> { let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?; - callback_table.set(name, func)?; - Ok(()) + callback_table.set(name, func) } pub fn get_custom_callback(l: &Lua, name: String) -> LuaResult { let callback_table: Table = l.named_registry_value(CALLBACK_REGISTRY_NAME)?; - let callback_function: Function = callback_table.get(name)?; - Ok(callback_function) + callback_table.get(name) +} + +/// Looks up a callback by name. +/// +/// Custom callbacks shadow callbacks defined in main object. +fn get_callback(lua: &Lua, name: &str) -> LuaResult { + let callback_table: Table = lua.named_registry_value(CALLBACK_REGISTRY_NAME)?; + + // check for custom callbacks first + if let Value::Function(f) = callback_table.get(name)? { + return Ok(f); + } + + // then look look in main object + if let Value::Table(main_object) = callback_table.get("MainObject")? + && let Value::Function(f) = main_object.get(name)? + { + // these functions expect the main object as first argument so we bind it here + return f.bind(main_object); + } + + Err(anyhow::anyhow!("Callback '{name}' not found").into()) } #[inline] diff --git a/src/pob/api/general.rs b/src/pob/api/general.rs new file mode 100644 index 0000000..378f8ed --- /dev/null +++ b/src/pob/api/general.rs @@ -0,0 +1,47 @@ +use crate::pob::{Context, api::rendering::PoBString}; +use mlua::{IntoLuaMulti, Lua, MultiValue, Result as LuaResult, Variadic}; +use std::time::{SystemTime, UNIX_EPOCH}; + +pub fn get_time(_l: &Lua, _: ()) -> LuaResult { + Ok(SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis()) +} + +pub fn strip_escapes(_: &Lua, text: String) -> LuaResult { + Ok(PoBString(&text).strip_escapes()) +} + +pub fn exit(l: &Lua, exit_msg: Option) -> LuaResult<()> { + if let Some(exit_msg) = exit_msg { + println!("{exit_msg}"); + } + let mut ctx = l.app_data_mut::().unwrap(); + ctx.should_exit = true; + Ok(()) +} + +pub fn restart(l: &Lua, _: ()) -> LuaResult<()> { + let mut ctx = l.app_data_mut::().unwrap(); + ctx.needs_restart = true; + Ok(()) +} + +pub fn open_url(l: &Lua, url: String) -> LuaResult { + match open::that(url) { + Ok(()) => ().into_lua_multi(l), + Err(_) => "Unable to open url!".into_lua_multi(l), + } +} + +pub fn render_init(l: &Lua, features: Variadic) -> LuaResult<()> { + let mut ctx = l.app_data_mut::().unwrap(); + ctx.is_dpi_aware = features.iter().any(|feat| feat == "DPI_AWARE"); + Ok(()) +} + +pub fn take_screenshot(_l: &Lua, _: ()) -> LuaResult<()> { + log::warn!("take_screenshot is not implemented!"); + Ok(()) +} diff --git a/src/pob/api/input.rs b/src/pob/api/input.rs index 5ac739d..f49e408 100644 --- a/src/pob/api/input.rs +++ b/src/pob/api/input.rs @@ -10,6 +10,14 @@ pub fn get_cursor_pos(l: &Lua, _: ()) -> LuaResult<(u32, u32)> { Ok((pos.x as u32, pos.y as u32)) } +pub fn set_cursor_pos(_l: &Lua, _: ()) -> LuaResult<()> { + unimplemented!() +} + +pub fn show_cursor(_l: &Lua, _: ()) -> LuaResult<()> { + unimplemented!() +} + pub fn is_key_down(l: &Lua, key_name: String) -> LuaResult { let ctx = l.app_data_ref::().unwrap(); diff --git a/src/pob/subscript.rs b/src/pob/subscript.rs index 6044747..6a06ae3 100644 --- a/src/pob/subscript.rs +++ b/src/pob/subscript.rs @@ -1,6 +1,6 @@ -use crate::{pob::PathOfBuilding, pob::api::get_callback}; +use crate::{pob::PathOfBuilding, pob::api}; use anyhow::{Result, anyhow}; -use mlua::{Function, Integer, IntoLuaMulti, Lua, MultiValue, Number, Value}; +use mlua::{Integer, IntoLuaMulti, Lua, MultiValue, Number, Value}; use std::{ path::PathBuf, sync::mpsc::{Receiver, Sender, channel}, @@ -200,18 +200,14 @@ impl Subscript { Err(_) => return, }; - // the function that needs to be called in the main Lua instance - let func: Result = get_callback(lua, "OnSubCall"); - match call { SubscriptCall::Blocking { function_name, arguments, reply_tx: return_values_sender, } => { - let result = func + let result = api::on_sub_call(lua, function_name, arguments) .map_err(anyhow::Error::from) - .and_then(|f| Ok(f.call::((function_name, arguments))?)) .and_then(NativeMultiValue::try_from); // if the subscript's thread has already gone away, there's nowhere to send the // result, so ignore the error @@ -221,10 +217,8 @@ impl Subscript { function_name, arguments, } => { - if let Ok(func) = func { - // return values of non-blocking calls are discarded - let _ = func.call::<()>((function_name, arguments)); - } + // return values and errors of non-blocking calls are discarded + let _ = api::on_sub_call(lua, function_name, arguments); } } }