1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
use std::{cell::RefCell, rc::Rc};

use super::Platform;

mod proxy;
pub use proxy::*;

#[derive(Clone, Copy)]
pub struct AppRef<'a>(pub &'a AppHandle);
impl<'a> types::AppRef<Platform> for AppRef<'a> {
	fn terminate(&self) {
		// not surport
	}
	fn proxy(&self) -> Option<AppProxy> {
		Some(AppProxy())
	}
}

pub struct AppHandle();
impl types::AppHandle<Platform> for AppHandle {
	fn singleton() -> Option<Self> {
		Some(Self())
	}
	fn with(&self, mut fun: impl FnMut(<Platform as types::Platform>::AppRef<'_>)) {
		fun(AppRef(self));
	}
}
impl AppHandle {
	pub fn run(&self) {
		with_app(None, |app| {
			app.delegate.borrow().as_ref()?.on_launch(AppRef(self));
			Some(())
		});
	}
}

pub type RcDynDelegate = Rc<dyn types::AppDelegate<Platform>>;
pub struct AppVars {
	delegate: RefCell<Option<RcDynDelegate>>,
}

thread_local! {
	static CACHE:RefCell<AppVars> = RefCell::new(AppVars {
		delegate: RefCell::new(None),
	});
}

pub fn with_app<T>(v: Option<RcDynDelegate>, fun: impl Fn(&AppVars) -> T) -> T {
	if let Some(new) = v {
		CACHE.with_borrow_mut(|old| {
			*old.delegate.borrow_mut() = Some(new);
		})
	}
	CACHE.with_borrow(|v| fun(v))
}