2023-09-28 05:23:59 +00:00
|
|
|
mod async_context;
|
2023-09-28 07:16:42 +00:00
|
|
|
mod entity_map;
|
2023-09-28 05:19:32 +00:00
|
|
|
mod model_context;
|
|
|
|
|
2023-09-28 05:23:59 +00:00
|
|
|
pub use async_context::*;
|
2023-09-28 07:16:42 +00:00
|
|
|
pub use entity_map::*;
|
2023-09-28 05:19:32 +00:00
|
|
|
pub use model_context::*;
|
2023-09-29 19:22:53 +00:00
|
|
|
use refineable::Refineable;
|
2023-09-28 05:19:32 +00:00
|
|
|
|
2023-09-20 16:17:29 +00:00
|
|
|
use crate::{
|
2023-09-29 20:34:40 +00:00
|
|
|
current_platform, run_on_main, spawn_on_main, Context, LayoutId, MainThread, MainThreadOnly,
|
|
|
|
Platform, PlatformDispatcher, RootView, TextStyle, TextStyleRefinement, TextSystem, Window,
|
2023-09-29 20:04:58 +00:00
|
|
|
WindowContext, WindowHandle, WindowId,
|
2023-09-20 16:17:29 +00:00
|
|
|
};
|
2023-09-19 19:19:22 +00:00
|
|
|
use anyhow::{anyhow, Result};
|
2023-09-25 17:47:37 +00:00
|
|
|
use collections::{HashMap, VecDeque};
|
2023-09-23 18:21:52 +00:00
|
|
|
use futures::{future, Future};
|
2023-09-22 18:44:37 +00:00
|
|
|
use parking_lot::Mutex;
|
2023-09-19 19:19:22 +00:00
|
|
|
use slotmap::SlotMap;
|
2023-09-25 17:47:37 +00:00
|
|
|
use smallvec::SmallVec;
|
2023-09-29 19:22:53 +00:00
|
|
|
use std::{
|
|
|
|
any::{type_name, Any, TypeId},
|
2023-09-29 20:34:40 +00:00
|
|
|
marker::PhantomData,
|
2023-09-29 20:04:58 +00:00
|
|
|
ops::{Deref, DerefMut},
|
2023-09-29 19:22:53 +00:00
|
|
|
sync::{Arc, Weak},
|
|
|
|
};
|
2023-09-27 21:35:46 +00:00
|
|
|
use util::ResultExt;
|
2023-09-19 19:19:22 +00:00
|
|
|
|
2023-09-20 16:17:29 +00:00
|
|
|
#[derive(Clone)]
|
2023-09-22 18:44:37 +00:00
|
|
|
pub struct App(Arc<Mutex<AppContext>>);
|
2023-09-19 19:19:22 +00:00
|
|
|
|
2023-09-20 16:17:29 +00:00
|
|
|
impl App {
|
2023-09-22 16:02:11 +00:00
|
|
|
pub fn production() -> Self {
|
|
|
|
Self::new(current_platform())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(any(test, feature = "test"))]
|
|
|
|
pub fn test() -> Self {
|
|
|
|
Self::new(Arc::new(super::TestPlatform::new()))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn new(platform: Arc<dyn Platform>) -> Self {
|
2023-09-22 18:44:37 +00:00
|
|
|
let dispatcher = platform.dispatcher();
|
2023-09-22 16:02:11 +00:00
|
|
|
let text_system = Arc::new(TextSystem::new(platform.text_system()));
|
2023-09-28 06:46:15 +00:00
|
|
|
let entities = EntityMap::new();
|
|
|
|
let unit_entity = entities.redeem(entities.reserve(), ());
|
2023-09-22 16:02:11 +00:00
|
|
|
Self(Arc::new_cyclic(|this| {
|
2023-09-22 18:44:37 +00:00
|
|
|
Mutex::new(AppContext {
|
2023-09-29 20:34:40 +00:00
|
|
|
thread: PhantomData,
|
2023-09-22 16:02:11 +00:00
|
|
|
this: this.clone(),
|
2023-09-29 20:34:40 +00:00
|
|
|
platform: MainThreadOnly::new(platform, dispatcher.clone()),
|
|
|
|
dispatcher,
|
2023-09-22 16:02:11 +00:00
|
|
|
text_system,
|
2023-09-29 19:22:53 +00:00
|
|
|
pending_updates: 0,
|
|
|
|
text_style_stack: Vec::new(),
|
|
|
|
state_stacks_by_type: HashMap::default(),
|
2023-09-26 17:29:44 +00:00
|
|
|
unit_entity,
|
2023-09-22 16:02:11 +00:00
|
|
|
entities,
|
|
|
|
windows: SlotMap::with_key(),
|
2023-09-25 17:47:37 +00:00
|
|
|
pending_effects: Default::default(),
|
|
|
|
observers: Default::default(),
|
2023-09-22 16:02:11 +00:00
|
|
|
layout_id_buffer: Default::default(),
|
|
|
|
})
|
|
|
|
}))
|
2023-09-20 18:03:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn run<F>(self, on_finish_launching: F)
|
|
|
|
where
|
2023-09-22 18:44:37 +00:00
|
|
|
F: 'static + FnOnce(&mut AppContext),
|
2023-09-20 18:03:37 +00:00
|
|
|
{
|
2023-09-22 18:52:52 +00:00
|
|
|
let this = self.clone();
|
2023-09-22 18:44:37 +00:00
|
|
|
let platform = self.0.lock().platform.clone();
|
|
|
|
platform.borrow_on_main_thread().run(Box::new(move || {
|
2023-09-22 18:52:52 +00:00
|
|
|
let cx = &mut *this.0.lock();
|
2023-09-22 16:02:11 +00:00
|
|
|
on_finish_launching(cx);
|
2023-09-20 18:03:37 +00:00
|
|
|
}));
|
2023-09-20 16:17:29 +00:00
|
|
|
}
|
|
|
|
}
|
2023-09-19 19:19:22 +00:00
|
|
|
|
2023-09-29 20:34:40 +00:00
|
|
|
type Handlers<Thread> =
|
|
|
|
SmallVec<[Arc<dyn Fn(&mut AppContext<Thread>) -> bool + Send + Sync + 'static>; 2]>;
|
2023-09-25 17:47:37 +00:00
|
|
|
|
2023-09-29 20:34:40 +00:00
|
|
|
pub struct AppContext<Thread = ()> {
|
|
|
|
thread: PhantomData<Thread>,
|
2023-09-22 18:44:37 +00:00
|
|
|
this: Weak<Mutex<AppContext>>,
|
|
|
|
platform: MainThreadOnly<dyn Platform>,
|
2023-09-29 20:04:58 +00:00
|
|
|
dispatcher: Arc<dyn PlatformDispatcher>,
|
2023-09-20 18:03:37 +00:00
|
|
|
text_system: Arc<TextSystem>,
|
2023-09-28 05:23:59 +00:00
|
|
|
pending_updates: usize,
|
2023-09-29 19:22:53 +00:00
|
|
|
pub(crate) text_style_stack: Vec<TextStyleRefinement>,
|
|
|
|
pub(crate) state_stacks_by_type: HashMap<TypeId, Vec<Box<dyn Any + Send + Sync>>>,
|
2023-09-26 17:29:44 +00:00
|
|
|
pub(crate) unit_entity: Handle<()>,
|
2023-09-28 06:46:15 +00:00
|
|
|
pub(crate) entities: EntityMap,
|
2023-09-19 19:19:22 +00:00
|
|
|
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
|
2023-09-25 17:47:37 +00:00
|
|
|
pub(crate) pending_effects: VecDeque<Effect>,
|
2023-09-29 20:34:40 +00:00
|
|
|
pub(crate) observers: HashMap<EntityId, Handlers<Thread>>,
|
2023-09-28 05:23:59 +00:00
|
|
|
pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
|
2023-09-19 19:19:22 +00:00
|
|
|
}
|
|
|
|
|
2023-09-29 20:34:40 +00:00
|
|
|
impl Deref for AppContext<MainThread> {
|
|
|
|
type Target = AppContext<()>;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for AppContext<MainThread> {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<Thread> AppContext<Thread> {
|
2023-09-20 18:03:37 +00:00
|
|
|
pub fn text_system(&self) -> &Arc<TextSystem> {
|
|
|
|
&self.text_system
|
2023-09-19 19:19:22 +00:00
|
|
|
}
|
|
|
|
|
2023-09-26 17:29:44 +00:00
|
|
|
pub fn to_async(&self) -> AsyncContext {
|
|
|
|
AsyncContext(self.this.clone())
|
|
|
|
}
|
|
|
|
|
2023-09-29 23:20:18 +00:00
|
|
|
// pub fn run_on_main<R>(
|
|
|
|
// &self,
|
|
|
|
// f: impl FnOnce(&mut AppContext<MainThread>) -> R + Send + 'static,
|
|
|
|
// ) -> impl Future<Output = R>
|
|
|
|
// where
|
|
|
|
// R: Send + 'static,
|
|
|
|
// {
|
|
|
|
// let this = self.this.upgrade().unwrap();
|
|
|
|
// run_on_main(self.dispatcher.clone(), move || {
|
|
|
|
// let cx = &mut *this.lock();
|
|
|
|
// let main_thread_cx: &mut AppContext<MainThread> = unsafe { std::mem::transmute(cx) };
|
|
|
|
// main_thread_cx.update(|cx| f(cx))
|
|
|
|
// })
|
|
|
|
// }
|
|
|
|
|
|
|
|
// pub fn spawn_on_main<F, R>(
|
|
|
|
// &self,
|
|
|
|
// f: impl FnOnce(&mut AppContext<MainThread>) -> F + Send + 'static,
|
|
|
|
// ) -> impl Future<Output = R>
|
|
|
|
// where
|
|
|
|
// F: Future<Output = R> + 'static,
|
|
|
|
// R: Send + 'static,
|
|
|
|
// {
|
|
|
|
// let this = self.this.upgrade().unwrap();
|
|
|
|
// spawn_on_main(self.dispatcher.clone(), move || {
|
|
|
|
// let cx = &mut *this.lock();
|
|
|
|
// let platform = cx.platform.borrow_on_main_thread().clone();
|
|
|
|
// // todo!()
|
|
|
|
// // cx.update(|cx| f(&mut MainThreadContext::mutable(cx, platform.as_ref())))
|
|
|
|
|
|
|
|
// future::ready(())
|
|
|
|
// })
|
|
|
|
// // self.platform.read(move |platform| {
|
|
|
|
// }
|
2023-09-22 18:44:37 +00:00
|
|
|
|
2023-09-29 19:22:53 +00:00
|
|
|
pub fn text_style(&self) -> TextStyle {
|
|
|
|
let mut style = TextStyle::default();
|
|
|
|
for refinement in &self.text_style_stack {
|
|
|
|
style.refine(refinement);
|
|
|
|
}
|
|
|
|
style
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn state<S: 'static>(&self) -> &S {
|
|
|
|
self.state_stacks_by_type
|
|
|
|
.get(&TypeId::of::<S>())
|
|
|
|
.and_then(|stack| stack.last())
|
|
|
|
.and_then(|any_state| any_state.downcast_ref::<S>())
|
|
|
|
.ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
|
|
|
|
.unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn state_mut<S: 'static>(&mut self) -> &mut S {
|
|
|
|
self.state_stacks_by_type
|
|
|
|
.get_mut(&TypeId::of::<S>())
|
|
|
|
.and_then(|stack| stack.last_mut())
|
|
|
|
.and_then(|any_state| any_state.downcast_mut::<S>())
|
|
|
|
.ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
|
|
|
|
.unwrap()
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
|
|
|
|
self.text_style_stack.push(text_style);
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn pop_text_style(&mut self) {
|
|
|
|
self.text_style_stack.pop();
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn push_state<T: Send + Sync + 'static>(&mut self, state: T) {
|
|
|
|
self.state_stacks_by_type
|
|
|
|
.entry(TypeId::of::<T>())
|
|
|
|
.or_default()
|
|
|
|
.push(Box::new(state));
|
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) fn pop_state<T: 'static>(&mut self) {
|
|
|
|
self.state_stacks_by_type
|
|
|
|
.get_mut(&TypeId::of::<T>())
|
|
|
|
.and_then(|stack| stack.pop())
|
|
|
|
.expect("state stack underflow");
|
|
|
|
}
|
|
|
|
|
2023-09-19 19:19:22 +00:00
|
|
|
pub(crate) fn update_window<R>(
|
|
|
|
&mut self,
|
2023-09-25 17:55:05 +00:00
|
|
|
id: WindowId,
|
2023-09-29 20:34:40 +00:00
|
|
|
update: impl FnOnce(&mut WindowContext<Thread>) -> R,
|
2023-09-19 19:19:22 +00:00
|
|
|
) -> Result<R> {
|
2023-09-26 17:34:41 +00:00
|
|
|
self.update(|cx| {
|
|
|
|
let mut window = cx
|
|
|
|
.windows
|
|
|
|
.get_mut(id)
|
|
|
|
.ok_or_else(|| anyhow!("window not found"))?
|
|
|
|
.take()
|
|
|
|
.unwrap();
|
|
|
|
|
|
|
|
let result = update(&mut WindowContext::mutable(cx, &mut window));
|
|
|
|
window.dirty = true;
|
|
|
|
|
|
|
|
cx.windows
|
|
|
|
.get_mut(id)
|
|
|
|
.ok_or_else(|| anyhow!("window not found"))?
|
|
|
|
.replace(window);
|
|
|
|
|
|
|
|
Ok(result)
|
|
|
|
})
|
2023-09-19 19:19:22 +00:00
|
|
|
}
|
2023-09-25 17:47:37 +00:00
|
|
|
|
|
|
|
fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
|
|
|
|
self.pending_updates += 1;
|
|
|
|
let result = update(self);
|
|
|
|
self.pending_updates -= 1;
|
|
|
|
if self.pending_updates == 0 {
|
|
|
|
self.flush_effects();
|
|
|
|
}
|
|
|
|
result
|
|
|
|
}
|
|
|
|
|
|
|
|
fn flush_effects(&mut self) {
|
|
|
|
while let Some(effect) = self.pending_effects.pop_front() {
|
|
|
|
match effect {
|
|
|
|
Effect::Notify(entity_id) => self.apply_notify_effect(entity_id),
|
|
|
|
}
|
|
|
|
}
|
2023-09-25 17:55:05 +00:00
|
|
|
|
|
|
|
let dirty_window_ids = self
|
|
|
|
.windows
|
|
|
|
.iter()
|
|
|
|
.filter_map(|(window_id, window)| {
|
|
|
|
let window = window.as_ref().unwrap();
|
|
|
|
if window.dirty {
|
|
|
|
Some(window_id)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect::<Vec<_>>();
|
|
|
|
|
|
|
|
for dirty_window_id in dirty_window_ids {
|
2023-09-27 21:35:46 +00:00
|
|
|
self.update_window(dirty_window_id, |cx| cx.draw())
|
|
|
|
.unwrap() // We know we have the window.
|
|
|
|
.log_err();
|
2023-09-25 17:55:05 +00:00
|
|
|
}
|
2023-09-25 17:47:37 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn apply_notify_effect(&mut self, updated_entity: EntityId) {
|
|
|
|
if let Some(mut handlers) = self.observers.remove(&updated_entity) {
|
|
|
|
handlers.retain(|handler| handler(self));
|
|
|
|
if let Some(new_handlers) = self.observers.remove(&updated_entity) {
|
|
|
|
handlers.extend(new_handlers);
|
|
|
|
}
|
|
|
|
self.observers.insert(updated_entity, handlers);
|
|
|
|
}
|
|
|
|
}
|
2023-09-19 19:19:22 +00:00
|
|
|
}
|
|
|
|
|
2023-09-29 23:20:18 +00:00
|
|
|
impl<Thread: 'static> Context for AppContext<Thread> {
|
|
|
|
type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T, Thread>;
|
2023-09-26 17:29:44 +00:00
|
|
|
type Result<T> = T;
|
2023-09-19 19:19:22 +00:00
|
|
|
|
2023-09-25 17:47:37 +00:00
|
|
|
fn entity<T: Send + Sync + 'static>(
|
2023-09-19 19:19:22 +00:00
|
|
|
&mut self,
|
|
|
|
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
|
|
|
|
) -> Handle<T> {
|
2023-09-28 06:46:15 +00:00
|
|
|
let slot = self.entities.reserve();
|
|
|
|
let entity = build_entity(&mut ModelContext::mutable(self, slot.id));
|
|
|
|
self.entities.redeem(slot, entity)
|
2023-09-19 19:19:22 +00:00
|
|
|
}
|
|
|
|
|
2023-09-25 17:47:37 +00:00
|
|
|
fn update_entity<T: Send + Sync + 'static, R>(
|
2023-09-19 19:19:22 +00:00
|
|
|
&mut self,
|
|
|
|
handle: &Handle<T>,
|
|
|
|
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
|
|
|
|
) -> R {
|
2023-09-28 06:46:15 +00:00
|
|
|
let mut entity = self.entities.lease(handle);
|
2023-09-19 19:19:22 +00:00
|
|
|
let result = update(&mut *entity, &mut ModelContext::mutable(self, handle.id));
|
2023-09-28 06:46:15 +00:00
|
|
|
self.entities.end_lease(entity);
|
2023-09-19 19:19:22 +00:00
|
|
|
result
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-29 20:34:40 +00:00
|
|
|
impl AppContext<MainThread> {
|
|
|
|
fn platform(&self) -> &dyn Platform {
|
|
|
|
self.platform.borrow_on_main_thread()
|
2023-09-29 20:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn activate(&mut self, ignoring_other_apps: bool) {
|
2023-09-29 20:34:40 +00:00
|
|
|
self.platform().activate(ignoring_other_apps);
|
2023-09-29 20:04:58 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn open_window<S: 'static + Send + Sync>(
|
|
|
|
&mut self,
|
|
|
|
options: crate::WindowOptions,
|
|
|
|
build_root_view: impl FnOnce(&mut WindowContext) -> RootView<S> + Send + 'static,
|
|
|
|
) -> WindowHandle<S> {
|
|
|
|
let id = self.windows.insert(None);
|
|
|
|
let handle = WindowHandle::new(id);
|
2023-09-29 20:34:40 +00:00
|
|
|
let mut window = Window::new(handle.into(), options, self.platform(), self);
|
|
|
|
let root_view = build_root_view(&mut WindowContext::mutable(self, &mut window));
|
2023-09-29 20:04:58 +00:00
|
|
|
window.root_view.replace(root_view.into_any());
|
2023-09-29 20:34:40 +00:00
|
|
|
self.windows.get_mut(id).unwrap().replace(window);
|
2023-09-29 20:04:58 +00:00
|
|
|
handle
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-25 17:47:37 +00:00
|
|
|
pub(crate) enum Effect {
|
|
|
|
Notify(EntityId),
|
|
|
|
}
|
|
|
|
|
2023-09-22 18:44:37 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::AppContext;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_app_context_send_sync() {
|
|
|
|
// This will not compile if `AppContext` does not implement `Send`
|
|
|
|
fn assert_send<T: Send>() {}
|
|
|
|
assert_send::<AppContext>();
|
|
|
|
}
|
|
|
|
}
|