1use std::ffi::{c_char, c_void, CStr};
18use std::fmt;
19use std::ptr::{self, NonNull};
20use std::sync::atomic::AtomicBool;
21
22use crate::error::{check, Error, ErrorCode, Result};
23use crate::event::{read_sized, Event, Payload};
24use crate::host::Host;
25use crate::panic::run_callback;
26use crate::sys::{
27 AnvilMapMode, AnvilMapModeChange, AnvilMapModeInfo, AnvilMapModesService,
28 ANVIL_MAP_MODES_SERVICE_VERSION, ANVIL_MAP_NO_COLOR, ANVIL_MAP_TAB_1, ANVIL_MAP_TAB_2,
29 ANVIL_MAP_TAB_3, ANVIL_MAP_TAB_4, ANVIL_MAP_TAB_DEFAULT,
30};
31use crate::table::Table;
32use crate::text::{c_string, static_str};
33
34pub const SERVICE: &CStr = c"anvil-map.modes";
36pub const VERSION: u32 = ANVIL_MAP_MODES_SERVICE_VERSION;
38
39pub const NO_COLOR: u32 = ANVIL_MAP_NO_COLOR;
42
43pub const fn rgb(r: u8, g: u8, b: u8) -> u32 {
45 ((r as u32) << 16) | ((g as u32) << 8) | b as u32
46}
47
48#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
52pub enum Tab {
53 #[default]
55 Default,
56 Political,
58 Terrain,
60 Trade,
62 Diplomacy,
64}
65
66impl Tab {
67 const fn raw(self) -> u32 {
68 (match self {
69 Self::Default => ANVIL_MAP_TAB_DEFAULT,
70 Self::Political => ANVIL_MAP_TAB_1,
71 Self::Terrain => ANVIL_MAP_TAB_2,
72 Self::Trade => ANVIL_MAP_TAB_3,
73 Self::Diplomacy => ANVIL_MAP_TAB_4,
74 }) as u32
75 }
76}
77
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct ModeInfo<'a> {
81 pub tab: Tab,
83 pub id: &'a str,
85 pub label: &'a str,
87 pub description: Option<&'a str>,
89 pub sprite: Option<&'a str>,
92}
93
94impl<'a> ModeInfo<'a> {
95 pub const fn new(id: &'a str, label: &'a str) -> Self {
97 Self {
98 tab: Tab::Default,
99 id,
100 label,
101 description: None,
102 sprite: None,
103 }
104 }
105}
106
107#[derive(Clone, Copy, PartialEq, Eq, Hash)]
109pub struct Mode {
110 raw: NonNull<AnvilMapMode>,
111}
112
113unsafe impl Send for Mode {}
116unsafe impl Sync for Mode {}
118
119impl fmt::Debug for Mode {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.debug_tuple("Mode").field(&self.raw).finish()
122 }
123}
124
125impl Mode {
126 fn from_raw(raw: *const AnvilMapMode) -> Option<Self> {
127 NonNull::new(raw.cast_mut()).map(|raw| Self { raw })
128 }
129
130 pub fn as_raw(&self) -> *const AnvilMapMode {
132 self.raw.as_ptr()
133 }
134}
135
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub struct ModeChange {
139 pub mode: Option<Mode>,
141 pub id: Option<&'static str>,
143}
144
145unsafe impl Payload for ModeChange {
148 unsafe fn read(raw: *const c_void) -> Option<Self> {
149 let change = unsafe { read_sized::<AnvilMapModeChange>(raw) }?;
151 Some(Self {
152 mode: Mode::from_raw(change.mode),
153 id: unsafe { static_str(change.id) },
155 })
156 }
157}
158
159pub const SHOWN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.shown") };
163pub const HIDDEN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.hidden") };
167
168#[derive(Clone, Copy)]
170pub struct MapModes {
171 table: Table<AnvilMapModesService>,
172}
173
174impl fmt::Debug for MapModes {
175 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
176 f.debug_struct("MapModes")
177 .field("size", &self.table.size())
178 .finish()
179 }
180}
181
182struct DescribeAdapter<F> {
183 handler: F,
184 panicked: AtomicBool,
185}
186
187unsafe fn write_lines(lines: &str, text: *mut c_char, capacity: usize) -> usize {
193 let end = lines.find('\0').unwrap_or(lines.len());
194 let mut length = end.min(capacity - 1);
195 while !lines.is_char_boundary(length) {
196 length -= 1;
197 }
198 unsafe {
200 ptr::copy_nonoverlapping(lines.as_ptr(), text.cast::<u8>(), length);
201 *text.add(length) = 0;
202 }
203 length
204}
205
206unsafe extern "C" fn describe_adapter<F>(
207 context: *mut c_void,
208 mode: *const AnvilMapMode,
209 province: i32,
210 text: *mut c_char,
211 capacity: usize,
212) -> usize
213where
214 F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
215{
216 let adapter = unsafe { &*context.cast::<DescribeAdapter<F>>() };
218 let Some(mode) = Mode::from_raw(mode) else {
219 return 0;
220 };
221 if text.is_null() || capacity == 0 {
222 return 0;
223 }
224 run_callback("map mode tooltip", &adapter.panicked, 0, || {
225 match (adapter.handler)(mode, province) {
226 Some(lines) => unsafe { write_lines(&lines, text, capacity) },
228 None => 0,
229 }
230 })
231}
232
233impl MapModes {
234 pub fn get(host: &Host) -> Option<Self> {
236 let table = unsafe { host.service::<AnvilMapModesService>(SERVICE, VERSION) }?;
238 Some(Self { table })
239 }
240
241 pub fn c_api(&self) -> Table<AnvilMapModesService> {
243 self.table
244 }
245
246 pub fn register(&self, info: &ModeInfo<'_>) -> Result<Mode> {
253 self.register_raw(info, None, ptr::null_mut())
254 }
255
256 pub fn register_with_tooltip<F>(&self, info: &ModeInfo<'_>, describe: F) -> Result<Mode>
263 where
264 F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
265 {
266 let adapter: &'static DescribeAdapter<F> = Box::leak(Box::new(DescribeAdapter {
268 handler: describe,
269 panicked: AtomicBool::new(false),
270 }));
271 self.register_raw(
272 info,
273 Some(describe_adapter::<F>),
274 ptr::from_ref(adapter).cast_mut().cast(),
275 )
276 }
277
278 fn register_raw(
279 &self,
280 info: &ModeInfo<'_>,
281 describe: crate::sys::AnvilMapDescribe,
282 context: *mut c_void,
283 ) -> Result<Mode> {
284 let f = function!(self.table, AnvilMapModesService, register_mode)?;
285 let id = c_string(info.id);
286 let label = c_string(info.label);
287 let description = info.description.map(c_string);
288 let sprite = info.sprite.map(c_string);
289 let raw_info = AnvilMapModeInfo {
290 size: std::mem::size_of::<AnvilMapModeInfo>() as u32,
291 tab: info.tab.raw(),
292 id: id.as_ptr(),
293 label: label.as_ptr(),
294 description: description
295 .as_ref()
296 .map_or(ptr::null(), |text| text.as_ptr()),
297 sprite: sprite.as_ref().map_or(ptr::null(), |text| text.as_ptr()),
298 describe,
299 context,
300 };
301 let mut out: *const AnvilMapMode = ptr::null();
302 check(unsafe { f(&raw_info, &mut out) }, || {
305 format!("map mode register {:?}", info.id)
306 })?;
307 Mode::from_raw(out).ok_or_else(|| {
308 Error::new(
309 ErrorCode::Internal,
310 format!("map mode register {:?}: no mode", info.id),
311 )
312 })
313 }
314
315 pub fn set_colors(&self, mode: Mode, colors: &[u32]) -> Result<()> {
323 let f = function!(self.table, AnvilMapModesService, set_colors)?;
324 let count = u32::try_from(colors.len()).map_err(|_| {
325 Error::new(
326 ErrorCode::InvalidArgument,
327 "map mode set_colors: too many colours",
328 )
329 })?;
330 check(unsafe { f(mode.as_raw(), colors.as_ptr(), count) }, || {
332 "map mode set_colors"
333 })
334 }
335
336 pub fn mode_id(&self, number: i32) -> Option<&'static str> {
339 let f = function!(self.table, AnvilMapModesService, mode_id).ok()?;
340 unsafe { static_str(f(number)) }
342 }
343
344 pub fn shown(&self) -> Option<Mode> {
346 let f = function!(self.table, AnvilMapModesService, shown).ok()?;
347 Mode::from_raw(unsafe { f() })
349 }
350
351 pub fn id(&self, mode: Mode) -> Option<&'static str> {
353 let f = function!(self.table, AnvilMapModesService, id).ok()?;
354 unsafe { static_str(f(mode.as_raw())) }
356 }
357
358 pub fn show(&self, mode: Mode) -> Result<()> {
363 let f = function!(self.table, AnvilMapModesService, show)?;
364 check(unsafe { f(mode.as_raw()) }, || "map mode show")
366 }
367}