use crate::core::ObjectId;
use crate::WidgetTriggerEvent;
use super::handle::{dispatch_trigger, WindowHandle};
#[derive(Debug, Clone)]
pub struct AppConfig {
pub app_name: String,
pub organization: String,
pub enable_i18n: bool,
}
impl Default for AppConfig {
fn default() -> Self {
Self { app_name: String::new(), organization: String::new(), enable_i18n: true }
}
}
impl AppConfig {
pub fn with_app_name(mut self, name: &str) -> Self {
self.app_name = name.to_owned();
self
}
pub fn with_organization(mut self, org: &str) -> Self {
self.organization = org.to_owned();
self
}
pub fn with_i18n(mut self, enable: bool) -> Self {
self.enable_i18n = enable;
self
}
}
pub struct App {
config: AppConfig,
}
impl App {
pub fn new() -> Self {
Self { config: AppConfig::default() }
}
pub fn with_config(config: AppConfig) -> Self {
Self { config }
}
pub fn config(&self) -> &AppConfig {
&self.config
}
pub fn on_startup<F: FnOnce() + 'static>(self, f: F) -> Self {
STARTUP.with(|s| {
*s.borrow_mut() = Some(Box::new(f));
});
self
}
pub fn on_shutdown<F: FnOnce() + 'static>(self, f: F) -> Self {
SHUTDOWN.with(|s| {
*s.borrow_mut() = Some(Box::new(f));
});
self
}
pub fn init(&self) {
trace_runtime_route("app::init");
crate::init();
STARTUP.with(|s| {
if let Some(cb) = s.borrow_mut().take() {
cb();
}
});
}
pub fn run(&self) {
trace_runtime_route("app::run");
crate::run();
SHUTDOWN.with(|s| {
if let Some(cb) = s.borrow_mut().take() {
cb();
}
});
}
pub fn quit(&self) {
crate::quit();
}
pub fn new_window(&self, title: &str, x: i32, y: i32, w: u32, h: u32) -> WindowHandle {
WindowHandle::from_raw(crate::create_window(title, x, y, w, h))
}
pub fn poll_event(&self) -> Option<WidgetTriggerEvent> {
let ev = crate::poll_widget_trigger_event();
if let Some(ref ev) = ev {
dispatch_trigger(ev.widget_id, ev.kind);
}
ev
}
pub fn poll_triggered(&self) -> Option<ObjectId> {
crate::poll_widget_triggered()
}
}
impl Default for App {
fn default() -> Self {
Self::new()
}
}
use std::cell::RefCell;
thread_local! {
static STARTUP: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
static SHUTDOWN: RefCell<Option<Box<dyn FnOnce()>>> = const { RefCell::new(None) };
}
fn trace_runtime_route(stage: &str) {
if std::env::var("RUST_WIDGETS_TRACE_RUNTIME").ok().as_deref() == Some("1") {
log::info!("[rust_widgets.app] stage={}", stage);
}
}