use std::ffi::{c_void, CString};
use std::fmt;
use std::ptr::{self, NonNull};
use std::sync::atomic::AtomicBool;
use crate::error::{check, Result};
use crate::host::Host;
use crate::panic::run_callback;
use crate::sys::{
AnvilPanel, AnvilPanelRow, AnvilPanelService, ANVIL_PANEL_BUTTON, ANVIL_PANEL_SEPARATOR,
ANVIL_PANEL_SERVICE_VERSION, ANVIL_PANEL_TEXT,
};
use crate::text::{c_string, static_str};
pub const SERVICE: &std::ffi::CStr = c"anvil-overlay.panel";
pub const VERSION: u32 = ANVIL_PANEL_SERVICE_VERSION;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Row<'a> {
Text {
label: &'a str,
value: Option<&'a str>,
},
Button {
label: &'a str,
id: u64,
},
Separator,
}
impl<'a> Row<'a> {
pub const fn text(label: &'a str) -> Self {
Self::Text { label, value: None }
}
pub const fn value(label: &'a str, value: &'a str) -> Self {
Self::Text {
label,
value: Some(value),
}
}
pub const fn button(label: &'a str, id: u64) -> Self {
Self::Button { label, id }
}
}
#[derive(Clone, Copy)]
pub struct Panels {
table: &'static AnvilPanelService,
}
impl fmt::Debug for Panels {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Panels")
.field("size", &self.table.size)
.finish()
}
}
impl Panels {
pub fn get(host: &Host) -> Option<Self> {
let table = unsafe { host.service::<AnvilPanelService>(SERVICE, VERSION) }?;
Some(Self { table })
}
pub fn c_api(&self) -> &'static AnvilPanelService {
self.table
}
pub fn create(&self, title: &str) -> Result<Panel> {
let f = function!(self.table, AnvilPanelService, create)?;
let title_c = c_string(title);
let mut raw: *mut AnvilPanel = ptr::null_mut();
check(unsafe { f(title_c.as_ptr(), &mut raw) }, || {
format!("panel create {title:?}")
})?;
let raw = NonNull::new(raw).ok_or_else(|| {
crate::Error::new(
crate::ErrorCode::Internal,
format!("panel create {title:?}: no panel"),
)
})?;
Ok(Panel {
table: self.table,
raw,
})
}
pub fn language(&self) -> &'static str {
let language = function!(self.table, AnvilPanelService, language).ok();
language
.and_then(|f| unsafe { static_str(f()) })
.unwrap_or("en")
}
}
#[derive(Clone, Copy)]
pub struct Panel {
table: &'static AnvilPanelService,
raw: NonNull<AnvilPanel>,
}
unsafe impl Send for Panel {}
unsafe impl Sync for Panel {}
impl fmt::Debug for Panel {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("Panel").field(&self.raw).finish()
}
}
struct ClickAdapter<F> {
handler: F,
panicked: AtomicBool,
}
unsafe extern "C" fn click_adapter<F: Fn(u64) + Send + Sync + 'static>(
context: *mut c_void,
id: u64,
) {
let adapter = unsafe { &*context.cast::<ClickAdapter<F>>() };
run_callback("panel click handler", &adapter.panicked, (), || {
(adapter.handler)(id)
});
}
impl Panel {
pub fn as_raw(&self) -> *mut AnvilPanel {
self.raw.as_ptr()
}
pub fn set_rows(&self, rows: &[Row<'_>]) -> Result<()> {
let f = function!(self.table, AnvilPanelService, set_rows)?;
let mut texts: Vec<CString> = Vec::with_capacity(rows.len() * 2);
let mut keep = |text: &str| {
let c = c_string(text);
let pointer = c.as_ptr();
texts.push(c);
pointer
};
let raw: Vec<AnvilPanelRow> = rows
.iter()
.map(|row| match *row {
Row::Text { label, value } => AnvilPanelRow {
kind: ANVIL_PANEL_TEXT as u32,
reserved: 0,
label: keep(label),
value: value.map_or(ptr::null(), &mut keep),
id: 0,
},
Row::Button { label, id } => AnvilPanelRow {
kind: ANVIL_PANEL_BUTTON as u32,
reserved: 0,
label: keep(label),
value: ptr::null(),
id,
},
Row::Separator => AnvilPanelRow {
kind: ANVIL_PANEL_SEPARATOR as u32,
reserved: 0,
label: ptr::null(),
value: ptr::null(),
id: 0,
},
})
.collect();
let count = u32::try_from(raw.len()).unwrap_or(u32::MAX);
let result = unsafe {
f(
self.raw.as_ptr(),
raw.as_ptr(),
count,
std::mem::size_of::<AnvilPanelRow>() as u32,
)
};
drop(texts);
check(result, || "panel set_rows")
}
pub fn on_click(&self, handler: impl Fn(u64) + Send + Sync + 'static) -> Result<()> {
self.click(handler)
}
fn click<F: Fn(u64) + Send + Sync + 'static>(&self, handler: F) -> Result<()> {
let f = function!(self.table, AnvilPanelService, on_click)?;
let adapter: &'static ClickAdapter<F> = Box::leak(Box::new(ClickAdapter {
handler,
panicked: AtomicBool::new(false),
}));
let result = unsafe {
f(
self.raw.as_ptr(),
Some(click_adapter::<F>),
ptr::from_ref(adapter).cast_mut().cast(),
)
};
check(result, || "panel on_click")
}
pub fn show(&self, shown: bool) -> Result<()> {
let f = function!(self.table, AnvilPanelService, show)?;
check(unsafe { f(self.raw.as_ptr(), i32::from(shown)) }, || {
"panel show"
})
}
pub fn is_shown(&self) -> bool {
function!(self.table, AnvilPanelService, shown)
.is_ok_and(|f| unsafe { f(self.raw.as_ptr()) } != 0)
}
}