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 AnvilMapLegendEntry, 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 LEGEND_MAX: usize = crate::sys::ANVIL_MAP_LEGEND_MAX as usize;
45
46pub const fn rgb(r: u8, g: u8, b: u8) -> u32 {
48 ((r as u32) << 16) | ((g as u32) << 8) | b as u32
49}
50
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
55pub enum Tab {
56 #[default]
58 Default,
59 Political,
61 Terrain,
63 Trade,
65 Diplomacy,
67}
68
69impl Tab {
70 const fn raw(self) -> u32 {
71 (match self {
72 Self::Default => ANVIL_MAP_TAB_DEFAULT,
73 Self::Political => ANVIL_MAP_TAB_1,
74 Self::Terrain => ANVIL_MAP_TAB_2,
75 Self::Trade => ANVIL_MAP_TAB_3,
76 Self::Diplomacy => ANVIL_MAP_TAB_4,
77 }) as u32
78 }
79}
80
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
83pub struct ModeInfo<'a> {
84 pub tab: Tab,
86 pub id: &'a str,
88 pub label: &'a str,
90 pub description: Option<&'a str>,
92 pub sprite: Option<&'a str>,
95}
96
97impl<'a> ModeInfo<'a> {
98 pub const fn new(id: &'a str, label: &'a str) -> Self {
100 Self {
101 tab: Tab::Default,
102 id,
103 label,
104 description: None,
105 sprite: None,
106 }
107 }
108}
109
110#[derive(Clone, Copy, PartialEq, Eq, Hash)]
112pub struct Mode {
113 raw: NonNull<AnvilMapMode>,
114}
115
116unsafe impl Send for Mode {}
119unsafe impl Sync for Mode {}
121
122impl fmt::Debug for Mode {
123 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
124 f.debug_tuple("Mode").field(&self.raw).finish()
125 }
126}
127
128impl Mode {
129 fn from_raw(raw: *const AnvilMapMode) -> Option<Self> {
130 NonNull::new(raw.cast_mut()).map(|raw| Self { raw })
131 }
132
133 pub fn as_raw(&self) -> *const AnvilMapMode {
135 self.raw.as_ptr()
136 }
137}
138
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
141pub struct ModeChange {
142 pub mode: Option<Mode>,
144 pub id: Option<&'static str>,
146}
147
148unsafe impl Payload for ModeChange {
151 unsafe fn read(raw: *const c_void) -> Option<Self> {
152 let change = unsafe { read_sized::<AnvilMapModeChange>(raw) }?;
154 Some(Self {
155 mode: Mode::from_raw(change.mode),
156 id: unsafe { static_str(change.id) },
158 })
159 }
160}
161
162pub const SHOWN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.shown") };
166pub const HIDDEN: Event<ModeChange> = unsafe { Event::new(c"anvil-map.hidden") };
170
171#[derive(Clone, Copy)]
173pub struct MapModes {
174 table: Table<AnvilMapModesService>,
175}
176
177impl fmt::Debug for MapModes {
178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179 f.debug_struct("MapModes")
180 .field("size", &self.table.size())
181 .finish()
182 }
183}
184
185struct DescribeAdapter<F> {
186 handler: F,
187 panicked: AtomicBool,
188}
189
190unsafe fn write_lines(lines: &str, text: *mut c_char, capacity: usize) -> usize {
196 let end = lines.find('\0').unwrap_or(lines.len());
197 let mut length = end.min(capacity - 1);
198 while !lines.is_char_boundary(length) {
199 length -= 1;
200 }
201 unsafe {
203 ptr::copy_nonoverlapping(lines.as_ptr(), text.cast::<u8>(), length);
204 *text.add(length) = 0;
205 }
206 length
207}
208
209unsafe extern "C" fn describe_adapter<F>(
210 context: *mut c_void,
211 mode: *const AnvilMapMode,
212 province: i32,
213 text: *mut c_char,
214 capacity: usize,
215) -> usize
216where
217 F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
218{
219 let adapter = unsafe { &*context.cast::<DescribeAdapter<F>>() };
221 let Some(mode) = Mode::from_raw(mode) else {
222 return 0;
223 };
224 if text.is_null() || capacity == 0 {
225 return 0;
226 }
227 run_callback("map mode tooltip", &adapter.panicked, 0, || {
228 match (adapter.handler)(mode, province) {
229 Some(lines) => unsafe { write_lines(&lines, text, capacity) },
231 None => 0,
232 }
233 })
234}
235
236impl MapModes {
237 pub fn get(host: &Host) -> Option<Self> {
239 let table = unsafe { host.service::<AnvilMapModesService>(SERVICE, VERSION) }?;
241 Some(Self { table })
242 }
243
244 pub fn c_api(&self) -> Table<AnvilMapModesService> {
246 self.table
247 }
248
249 pub fn register(&self, info: &ModeInfo<'_>) -> Result<Mode> {
256 self.register_raw(info, None, ptr::null_mut())
257 }
258
259 pub fn register_with_tooltip<F>(&self, info: &ModeInfo<'_>, describe: F) -> Result<Mode>
266 where
267 F: Fn(Mode, i32) -> Option<String> + Send + Sync + 'static,
268 {
269 let adapter: &'static DescribeAdapter<F> = Box::leak(Box::new(DescribeAdapter {
271 handler: describe,
272 panicked: AtomicBool::new(false),
273 }));
274 self.register_raw(
275 info,
276 Some(describe_adapter::<F>),
277 ptr::from_ref(adapter).cast_mut().cast(),
278 )
279 }
280
281 fn register_raw(
282 &self,
283 info: &ModeInfo<'_>,
284 describe: crate::sys::AnvilMapDescribe,
285 context: *mut c_void,
286 ) -> Result<Mode> {
287 let f = function!(self.table, AnvilMapModesService, register_mode)?;
288 let id = c_string(info.id);
289 let label = c_string(info.label);
290 let description = info.description.map(c_string);
291 let sprite = info.sprite.map(c_string);
292 let raw_info = AnvilMapModeInfo {
293 size: std::mem::size_of::<AnvilMapModeInfo>() as u32,
294 tab: info.tab.raw(),
295 id: id.as_ptr(),
296 label: label.as_ptr(),
297 description: description
298 .as_ref()
299 .map_or(ptr::null(), |text| text.as_ptr()),
300 sprite: sprite.as_ref().map_or(ptr::null(), |text| text.as_ptr()),
301 describe,
302 context,
303 };
304 let mut out: *const AnvilMapMode = ptr::null();
305 check(unsafe { f(&raw_info, &mut out) }, || {
308 format!("map mode register {:?}", info.id)
309 })?;
310 Mode::from_raw(out).ok_or_else(|| {
311 Error::new(
312 ErrorCode::Internal,
313 format!("map mode register {:?}: no mode", info.id),
314 )
315 })
316 }
317
318 pub fn set_colors(&self, mode: Mode, colors: &[u32]) -> Result<()> {
326 let f = function!(self.table, AnvilMapModesService, set_colors)?;
327 let count = u32::try_from(colors.len()).map_err(|_| {
328 Error::new(
329 ErrorCode::InvalidArgument,
330 "map mode set_colors: too many colours",
331 )
332 })?;
333 check(unsafe { f(mode.as_raw(), colors.as_ptr(), count) }, || {
335 "map mode set_colors"
336 })
337 }
338
339 pub fn mode_id(&self, number: i32) -> Option<&'static str> {
342 let f = function!(self.table, AnvilMapModesService, mode_id).ok()?;
343 unsafe { static_str(f(number)) }
345 }
346
347 pub fn shown(&self) -> Option<Mode> {
349 let f = function!(self.table, AnvilMapModesService, shown).ok()?;
350 Mode::from_raw(unsafe { f() })
352 }
353
354 pub fn id(&self, mode: Mode) -> Option<&'static str> {
356 let f = function!(self.table, AnvilMapModesService, id).ok()?;
357 unsafe { static_str(f(mode.as_raw())) }
359 }
360
361 pub fn show(&self, mode: Mode) -> Result<()> {
366 let f = function!(self.table, AnvilMapModesService, show)?;
367 check(unsafe { f(mode.as_raw()) }, || "map mode show")
369 }
370
371 pub fn set_legend(&self, mode: Mode, entries: &[(u32, &str)]) -> Result<()> {
378 let f = function!(self.table, AnvilMapModesService, set_legend)?;
379 let count = u32::try_from(entries.len()).map_err(|_| {
380 Error::new(
381 ErrorCode::InvalidArgument,
382 "map mode set_legend: too many entries",
383 )
384 })?;
385 let labels: Vec<_> = entries.iter().map(|(_, label)| c_string(label)).collect();
387 let raw: Vec<AnvilMapLegendEntry> = entries
388 .iter()
389 .zip(&labels)
390 .map(|((color, _), label)| AnvilMapLegendEntry {
391 color: *color,
392 reserved: 0,
393 label: label.as_ptr(),
394 })
395 .collect();
396 check(
399 unsafe {
400 f(
401 mode.as_raw(),
402 raw.as_ptr(),
403 count,
404 std::mem::size_of::<AnvilMapLegendEntry>() as u32,
405 )
406 },
407 || "map mode set_legend",
408 )
409 }
410}