use std::borrow::Cow;
use std::ffi::{c_char, c_void, CStr, CString};
use std::fmt;
use std::ptr;
use std::sync::atomic::AtomicBool;
use crate::error::{check, Error, ErrorCode, Result};
use crate::host::Host;
use crate::panic::run_callback;
use crate::sys::{
AnvilGameTag, AnvilScriptCall, AnvilScriptDay, AnvilScriptDayEndService, AnvilScriptEffect,
AnvilScriptEffectsService, ANVIL_SCRIPT_DAY_END_SERVICE_VERSION, ANVIL_SCRIPT_DAY_NEW_MONTH,
ANVIL_SCRIPT_DAY_NEW_YEAR, ANVIL_SCRIPT_EFFECTS_SERVICE_VERSION,
};
use crate::Tag;
pub const SERVICE: &CStr = c"anvil-script.day_end";
pub const VERSION: u32 = ANVIL_SCRIPT_DAY_END_SERVICE_VERSION;
pub const EFFECTS_SERVICE: &CStr = c"anvil-script.effects";
pub const EFFECTS_VERSION: u32 = ANVIL_SCRIPT_EFFECTS_SERVICE_VERSION;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Call<'a> {
pub key: &'a str,
pub value: Cow<'a, str>,
pub province: Option<i32>,
pub country: Option<Tag>,
}
impl<'a> Call<'a> {
unsafe fn from_raw(raw: *const AnvilScriptCall) -> Option<Self> {
let raw = unsafe { raw.as_ref() }?;
if raw.key.is_null() {
return None;
}
let key = unsafe { CStr::from_ptr(raw.key) }.to_str().ok()?;
let value = if raw.value.is_null() {
Cow::Borrowed("")
} else {
unsafe { CStr::from_ptr(raw.value) }.to_string_lossy()
};
let province = (raw.scope.province != 0).then_some(raw.scope.province);
let country = Tag::from_raw(&AnvilGameTag {
text: raw.scope.country,
});
Some(Self {
key,
value,
province,
country,
})
}
}
#[derive(Clone, Copy)]
pub struct Effects {
table: &'static AnvilScriptEffectsService,
}
impl fmt::Debug for Effects {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Effects")
.field("size", &self.table.size)
.finish()
}
}
struct EffectAdapter<E, D> {
execute: E,
describe: Option<D>,
execute_panicked: AtomicBool,
describe_panicked: AtomicBool,
}
unsafe extern "C" fn execute_adapter<E, D>(context: *mut c_void, call: *const AnvilScriptCall)
where
E: Fn(&Call<'_>) + Send + Sync + 'static,
D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
{
let adapter = unsafe { &*context.cast::<EffectAdapter<E, D>>() };
let Some(call) = (unsafe { Call::from_raw(call) }) else {
return;
};
run_callback("script effect", &adapter.execute_panicked, (), || {
(adapter.execute)(&call)
});
}
unsafe fn write_line(line: &str, utf8: *mut c_char, capacity: u32) -> u32 {
let end = line.find(['\n', '\r', '\0']).unwrap_or(line.len());
let line = &line[..end];
if capacity > 0 && !utf8.is_null() {
let mut length = line.len().min(capacity as usize - 1);
while !line.is_char_boundary(length) {
length -= 1;
}
unsafe {
ptr::copy_nonoverlapping(line.as_ptr(), utf8.cast::<u8>(), length);
*utf8.add(length) = 0;
}
}
u32::try_from(line.len()).unwrap_or(u32::MAX)
}
unsafe extern "C" fn describe_adapter<E, D>(
context: *mut c_void,
call: *const AnvilScriptCall,
utf8: *mut c_char,
capacity: u32,
) -> u32
where
E: Fn(&Call<'_>) + Send + Sync + 'static,
D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
{
let adapter = unsafe { &*context.cast::<EffectAdapter<E, D>>() };
let Some(describe) = adapter.describe.as_ref() else {
return 0;
};
let Some(call) = (unsafe { Call::from_raw(call) }) else {
return 0;
};
run_callback(
"script effect tooltip",
&adapter.describe_panicked,
0,
|| {
match describe(&call) {
Some(line) if !line.is_empty() => unsafe { write_line(&line, utf8, capacity) },
_ => 0,
}
},
)
}
type NoDescribe = fn(&Call<'_>) -> Option<String>;
impl Effects {
pub fn get(host: &Host) -> Option<Self> {
let table =
unsafe { host.service::<AnvilScriptEffectsService>(EFFECTS_SERVICE, EFFECTS_VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> &'static AnvilScriptEffectsService {
self.table
}
pub fn register<E>(&self, host: &Host, key: &str, execute: E) -> Result<()>
where
E: Fn(&Call<'_>) + Send + Sync + 'static,
{
self.register_raw::<E, NoDescribe>(host, key, execute, None)
}
pub fn register_with_tooltip<E, D>(
&self,
host: &Host,
key: &str,
execute: E,
describe: D,
) -> Result<()>
where
E: Fn(&Call<'_>) + Send + Sync + 'static,
D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
{
self.register_raw(host, key, execute, Some(describe))
}
fn register_raw<E, D>(
&self,
host: &Host,
key: &str,
execute: E,
describe: Option<D>,
) -> Result<()>
where
E: Fn(&Call<'_>) + Send + Sync + 'static,
D: Fn(&Call<'_>) -> Option<String> + Send + Sync + 'static,
{
let f = function!(self.table, AnvilScriptEffectsService, register_effect)?;
let c_key = CString::new(key).map_err(|_| {
Error::new(
ErrorCode::InvalidArgument,
format!("register effect {key:?}: the key holds a NUL"),
)
})?;
let has_describe = describe.is_some();
let adapter: &'static EffectAdapter<E, D> = Box::leak(Box::new(EffectAdapter {
execute,
describe,
execute_panicked: AtomicBool::new(false),
describe_panicked: AtomicBool::new(false),
}));
let effect = AnvilScriptEffect {
size: std::mem::size_of::<AnvilScriptEffect>() as u32,
flags: 0,
key: c_key.as_ptr(),
execute: Some(execute_adapter::<E, D>),
describe: if has_describe {
Some(describe_adapter::<E, D>)
} else {
None
},
context: ptr::from_ref(adapter).cast_mut().cast(),
};
check(unsafe { f(host.raw_plugin(), &effect) }, || {
format!("register effect {key:?}")
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Day {
pub year: i32,
pub month: i32,
pub day: i32,
pub new_month: bool,
pub new_year: bool,
}
impl Day {
fn from_raw(raw: &AnvilScriptDay) -> Self {
Self {
year: raw.year,
month: raw.month,
day: raw.day,
new_month: raw.flags & ANVIL_SCRIPT_DAY_NEW_MONTH != 0,
new_year: raw.flags & ANVIL_SCRIPT_DAY_NEW_YEAR != 0,
}
}
}
#[derive(Clone, Copy)]
pub struct DayEnd {
table: &'static AnvilScriptDayEndService,
}
impl fmt::Debug for DayEnd {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DayEnd")
.field("size", &self.table.size)
.finish()
}
}
struct Adapter<F> {
handler: F,
panicked: AtomicBool,
}
unsafe extern "C" fn day_end_adapter<F>(context: *mut c_void, day: *const AnvilScriptDay)
where
F: Fn(&Day) + Send + Sync + 'static,
{
let adapter = unsafe { &*context.cast::<Adapter<F>>() };
let Some(raw) = (unsafe { day.as_ref() }) else {
return;
};
let day = Day::from_raw(raw);
run_callback("day end", &adapter.panicked, (), || (adapter.handler)(&day));
}
impl DayEnd {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilScriptDayEndService>(SERVICE, VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> &'static AnvilScriptDayEndService {
self.table
}
pub fn subscribe<F>(&self, host: &Host, handler: F) -> Result<()>
where
F: Fn(&Day) + Send + Sync + 'static,
{
let f = function!(self.table, AnvilScriptDayEndService, subscribe)?;
let adapter: &'static Adapter<F> = Box::leak(Box::new(Adapter {
handler,
panicked: AtomicBool::new(false),
}));
check(
unsafe {
f(
host.raw_plugin(),
Some(day_end_adapter::<F>),
ptr::from_ref(adapter).cast_mut().cast(),
)
},
|| "day end subscribe".to_string(),
)
}
}