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_SWATCH, 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)]
39#[non_exhaustive]
40pub enum Row<'a> {
41 Text {
43 label: &'a str,
45 value: Option<&'a str>,
47 },
48 Button {
50 label: &'a str,
52 id: u64,
54 },
55 Separator,
57 Swatch {
61 color: u32,
63 label: &'a str,
65 value: Option<&'a str>,
67 },
68}
69
70impl<'a> Row<'a> {
71 pub const fn text(label: &'a str) -> Self {
73 Self::Text { label, value: None }
74 }
75
76 pub const fn value(label: &'a str, value: &'a str) -> Self {
78 Self::Text {
79 label,
80 value: Some(value),
81 }
82 }
83
84 pub const fn button(label: &'a str, id: u64) -> Self {
86 Self::Button { label, id }
87 }
88
89 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#[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 pub fn get(host: &Host) -> Option<Self> {
116 let table = unsafe { host.service::<AnvilPanelService>(SERVICE, VERSION) }?;
118 Some(Self { table })
119 }
120
121 pub fn c_api(&self) -> Table<AnvilPanelService> {
123 self.table
124 }
125
126 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 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 pub fn language(&self) -> &'static str {
152 let language = function!(self.table, AnvilPanelService, language).ok();
153 language
155 .and_then(|f| unsafe { static_str(f()) })
156 .unwrap_or("en")
157 }
158}
159
160#[derive(Clone, Copy)]
162pub struct Panel {
163 table: Table<AnvilPanelService>,
164 raw: NonNull<AnvilPanel>,
165}
166
167unsafe impl Send for Panel {}
169unsafe 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 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 pub fn as_raw(&self) -> *mut AnvilPanel {
197 self.raw.as_ptr()
198 }
199
200 pub fn set_rows(&self, rows: &[Row<'_>]) -> Result<()> {
203 let f = function!(self.table, AnvilPanelService, set_rows)?;
204 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 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 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 let adapter: &'static ClickAdapter<F> = Box::leak(Box::new(ClickAdapter {
282 handler,
283 panicked: AtomicBool::new(false),
284 }));
285 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 pub fn show(&self, shown: bool) -> Result<()> {
299 let f = function!(self.table, AnvilPanelService, show)?;
300 check(unsafe { f(self.raw.as_ptr(), i32::from(shown)) }, || {
302 "panel show"
303 })
304 }
305
306 pub fn is_shown(&self) -> bool {
308 function!(self.table, AnvilPanelService, shown)
310 .is_ok_and(|f| unsafe { f(self.raw.as_ptr()) } != 0)
311 }
312}