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_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.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Row<'a> {
39    /// `label`, and `value` beside it when there is one.
40    Text {
41        /// The text.
42        label: &'a str,
43        /// The value beside it.
44        value: Option<&'a str>,
45    },
46    /// A button with `label`; a click gives back `id`.
47    Button {
48        /// The button's text.
49        label: &'a str,
50        /// What the click handler receives.
51        id: u64,
52    },
53    /// A line.
54    Separator,
55}
56
57impl<'a> Row<'a> {
58    /// A line of text.
59    pub const fn text(label: &'a str) -> Self {
60        Self::Text { label, value: None }
61    }
62
63    /// A label with a value beside it.
64    pub const fn value(label: &'a str, value: &'a str) -> Self {
65        Self::Text {
66            label,
67            value: Some(value),
68        }
69    }
70
71    /// A button.
72    pub const fn button(label: &'a str, id: u64) -> Self {
73        Self::Button { label, id }
74    }
75}
76
77/// The `anvil-overlay.panel` service.
78#[derive(Clone, Copy)]
79pub struct Panels {
80    table: Table<AnvilPanelService>,
81}
82
83impl fmt::Debug for Panels {
84    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
85        f.debug_struct("Panels")
86            .field("size", &self.table.size())
87            .finish()
88    }
89}
90
91impl Panels {
92    /// The service; `None` without the overlay (or with one older than 1.11).
93    pub fn get(host: &Host) -> Option<Self> {
94        // SAFETY: the table type of anvil-overlay.panel version 1.
95        let table = unsafe { host.service::<AnvilPanelService>(SERVICE, VERSION) }?;
96        Some(Self { table })
97    }
98
99    /// The C table, for what this crate does not wrap.
100    pub fn c_api(&self) -> Table<AnvilPanelService> {
101        self.table
102    }
103
104    /// A hidden panel with a title, which also names it in the overlay's
105    /// status tab, where the player can show and hide it. At most 64 panels
106    /// in a process (`OutOfMemory` after that).
107    pub fn create(&self, title: &str) -> Result<Panel> {
108        let f = function!(self.table, AnvilPanelService, create)?;
109        let title_c = c_string(title);
110        let mut raw: *mut AnvilPanel = ptr::null_mut();
111        // SAFETY: a NUL-terminated title and an out pointer.
112        check(unsafe { f(title_c.as_ptr(), &mut raw) }, || {
113            format!("panel create {title:?}")
114        })?;
115        let raw = NonNull::new(raw).ok_or_else(|| {
116            crate::Error::new(
117                crate::ErrorCode::Internal,
118                format!("panel create {title:?}: no panel"),
119            )
120        })?;
121        Ok(Panel {
122            table: self.table,
123            raw,
124        })
125    }
126
127    /// The player's language: "en", "fr", "de", "es", "zh-Hans", "zh-Hant",
128    /// "ja" or "ko".
129    pub fn language(&self) -> &'static str {
130        let language = function!(self.table, AnvilPanelService, language).ok();
131        // SAFETY: the service's function; the text lives for the process.
132        language
133            .and_then(|f| unsafe { static_str(f()) })
134            .unwrap_or("en")
135    }
136}
137
138/// A panel. It is `Copy`: the overlay keeps it until the process ends.
139#[derive(Clone, Copy)]
140pub struct Panel {
141    table: Table<AnvilPanelService>,
142    raw: NonNull<AnvilPanel>,
143}
144
145// SAFETY: every panel call may come from any thread (anvil_panel.h, "Threads").
146unsafe impl Send for Panel {}
147// SAFETY: as above.
148unsafe impl Sync for Panel {}
149
150impl fmt::Debug for Panel {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        f.debug_tuple("Panel").field(&self.raw).finish()
153    }
154}
155
156struct ClickAdapter<F> {
157    handler: F,
158    panicked: AtomicBool,
159}
160
161unsafe extern "C" fn click_adapter<F: Fn(u64) + Send + Sync + 'static>(
162    context: *mut c_void,
163    id: u64,
164) {
165    // SAFETY: the adapter on_click registered, never freed.
166    let adapter = unsafe { &*context.cast::<ClickAdapter<F>>() };
167    run_callback("panel click handler", &adapter.panicked, (), || {
168        (adapter.handler)(id)
169    });
170}
171
172impl Panel {
173    /// The raw panel, for the C table.
174    pub fn as_raw(&self) -> *mut AnvilPanel {
175        self.raw.as_ptr()
176    }
177
178    /// Replaces the rows: at most 1024, each text at most 4096 bytes, else
179    /// `InvalidArgument`. A NUL inside a text is dropped.
180    pub fn set_rows(&self, rows: &[Row<'_>]) -> Result<()> {
181        let f = function!(self.table, AnvilPanelService, set_rows)?;
182        // The texts live until the call returns; the overlay copies them.
183        let mut texts: Vec<CString> = Vec::with_capacity(rows.len() * 2);
184        let mut keep = |text: &str| {
185            let c = c_string(text);
186            let pointer = c.as_ptr();
187            texts.push(c);
188            pointer
189        };
190        let raw: Vec<AnvilPanelRow> = rows
191            .iter()
192            .map(|row| match *row {
193                Row::Text { label, value } => AnvilPanelRow {
194                    kind: ANVIL_PANEL_TEXT as u32,
195                    reserved: 0,
196                    label: keep(label),
197                    value: value.map_or(ptr::null(), &mut keep),
198                    id: 0,
199                },
200                Row::Button { label, id } => AnvilPanelRow {
201                    kind: ANVIL_PANEL_BUTTON as u32,
202                    reserved: 0,
203                    label: keep(label),
204                    value: ptr::null(),
205                    id,
206                },
207                Row::Separator => AnvilPanelRow {
208                    kind: ANVIL_PANEL_SEPARATOR as u32,
209                    reserved: 0,
210                    label: ptr::null(),
211                    value: ptr::null(),
212                    id: 0,
213                },
214            })
215            .collect();
216        let count = u32::try_from(raw.len()).unwrap_or(u32::MAX);
217        // SAFETY: `count` rows of row_size bytes whose texts live until the call returns.
218        let result = unsafe {
219            f(
220                self.raw.as_ptr(),
221                raw.as_ptr(),
222                count,
223                std::mem::size_of::<AnvilPanelRow>() as u32,
224            )
225        };
226        drop(texts);
227        check(result, || "panel set_rows")
228    }
229
230    /// The handler of the panel's buttons (it gets the button's id),
231    /// replacing the last one. Clicks run on the game's main thread; without
232    /// anvil-game no click is delivered.
233    pub fn on_click(&self, handler: impl Fn(u64) + Send + Sync + 'static) -> Result<()> {
234        self.click(handler)
235    }
236
237    fn click<F: Fn(u64) + Send + Sync + 'static>(&self, handler: F) -> Result<()> {
238        let f = function!(self.table, AnvilPanelService, on_click)?;
239        // Never freed: a click may still run the replaced handler.
240        let adapter: &'static ClickAdapter<F> = Box::leak(Box::new(ClickAdapter {
241            handler,
242            panicked: AtomicBool::new(false),
243        }));
244        // SAFETY: the adapter lives for the process and never unwinds.
245        let result = unsafe {
246            f(
247                self.raw.as_ptr(),
248                Some(click_adapter::<F>),
249                ptr::from_ref(adapter).cast_mut().cast(),
250            )
251        };
252        check(result, || "panel on_click")
253    }
254
255    /// Shows or hides the panel. The player may close it at any time: ask
256    /// [`is_shown`](Panel::is_shown).
257    pub fn show(&self, shown: bool) -> Result<()> {
258        let f = function!(self.table, AnvilPanelService, show)?;
259        // SAFETY: the service's function with its panel.
260        check(unsafe { f(self.raw.as_ptr(), i32::from(shown)) }, || {
261            "panel show"
262        })
263    }
264
265    /// Whether the panel is shown.
266    pub fn is_shown(&self) -> bool {
267        // SAFETY: the service's function with its panel.
268        function!(self.table, AnvilPanelService, shown)
269            .is_ok_and(|f| unsafe { f(self.raw.as_ptr()) } != 0)
270    }
271}