use std::ffi::{c_char, c_void, CStr};
use std::fmt;
use std::ptr::{self, NonNull};
use std::sync::atomic::AtomicBool;
use crate::error::{check, Error, ErrorCode, Result};
use crate::event::{read_sized, Event, Payload};
use crate::host::Host;
use crate::panic::run_callback;
use crate::sys::{
AnvilMapLegendEntry, AnvilMapMode, AnvilMapModeChange, AnvilMapModeInfo, AnvilMapModesService,
ANVIL_MAP_MODES_SERVICE_VERSION, ANVIL_MAP_NO_COLOR, ANVIL_MAP_TAB_1, ANVIL_MAP_TAB_2,
ANVIL_MAP_TAB_3, ANVIL_MAP_TAB_4, ANVIL_MAP_TAB_DEFAULT,
};
use crate::table::Table;
use crate::text::{c_string, static_str};
pub const SERVICE: &CStr = c"anvil-map.modes";
pub const VERSION: u32 = ANVIL_MAP_MODES_SERVICE_VERSION;
pub const NO_COLOR: u32 = ANVIL_MAP_NO_COLOR;
pub const LEGEND_MAX: usize = crate::sys::ANVIL_MAP_LEGEND_MAX as usize;
pub const fn rgb(r: u8, g: u8, b: u8) -> u32 {
((r as u32) << 16) | ((g as u32) << 8) | b as u32
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum Tab {
#[default]
Default,
Political,
Terrain,
Trade,
Diplomacy,
}
impl Tab {
const fn raw(self) -> u32 {
(match self {
Self::Default => ANVIL_MAP_TAB_DEFAULT,
Self::Political => ANVIL_MAP_TAB_1,
Self::Terrain => ANVIL_MAP_TAB_2,
Self::Trade => ANVIL_MAP_TAB_3,
Self::Diplomacy => ANVIL_MAP_TAB_4,
}) as u32
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModeInfo<'a> {
pub tab: Tab,
pub id: &'a str,
pub label: &'a str,
pub description: Option<&'a str>,
pub sprite: Option<&'a str>,
}
impl<'a> ModeInfo<'a> {
pub const fn new(id: &'a str, label: &'a str) -> Self {
Self {
tab: Tab::Default,
id,
label,
description: None,
sprite: None,
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Mode {
raw: NonNull<AnvilMapMode>,
}
unsafe impl Send for Mode {}
unsafe impl Sync for Mode {}
impl fmt::Debug for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Mode").field(&self.raw).finish()
}
}
impl Mode {
fn from_raw(raw: *const AnvilMapMode) -> Option<Self> {
NonNull::new(raw.cast_mut()).map(|raw| Self { raw })
}
pub fn as_raw(&self) -> *const AnvilMapMode {
self.raw.as_ptr()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ModeChange {
pub mode: Option<Mode>,
pub id: Option<&'static str>,
}
unsafe impl Payload for ModeChange {
unsafe fn read(raw: *const c_void) -> Option<Self> {
let change = unsafe { read_sized::<AnvilMapModeChange>(raw) }?;
Some(Self {
mode: Mode::from_raw(change.mode),
id: unsafe { static_str(change.id) },
})
}
}
pub const SHOWN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.shown") };
pub const HIDDEN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.hidden") };
#[derive(Clone, Copy)]
pub struct MapModes {
table: Table<AnvilMapModesService>,
}
impl fmt::Debug for MapModes {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MapModes")
.field("size", &self.table.size())
.finish()
}
}
struct DescribeAdapter<F> {
handler: F,
panicked: AtomicBool,
}
unsafe fn write_lines(lines: &str, text: *mut c_char, capacity: usize) -> usize {
let end = lines.find('\0').unwrap_or(lines.len());
let mut length = end.min(capacity - 1);
while !lines.is_char_boundary(length) {
length -= 1;
}
unsafe {
ptr::copy_nonoverlapping(lines.as_ptr(), text.cast::<u8>(), length);
*text.add(length) = 0;
}
length
}
unsafe extern "C" fn describe_adapter<F>(
context: *mut c_void,
mode: *const AnvilMapMode,
province: i32,
text: *mut c_char,
capacity: usize,
) -> usize
where
F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
{
let adapter = unsafe { &*context.cast::<DescribeAdapter<F>>() };
let Some(mode) = Mode::from_raw(mode) else {
return 0;
};
if text.is_null() || capacity == 0 {
return 0;
}
run_callback("map mode tooltip", &adapter.panicked, 0, || {
match (adapter.handler)(mode, province) {
Some(lines) => unsafe { write_lines(&lines, text, capacity) },
None => 0,
}
})
}
impl MapModes {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilMapModesService>(SERVICE, VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> Table<AnvilMapModesService> {
self.table
}
pub fn register(&self, info: &ModeInfo<'_>) -> Result<Mode> {
self.register_raw(info, None, ptr::null_mut())
}
pub fn register_with_tooltip<F>(&self, info: &ModeInfo<'_>, describe: F) -> Result<Mode>
where
F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
{
let adapter: &'static DescribeAdapter<F> = Box::leak(Box::new(DescribeAdapter {
handler: describe,
panicked: AtomicBool::new(false),
}));
self.register_raw(
info,
Some(describe_adapter::<F>),
ptr::from_ref(adapter).cast_mut().cast(),
)
}
fn register_raw(
&self,
info: &ModeInfo<'_>,
describe: crate::sys::AnvilMapDescribe,
context: *mut c_void,
) -> Result<Mode> {
let f = function!(self.table, AnvilMapModesService, register_mode)?;
let id = c_string(info.id);
let label = c_string(info.label);
let description = info.description.map(c_string);
let sprite = info.sprite.map(c_string);
let raw_info = AnvilMapModeInfo {
size: std::mem::size_of::<AnvilMapModeInfo>() as u32,
tab: info.tab.raw(),
id: id.as_ptr(),
label: label.as_ptr(),
description: description
.as_ref()
.map_or(ptr::null(), |text| text.as_ptr()),
sprite: sprite.as_ref().map_or(ptr::null(), |text| text.as_ptr()),
describe,
context,
};
let mut out: *const AnvilMapMode = ptr::null();
check(unsafe { f(&raw_info, &mut out) }, || {
format!("map mode register {:?}", info.id)
})?;
Mode::from_raw(out).ok_or_else(|| {
Error::new(
ErrorCode::Internal,
format!("map mode register {:?}: no mode", info.id),
)
})
}
pub fn set_colors(&self, mode: Mode, colors: &[u32]) -> Result<()> {
let f = function!(self.table, AnvilMapModesService, set_colors)?;
let count = u32::try_from(colors.len()).map_err(|_| {
Error::new(
ErrorCode::InvalidArgument,
"map mode set_colors: too many colours",
)
})?;
check(unsafe { f(mode.as_raw(), colors.as_ptr(), count) }, || {
"map mode set_colors"
})
}
pub fn mode_id(&self, number: i32) -> Option<&'static str> {
let f = function!(self.table, AnvilMapModesService, mode_id).ok()?;
unsafe { static_str(f(number)) }
}
pub fn shown(&self) -> Option<Mode> {
let f = function!(self.table, AnvilMapModesService, shown).ok()?;
Mode::from_raw(unsafe { f() })
}
pub fn id(&self, mode: Mode) -> Option<&'static str> {
let f = function!(self.table, AnvilMapModesService, id).ok()?;
unsafe { static_str(f(mode.as_raw())) }
}
pub fn show(&self, mode: Mode) -> Result<()> {
let f = function!(self.table, AnvilMapModesService, show)?;
check(unsafe { f(mode.as_raw()) }, || "map mode show")
}
pub fn set_legend(&self, mode: Mode, entries: &[(u32, &str)]) -> Result<()> {
let f = function!(self.table, AnvilMapModesService, set_legend)?;
let count = u32::try_from(entries.len()).map_err(|_| {
Error::new(
ErrorCode::InvalidArgument,
"map mode set_legend: too many entries",
)
})?;
let labels: Vec<_> = entries.iter().map(|(_, label)| c_string(label)).collect();
let raw: Vec<AnvilMapLegendEntry> = entries
.iter()
.zip(&labels)
.map(|((color, _), label)| AnvilMapLegendEntry {
color: *color,
reserved: 0,
label: label.as_ptr(),
})
.collect();
check(
unsafe {
f(
mode.as_raw(),
raw.as_ptr(),
count,
std::mem::size_of::<AnvilMapLegendEntry>() as u32,
)
},
|| "map mode set_legend",
)
}
}