1use 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
31pub const SERVICE: &std::ffi::CStr = c"anvil-overlay.panel";
33pub const VERSION: u32 = ANVIL_PANEL_SERVICE_VERSION;
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum Row<'a> {
39 Text {
41 label: &'a str,
43 value: Option<&'a str>,
45 },
46 Button {
48 label: &'a str,
50 id: u64,
52 },
53 Separator,
55}
56
57impl<'a> Row<'a> {
58 pub const fn text(label: &'a str) -> Self {
60 Self::Text { label, value: None }
61 }
62
63 pub const fn value(label: &'a str, value: &'a str) -> Self {
65 Self::Text {
66 label,
67 value: Some(value),
68 }
69 }
70
71 pub const fn button(label: &'a str, id: u64) -> Self {
73 Self::Button { label, id }
74 }
75}
76
77#[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 pub fn get(host: &Host) -> Option<Self> {
94 let table = unsafe { host.service::<AnvilPanelService>(SERVICE, VERSION) }?;
96 Some(Self { table })
97 }
98
99 pub fn c_api(&self) -> Table<AnvilPanelService> {
101 self.table
102 }
103
104 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 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 pub fn language(&self) -> &'static str {
130 let language = function!(self.table, AnvilPanelService, language).ok();
131 language
133 .and_then(|f| unsafe { static_str(f()) })
134 .unwrap_or("en")
135 }
136}
137
138#[derive(Clone, Copy)]
140pub struct Panel {
141 table: Table<AnvilPanelService>,
142 raw: NonNull<AnvilPanel>,
143}
144
145unsafe impl Send for Panel {}
147unsafe 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 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 pub fn as_raw(&self) -> *mut AnvilPanel {
175 self.raw.as_ptr()
176 }
177
178 pub fn set_rows(&self, rows: &[Row<'_>]) -> Result<()> {
181 let f = function!(self.table, AnvilPanelService, set_rows)?;
182 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 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 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 let adapter: &'static ClickAdapter<F> = Box::leak(Box::new(ClickAdapter {
241 handler,
242 panicked: AtomicBool::new(false),
243 }));
244 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 pub fn show(&self, shown: bool) -> Result<()> {
258 let f = function!(self.table, AnvilPanelService, show)?;
259 check(unsafe { f(self.raw.as_ptr(), i32::from(shown)) }, || {
261 "panel show"
262 })
263 }
264
265 pub fn is_shown(&self) -> bool {
267 function!(self.table, AnvilPanelService, shown)
269 .is_ok_and(|f| unsafe { f(self.raw.as_ptr()) } != 0)
270 }
271}