mod app;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread::{self, JoinHandle};
use egui::Ui;
use plotine_core::{PlotError, Result};
use crate::figure::Figure;
pub type WidgetCallback = Box<dyn FnMut(&mut Ui, &mut Figure) -> bool + Send>;
pub struct ShowHandle {
join: Option<JoinHandle<Result<()>>>,
close: Arc<AtomicBool>,
}
impl ShowHandle {
pub fn close(&self) {
self.close.store(true, Ordering::SeqCst);
}
pub fn is_finished(&self) -> bool {
self.join.as_ref().map(|j| j.is_finished()).unwrap_or(true)
}
pub fn join(mut self) -> Result<()> {
if let Some(handle) = self.join.take() {
match handle.join() {
Ok(r) => r,
Err(_) => Err(gui_error("GUI thread panicked")),
}
} else {
Ok(())
}
}
}
impl Drop for ShowHandle {
fn drop(&mut self) {
self.close.store(true, Ordering::SeqCst);
if let Some(handle) = self.join.take() {
let _ = handle.join();
}
}
}
impl Figure {
pub fn show(self) -> Result<()> {
app::run(self, None, None)
}
pub fn show_with<F>(self, widgets: F) -> Result<()>
where
F: FnMut(&mut Ui, &mut Figure) -> bool + Send + 'static,
{
app::run(self, Some(Box::new(widgets)), None)
}
pub fn show_nonblocking(self) -> Result<ShowHandle> {
let close = Arc::new(AtomicBool::new(false));
let close_flag = Arc::clone(&close);
let join = thread::Builder::new()
.name("plotine-gui".into())
.spawn(move || app::run(self, None, Some(close_flag)))
.map_err(|e| gui_error(format!("failed to spawn GUI thread: {e}")))?;
Ok(ShowHandle {
join: Some(join),
close,
})
}
}
pub(crate) fn gui_error(message: impl Into<String>) -> PlotError {
PlotError::Render {
message: message.into(),
suggestion: "ensure a display is available; GUI requires the `gui` feature and a windowing environment",
}
}