diff options
| author | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-08-10 15:41:31 +0200 |
|---|---|---|
| committer | Nathan Reiner <nathan@nathanreiner.xyz> | 2024-08-10 15:41:31 +0200 |
| commit | b747ca8af52129876b577a4f20f7105a05c6b002 (patch) | |
| tree | d976a5c3cd135dfecb1014246936bb7a8b525c4b /src/sheet/loader.rs | |
| parent | 4763d8ce3b833df1e7321a407b08666f69657fdb (diff) | |
add global fileloader registry
Diffstat (limited to 'src/sheet/loader.rs')
| -rw-r--r-- | src/sheet/loader.rs | 55 |
1 files changed, 55 insertions, 0 deletions
diff --git a/src/sheet/loader.rs b/src/sheet/loader.rs new file mode 100644 index 0000000..613d2a5 --- /dev/null +++ b/src/sheet/loader.rs @@ -0,0 +1,55 @@ +use std::{ + collections::HashMap, + path::Path, + sync::{Mutex, MutexGuard}, +}; + +use lazy_static::lazy_static; +use mlua::{Lua, UserData}; + +use crate::lua::{ownedfunction::OwnedFunction, runnable::Runnable}; + +use super::{register::SheetId, tablized::Tablized}; + +lazy_static! { + static ref GLOBAL_LOADER: Mutex<Loader> = Mutex::new(Loader::new()); +} + +#[derive(Default)] +pub struct Loader { + loaders: HashMap<String, Box<dyn Runnable<String, Tablized>>>, +} + +impl Loader { + pub fn new() -> Self { + Self { + loaders: HashMap::new(), + } + } + + pub fn load_sheet(&self, path: String, lua: &Lua) -> Option<SheetId> { + let p = Path::new(&path); + let loader = self.loaders.get(p.extension()?.to_str()?)?; + match loader.run(path, lua) { + Ok(table) => table.to_sheet(lua).ok(), + Err(_) => None, + } + } + + pub fn add(&mut self, extension: String, func: Box<dyn Runnable<String, Tablized>>) { + self.loaders.insert(extension, func); + } + + pub fn get() -> MutexGuard<'static, Loader> { + GLOBAL_LOADER.lock().unwrap() + } +} + +impl UserData for Loader { + fn add_methods<'lua, M: mlua::prelude::LuaUserDataMethods<'lua, Self>>(methods: &mut M) { + methods.add_function("add", |_, (extension, func): (String, OwnedFunction)| { + GLOBAL_LOADER.lock().unwrap().add(extension, Box::new(func)); + Ok(()) + }); + } +} |