Skip to main content

anvil/
panel.rs

1//! `anvil-overlay.panel`: a window of the plugin in Anvil's overlay. The
2//! plugin hands over rows of text and buttons and the overlay draws them
3//! (`anvil_panel.h`).
4//!
5//! Depend on the overlay in plugin.toml (`[[dependencies]] id =
6//! "anvil-overlay"`, `optional = true` for a plugin that also works without a
7//! window) and look the service up with [`Panels::get`]. A panel changes
8//! nothing in the game, so it needs no `affects_gameplay = true`.
9//!
10//! Text is UTF-8, and Anvil translates none of it: ask
11//! [`Panels::language`]. Every call may come from any thread; rows are
12//! copied. A panel lives until the process ends. Clicks run on the game's
13//! main thread after an outer frame (as anvil-game work), so a click handler
14//! may read [`World`](crate::world::World).
15
16use std::ffi::{c_void, CString};
17use std::fmt;
18use std::ptr::{self, NonNull};
19use std::sync::atomic::AtomicBool;
20
21use crate::error::{check, Result};
22use crate::host::Host;
23use crate::panic::run_callback;
24use crate::sys::{
25    AnvilPanel, AnvilPanelRow, AnvilPanelService, ANVIL_PANEL_BUTTON, ANVIL_PANEL_SEPARATOR,
26    ANVIL_PANEL_SERVICE_VERSION, ANVIL_PANEL_SWATCH, ANVIL_PANEL_TEXT,
27};
28use crate::table::Table;
29use crate::text::{c_string, static_str};
30
31/// The service's name.
32pub const SERVICE: &std::ffi::CStr = c"anvil-overlay.panel";
33/// The service's major version.
34pub const VERSION: u32 = ANVIL_PANEL_SERVICE_VERSION;
35
36/// One row of a panel. Kinds are added with newer overlays, so a `match`
37/// needs a `_` arm.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum Row<'a> {
41    /// `label`, and `value` beside it when there is one.
42    Text {
43        /// The text.
44        label: &'a str,
45        /// The value beside it.
46        value: Option<&'a str>,
47    },
48    /// A button with `label`; a click gives back `id`.
49    Button {
50        /// The button's text.
51        label: &'a str,
52        /// What the click handler receives.
53        id: u64,
54    },
55    /// A line.
56    Separator,
57    /// A square of `color` (`0x00RRGGBB`) before `label`, and `value` beside
58    /// it when there is one. Since anvil-overlay 1.26.0: an older overlay
59    /// refuses the rows with `InvalidArgument`.
60    Swatch {
61        /// The colour, `0x00RRGGBB`.
62        color: u32,
63        /// The text.
64        label: &'a str,
65        /// The value beside it.
66        value: Option<&'a str>,
67    },
68}
69
70impl<'a> Row<'a> {
71    /// A line of text.
72    pub const fn text(label: &'a str) -> Self {
73        Self::Text { label, value: None }
74    }
75
76    /// A label with a value beside it.
77    pub const fn value(label: &'a str, value: &'a str) -> Self {
78        Self::Text {
79            label,
80            value: Some(value),
81        }
82    }
83
84    /// A button.
85    pub const fn button(label: &'a str, id: u64) -> Self {
86        Self::Button { label, id }
87    }
88
89    /// A colour square before a label (anvil-overlay 1.26.0).
90    pub const fn swatch(color: u32, label: &'a str) -> Self {
91        Self::Swatch {
92            color,
93            label,
94            value: None,
95        }
96    }
97}
98
99/// The `anvil-overlay.panel` service.
100#[derive(Clone, Copy)]
101pub struct Panels {
102    table: Table<AnvilPanelService>,
103}
104
105impl fmt::Debug for Panels {
106    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107        f.debug_struct("Panels")
108            .field("size", &self.table.size())
109            .finish()
110    }
111}
112
113impl Panels {
114    /// The service; `None` without the overlay (or with one older than 1.11).
115    pub fn get(host: &Host) -> Option<Self> {
116        // SAFETY: the table type of anvil-overlay.panel version 1.
117        let table = unsafe { host.service::<AnvilPanelService>(SERVICE, VERSION) }?;
118        Some(Self { table })
119    }
120
121    /// The C table, for what this crate does not wrap.
122    pub fn c_api(&self) -> Table<AnvilPanelService> {
123        self.table
124    }
125
126    /// A hidden panel with a title, which also names it in the overlay's
127    /// status tab, where the player can show and hide it. At most 64 panels
128    /// in a process (`OutOfMemory` after that).
129    pub fn create(&self, title: &str) -> Result<Panel> {
130        let f = function!(self.table, AnvilPanelService, create)?;
131        let title_c = c_string(title);
132        let mut raw: *mut AnvilPanel = ptr::null_mut();
133        // SAFETY: a NUL-terminated title and an out pointer.
134        check(unsafe { f(title_c.as_ptr(), &mut raw) }, || {
135            format!("panel create {title:?}")
136        })?;
137        let raw = NonNull::new(raw).ok_or_else(|| {
138            crate::Error::new(
139                crate::ErrorCode::Internal,
140                format!("panel create {title:?}: no panel"),
141            )
142        })?;
143        Ok(Panel {
144            table: self.table,
145            raw,
146        })
147    }
148
149    /// The player's language: "en", "fr", "de", "es", "zh-Hans", "zh-Hant",
150    /// "ja" or "ko".
151    pub fn language(&self) -> &'static str {
152        let language = function!(self.table, AnvilPanelService, language).ok();
153        // SAFETY: the service's function; the text lives for the process.
154        language
155            .and_then(|f| unsafe { static_str(f()) })
156            .unwrap_or("en")
157    }
158}
159
160/// A panel. It is `Copy`: the overlay keeps it until the process ends.
161#[derive(Clone, Copy)]
162pub struct Panel {
163    table: Table<AnvilPanelService>,
164    raw: NonNull<AnvilPanel>,
165}
166
167// SAFETY: every panel call may come from any thread (anvil_panel.h, "Threads").
168unsafe impl Send for Panel {}
169// SAFETY: as above.
170unsafe impl Sync for Panel {}
171
172impl fmt::Debug for Panel {
173    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174        f.debug_tuple("Panel").field(&self.raw).finish()
175    }
176}
177
178struct ClickAdapter<F> {
179    handler: F,
180    panicked: AtomicBool,
181}
182
183unsafe extern "C" fn click_adapter<F: Fn(u64) + Send + Sync + 'static>(
184    context: *mut c_void,
185    id: u64,
186) {
187    // SAFETY: the adapter on_click registered, never freed.
188    let adapter = unsafe { &*context.cast::<ClickAdapter<F>>() };
189    run_callback("panel click handler", &adapter.panicked, (), || {
190        (adapter.handler)(id)
191    });
192}
193
194impl Panel {
195    /// The raw panel, for the C table.
196    pub fn as_raw(&self) -> *mut AnvilPanel {
197        self.raw.as_ptr()
198    }
199
200    /// Replaces the rows: at most 1024, each text at most 4096 bytes, else
201    /// `InvalidArgument`. A NUL inside a text is dropped.
202    pub fn set_rows(&self, rows: &[Row<'_>]) -> Result<()> {
203        let f = function!(self.table, AnvilPanelService, set_rows)?;
204        // The texts live until the call returns; the overlay copies them.
205        let mut texts: Vec<CString> = Vec::with_capacity(rows.len() * 2);
206        let mut keep = |text: &str| {
207            let c = c_string(text);
208            let pointer = c.as_ptr();
209            texts.push(c);
210            pointer
211        };
212        let raw: Vec<AnvilPanelRow> = rows
213            .iter()
214            .map(|row| match *row {
215                Row::Text { label, value } => AnvilPanelRow {
216                    kind: ANVIL_PANEL_TEXT as u32,
217                    reserved: 0,
218                    label: keep(label),
219                    value: value.map_or(ptr::null(), &mut keep),
220                    id: 0,
221                    color: 0,
222                    reserved2: 0,
223                },
224                Row::Button { label, id } => AnvilPanelRow {
225                    kind: ANVIL_PANEL_BUTTON as u32,
226                    reserved: 0,
227                    label: keep(label),
228                    value: ptr::null(),
229                    id,
230                    color: 0,
231                    reserved2: 0,
232                },
233                Row::Separator => AnvilPanelRow {
234                    kind: ANVIL_PANEL_SEPARATOR as u32,
235                    reserved: 0,
236                    label: ptr::null(),
237                    value: ptr::null(),
238                    id: 0,
239                    color: 0,
240                    reserved2: 0,
241                },
242                Row::Swatch {
243                    color,
244                    label,
245                    value,
246                } => AnvilPanelRow {
247                    kind: ANVIL_PANEL_SWATCH as u32,
248                    reserved: 0,
249                    label: keep(label),
250                    value: value.map_or(ptr::null(), &mut keep),
251                    id: 0,
252                    color,
253                    reserved2: 0,
254                },
255            })
256            .collect();
257        let count = u32::try_from(raw.len()).unwrap_or(u32::MAX);
258        // SAFETY: `count` rows of row_size bytes whose texts live until the call returns.
259        let result = unsafe {
260            f(
261                self.raw.as_ptr(),
262                raw.as_ptr(),
263                count,
264                std::mem::size_of::<AnvilPanelRow>() as u32,
265            )
266        };
267        drop(texts);
268        check(result, || "panel set_rows")
269    }
270
271    /// The handler of the panel's buttons (it gets the button's id),
272    /// replacing the last one. Clicks run on the game's main thread; without
273    /// anvil-game no click is delivered.
274    pub fn on_click(&self, handler: impl Fn(u64) + Send + Sync + 'static) -> Result<()> {
275        self.click(handler)
276    }
277
278    fn click<F: Fn(u64) + Send + Sync + 'static>(&self, handler: F) -> Result<()> {
279        let f = function!(self.table, AnvilPanelService, on_click)?;
280        // Never freed: a click may still run the replaced handler.
281        let adapter: &'static ClickAdapter<F> = Box::leak(Box::new(ClickAdapter {
282            handler,
283            panicked: AtomicBool::new(false),
284        }));
285        // SAFETY: the adapter lives for the process and never unwinds.
286        let result = unsafe {
287            f(
288                self.raw.as_ptr(),
289                Some(click_adapter::<F>),
290                ptr::from_ref(adapter).cast_mut().cast(),
291            )
292        };
293        check(result, || "panel on_click")
294    }
295
296    /// Shows or hides the panel. The player may close it at any time: ask
297    /// [`is_shown`](Panel::is_shown).
298    pub fn show(&self, shown: bool) -> Result<()> {
299        let f = function!(self.table, AnvilPanelService, show)?;
300        // SAFETY: the service's function with its panel.
301        check(unsafe { f(self.raw.as_ptr(), i32::from(shown)) }, || {
302            "panel show"
303        })
304    }
305
306    /// Whether the panel is shown.
307    pub fn is_shown(&self) -> bool {
308        // SAFETY: the service's function with its panel.
309        function!(self.table, AnvilPanelService, shown)
310            .is_ok_and(|f| unsafe { f(self.raw.as_ptr()) } != 0)
311    }
312}