wmenu-rs/src/lib.rs

247 lines
5.6 KiB
Rust

use gag::BufferRedirect;
use std::{
error::Error,
ffi::{c_char, CStr, CString},
io::Read,
str::Utf8Error,
};
use wmenu_sys::bindings;
unsafe extern "C" fn print_item(menu: *mut bindings::menu, text: *mut i8, exit: bool) {
wmenu_sys::bindings::puts(text);
wmenu_sys::bindings::fflush(bindings::stdout);
if exit {
(*menu).exit = true;
}
}
type ItemHandler = unsafe extern "C" fn(menu: *mut bindings::menu, text: *mut i8, exit: bool);
fn to_c_char(text: &str) -> *mut c_char {
return CString::new(text).unwrap().into_raw();
}
fn from_c_string(text: *mut c_char) -> Result<&'static str, Utf8Error> {
unsafe { CStr::from_ptr(text).to_str() }
}
enum Output {
Stdout(String),
Stderr(String),
}
struct OutputCapture {
stdout: BufferRedirect,
stderr: BufferRedirect,
}
impl OutputCapture {
pub fn capture() -> std::io::Result<Self> {
Ok(Self {
stdout: BufferRedirect::stdout()?,
stderr: BufferRedirect::stderr()?,
})
}
pub fn get_output(mut self) -> std::io::Result<Output> {
let mut buf = String::new();
if self.stderr.read_to_string(&mut buf)? > 0 {
Ok(Output::Stderr(buf))
} else {
self.stdout.read_to_string(&mut buf)?;
Ok(Output::Stdout(buf))
}
}
}
#[derive(Debug)]
pub struct MenuError {
message: String,
status: i32,
}
impl MenuError {
pub fn new(status: i32, message: String) -> Self {
Self { message, status }
}
}
impl std::fmt::Display for MenuError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "exit code {}: {}", self.status, self.message)
}
}
impl Error for MenuError {}
trait Handle {
fn handle_item(&self, menu: Menu, text: &str) -> bool;
}
pub struct Menu {
menu: *mut bindings::menu,
}
impl Menu {
pub fn new() -> Menu {
Self {
menu: unsafe { bindings::menu_create(None) },
}
}
pub fn from_menu(menu: *mut bindings::menu) -> Self {
Self { menu }
}
fn inner(&mut self) -> &mut bindings::menu {
unsafe { &mut *self.menu }
}
pub fn handler(&mut self, handler: ItemHandler) -> &mut Self {
self.inner().callback = Some(handler);
self
}
pub fn bottom(&mut self, value: bool) -> &mut Self {
self.inner().bottom = value;
self
}
pub fn password(&mut self, value: bool) -> &mut Self {
self.inner().passwd = value;
self
}
pub fn font(&mut self, value: &str) -> &mut Self {
self.inner().font = to_c_char(value);
self
}
pub fn lines(&mut self, value: i32) -> &mut Self {
self.inner().lines = value;
self
}
pub fn output_name(&mut self, value: &str) -> &mut Self {
self.inner().output_name = to_c_char(value);
self
}
pub fn prompt(&mut self, value: &str) -> &mut Self {
self.inner().prompt = to_c_char(value);
self
}
pub fn normal_bg(&mut self, value: u32) -> &mut Self {
self.inner().normalbg = value;
self
}
pub fn normal_fg(&mut self, value: u32) -> &mut Self {
self.inner().normalfg = value;
self
}
pub fn prompt_fg(&mut self, value: u32) -> &mut Self {
self.inner().promptfg = value;
self
}
pub fn prompt_bg(&mut self, value: u32) -> &mut Self {
self.inner().promptbg = value;
self
}
pub fn selection_bg(&mut self, value: u32) -> &mut Self {
self.inner().selectionbg = value;
self
}
pub fn selection_fg(&mut self, value: u32) -> &mut Self {
self.inner().selectionbg = value;
self
}
pub fn width(&mut self, value: i32) -> &mut Self {
self.inner().width = value;
self
}
pub fn height(&mut self, value: i32) -> &mut Self {
self.inner().height = value;
self
}
pub fn line_height(&mut self, value: i32) -> &mut Self {
self.inner().line_height = value;
self
}
pub fn padding(&mut self, value: i32) -> &mut Self {
self.inner().padding = value;
self
}
pub fn add_item(&mut self, item: &str) -> &mut Self {
unsafe {
bindings::menu_add_item(self.menu, to_c_char(item));
}
self
}
pub fn add_items(&mut self, items: &[&str]) -> &mut Self {
for item in items {
self.add_item(item);
}
self
}
pub fn run(&self) -> Result<String, MenuError> {
let output = OutputCapture::capture().unwrap();
unsafe {
match (bindings::menu_run(self.menu), output.get_output()) {
(0, Ok(Output::Stdout(value))) => Ok(value.trim_end().to_string()),
(n, Ok(Output::Stdout(value) | Output::Stderr(value))) => {
Err(MenuError::new(n, value))
}
(n, Err(e)) => Err(MenuError::new(n, e.to_string())),
}
}
}
}
impl Drop for Menu {
fn drop(&mut self) {
unsafe {
bindings::menu_destroy(self.menu);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn awawa() {
let items = ["roewrn", "sybil", "vex"];
let mut menu = Menu::new(print_item);
let menu = menu
.font("monospace 12")
.height(32)
.line_height(32)
.padding(8)
.add_items(&items);
let result = menu.run().expect("couldn't get result");
println!("{:?}", result.as_bytes());
assert!(items.contains(&result.as_str()));
}
}