use std::sync::{Arc, Mutex};
use alchemy_styles::{StyleSheet, THEME_ENGINE};
use alchemy_lifecycle::traits::AppDelegate;
use crate::window::WindowManager;
#[cfg(feature = "cocoa")]
pub use alchemy_cocoa::app::{App as PlatformAppBridge};
struct DefaultAppDelegate;
impl AppDelegate for DefaultAppDelegate {}
pub struct App {
pub(crate) bridge: Mutex<Option<PlatformAppBridge>>,
pub delegate: Mutex<Box<AppDelegate>>,
pub windows: WindowManager
}
impl App {
pub(crate) fn new() -> Arc<App> {
let app = Arc::new(App {
bridge: Mutex::new(None),
delegate: Mutex::new(Box::new(DefaultAppDelegate {})),
windows: WindowManager::new()
});
let app_ptr: *const App = &*app;
app.configure_bridge(app_ptr);
app
}
pub(crate) fn configure_bridge(&self, ptr: *const App) {
let mut bridge = self.bridge.lock().unwrap();
*bridge = Some(PlatformAppBridge::new(ptr));
}
pub fn register_styles(&self, theme_key: &str, stylesheet: StyleSheet) {
THEME_ENGINE.register_styles(theme_key, stylesheet);
}
pub fn run<S: 'static + AppDelegate>(&self, state: S) {
{
let mut delegate = self.delegate.lock().unwrap();
*delegate = Box::new(state);
}
let lock = self.bridge.lock().unwrap();
if let Some(bridge) = &*lock {
bridge.run();
}
}
}
impl AppDelegate for App {
fn will_finish_launching(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.will_finish_launching();
}
fn did_finish_launching(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.did_finish_launching();
}
fn will_become_active(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.will_become_active();
}
fn did_become_active(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.did_become_active();
}
fn will_resign_active(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.will_resign_active();
}
fn did_resign_active(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.did_resign_active();
}
fn should_terminate(&self) -> bool {
let delegate = self.delegate.lock().unwrap();
delegate.should_terminate()
}
fn will_terminate(&mut self) {
let mut delegate = self.delegate.lock().unwrap();
delegate.will_terminate();
}
fn _window_will_close(&self, window_id: usize) {
self.windows.will_close(window_id);
}
}