use super::Control;
use callback_helpers::{from_void_ptr, to_heap_ptr};
use std::ffi::CStr;
use std::i32;
use std::mem;
use std::os::raw::c_void;
use str_tools::to_toolkit_string;
use ui::UI;
use libui_ffi::{self, uiCombobox, uiControl, uiEditableCombobox};
define_control! {
rust_type: Combobox,
sys_type: uiCombobox
}
impl Combobox {
pub fn new() -> Self {
unsafe { Combobox::from_raw(libui_ffi::uiNewCombobox()) }
}
pub fn append(&self, name: &str) {
unsafe {
let c_string = to_toolkit_string(name);
libui_ffi::uiComboboxAppend(self.uiCombobox, c_string.as_ptr())
}
}
pub fn insert_at(&self, index: i32, name: &str) {
unsafe {
let c_string = to_toolkit_string(name);
libui_ffi::uiComboboxInsertAt(self.uiCombobox, index, c_string.as_ptr())
}
}
pub fn delete(&self, index: i32) {
unsafe { libui_ffi::uiComboboxDelete(self.uiCombobox, index) }
}
pub fn clear(&self) {
unsafe { libui_ffi::uiComboboxClear(self.uiCombobox) }
}
pub fn count(&self) -> i32 {
unsafe { libui_ffi::uiComboboxNumItems(self.uiCombobox) }
}
pub fn selected(&self) -> i32 {
unsafe { libui_ffi::uiComboboxSelected(self.uiCombobox) }
}
pub fn set_selected(&mut self, value: i32) {
unsafe { libui_ffi::uiComboboxSetSelected(self.uiCombobox, value) }
}
pub fn on_selected<'ctx, F>(&mut self, _ctx: &'ctx UI, callback: F)
where
F: FnMut(i32) + 'static,
{
extern "C" fn c_callback<G>(combobox: *mut uiCombobox, data: *mut c_void)
where
G: FnMut(i32),
{
let val = unsafe { libui_ffi::uiComboboxSelected(combobox) };
unsafe { from_void_ptr::<G>(data)(val) }
}
unsafe {
libui_ffi::uiComboboxOnSelected(
self.uiCombobox,
Some(c_callback::<F>),
to_heap_ptr(callback),
);
}
}
}
define_control! {
rust_type: EditableCombobox,
sys_type: uiEditableCombobox
}
impl EditableCombobox {
pub fn new() -> EditableCombobox {
unsafe { EditableCombobox::from_raw(libui_ffi::uiNewEditableCombobox()) }
}
pub fn append(&self, name: &str) {
unsafe {
let c_string = to_toolkit_string(name);
libui_ffi::uiEditableComboboxAppend(self.uiEditableCombobox, c_string.as_ptr())
}
}
pub fn value(&self) -> String {
let ptr = unsafe { libui_ffi::uiEditableComboboxText(self.uiEditableCombobox) };
let text: String = unsafe { CStr::from_ptr(ptr).to_string_lossy().into() };
unsafe {
libui_ffi::uiFreeText(ptr);
}
text
}
pub fn set_value(&mut self, value: &str) {
let cstring = to_toolkit_string(value);
unsafe { libui_ffi::uiEditableComboboxSetText(self.uiEditableCombobox, cstring.as_ptr()) }
}
pub fn on_changed<'ctx, F>(&mut self, _ctx: &'ctx UI, callback: F)
where
F: FnMut(String) + 'static,
{
extern "C" fn c_callback<G>(combobox: *mut uiEditableCombobox, data: *mut c_void)
where
G: FnMut(String),
{
let ptr = unsafe { libui_ffi::uiEditableComboboxText(combobox) };
let text: String = unsafe { CStr::from_ptr(ptr).to_string_lossy().into() };
unsafe {
libui_ffi::uiFreeText(ptr);
}
unsafe { from_void_ptr::<G>(data)(text) }
}
unsafe {
libui_ffi::uiEditableComboboxOnChanged(
self.uiEditableCombobox,
Some(c_callback::<F>),
to_heap_ptr(callback),
);
}
}
}