1mod async_context;
2mod entity_map;
3mod model_context;
4
5pub use async_context::*;
6pub use entity_map::*;
7pub use model_context::*;
8use refineable::Refineable;
9
10use crate::{
11 current_platform, Context, LayoutId, MainThreadOnly, Platform, RootView, TextStyle,
12 TextStyleRefinement, TextSystem, Window, WindowContext, WindowHandle, WindowId,
13};
14use anyhow::{anyhow, Result};
15use collections::{HashMap, VecDeque};
16use futures::{future, Future};
17use parking_lot::Mutex;
18use slotmap::SlotMap;
19use smallvec::SmallVec;
20use std::{
21 any::{type_name, Any, TypeId},
22 sync::{Arc, Weak},
23};
24use util::ResultExt;
25
26#[derive(Clone)]
27pub struct App(Arc<Mutex<AppContext>>);
28
29impl App {
30 pub fn production() -> Self {
31 Self::new(current_platform())
32 }
33
34 #[cfg(any(test, feature = "test"))]
35 pub fn test() -> Self {
36 Self::new(Arc::new(super::TestPlatform::new()))
37 }
38
39 fn new(platform: Arc<dyn Platform>) -> Self {
40 let dispatcher = platform.dispatcher();
41 let text_system = Arc::new(TextSystem::new(platform.text_system()));
42 let entities = EntityMap::new();
43 let unit_entity = entities.redeem(entities.reserve(), ());
44 Self(Arc::new_cyclic(|this| {
45 Mutex::new(AppContext {
46 this: this.clone(),
47 platform: MainThreadOnly::new(platform, dispatcher),
48 text_system,
49 pending_updates: 0,
50 text_style_stack: Vec::new(),
51 state_stacks_by_type: HashMap::default(),
52 unit_entity,
53 entities,
54 windows: SlotMap::with_key(),
55 pending_effects: Default::default(),
56 observers: Default::default(),
57 layout_id_buffer: Default::default(),
58 })
59 }))
60 }
61
62 pub fn run<F>(self, on_finish_launching: F)
63 where
64 F: 'static + FnOnce(&mut AppContext),
65 {
66 let this = self.clone();
67 let platform = self.0.lock().platform.clone();
68 platform.borrow_on_main_thread().run(Box::new(move || {
69 let cx = &mut *this.0.lock();
70 on_finish_launching(cx);
71 }));
72 }
73}
74
75type Handlers = SmallVec<[Arc<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>; 2]>;
76
77pub struct AppContext {
78 this: Weak<Mutex<AppContext>>,
79 platform: MainThreadOnly<dyn Platform>,
80 text_system: Arc<TextSystem>,
81 pending_updates: usize,
82 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
83 pub(crate) state_stacks_by_type: HashMap<TypeId, Vec<Box<dyn Any + Send + Sync>>>,
84 pub(crate) unit_entity: Handle<()>,
85 pub(crate) entities: EntityMap,
86 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
87 pub(crate) pending_effects: VecDeque<Effect>,
88 pub(crate) observers: HashMap<EntityId, Handlers>,
89 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
90}
91
92impl AppContext {
93 pub fn text_system(&self) -> &Arc<TextSystem> {
94 &self.text_system
95 }
96
97 pub fn to_async(&self) -> AsyncContext {
98 AsyncContext(self.this.clone())
99 }
100
101 pub fn spawn_on_main<F, R>(
102 &self,
103 f: impl FnOnce(&dyn Platform, &mut Self) -> F + Send + 'static,
104 ) -> impl Future<Output = R>
105 where
106 F: Future<Output = R> + 'static,
107 R: Send + 'static,
108 {
109 let this = self.this.upgrade().unwrap();
110 self.platform.read(move |platform| {
111 let cx = &mut *this.lock();
112 cx.update(|cx| f(platform, cx))
113 })
114 }
115
116 pub fn open_window<S: 'static + Send + Sync>(
117 &mut self,
118 options: crate::WindowOptions,
119 build_root_view: impl FnOnce(&mut WindowContext) -> RootView<S> + Send + 'static,
120 ) -> impl Future<Output = WindowHandle<S>> {
121 let id = self.windows.insert(None);
122 let handle = WindowHandle::new(id);
123 self.spawn_on_main(move |platform, cx| {
124 let mut window = Window::new(handle.into(), options, platform, cx);
125 let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
126 window.root_view.replace(root_view.into_any());
127 cx.windows.get_mut(id).unwrap().replace(window);
128 future::ready(handle)
129 })
130 }
131
132 pub fn text_style(&self) -> TextStyle {
133 let mut style = TextStyle::default();
134 for refinement in &self.text_style_stack {
135 style.refine(refinement);
136 }
137 style
138 }
139
140 pub fn state<S: 'static>(&self) -> &S {
141 self.state_stacks_by_type
142 .get(&TypeId::of::<S>())
143 .and_then(|stack| stack.last())
144 .and_then(|any_state| any_state.downcast_ref::<S>())
145 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
146 .unwrap()
147 }
148
149 pub fn state_mut<S: 'static>(&mut self) -> &mut S {
150 self.state_stacks_by_type
151 .get_mut(&TypeId::of::<S>())
152 .and_then(|stack| stack.last_mut())
153 .and_then(|any_state| any_state.downcast_mut::<S>())
154 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
155 .unwrap()
156 }
157
158 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
159 self.text_style_stack.push(text_style);
160 }
161
162 pub(crate) fn pop_text_style(&mut self) {
163 self.text_style_stack.pop();
164 }
165
166 pub(crate) fn push_state<T: Send + Sync + 'static>(&mut self, state: T) {
167 self.state_stacks_by_type
168 .entry(TypeId::of::<T>())
169 .or_default()
170 .push(Box::new(state));
171 }
172
173 pub(crate) fn pop_state<T: 'static>(&mut self) {
174 self.state_stacks_by_type
175 .get_mut(&TypeId::of::<T>())
176 .and_then(|stack| stack.pop())
177 .expect("state stack underflow");
178 }
179
180 pub(crate) fn update_window<R>(
181 &mut self,
182 id: WindowId,
183 update: impl FnOnce(&mut WindowContext) -> R,
184 ) -> Result<R> {
185 self.update(|cx| {
186 let mut window = cx
187 .windows
188 .get_mut(id)
189 .ok_or_else(|| anyhow!("window not found"))?
190 .take()
191 .unwrap();
192
193 let result = update(&mut WindowContext::mutable(cx, &mut window));
194 window.dirty = true;
195
196 cx.windows
197 .get_mut(id)
198 .ok_or_else(|| anyhow!("window not found"))?
199 .replace(window);
200
201 Ok(result)
202 })
203 }
204
205 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
206 self.pending_updates += 1;
207 let result = update(self);
208 self.pending_updates -= 1;
209 if self.pending_updates == 0 {
210 self.flush_effects();
211 }
212 result
213 }
214
215 fn flush_effects(&mut self) {
216 while let Some(effect) = self.pending_effects.pop_front() {
217 match effect {
218 Effect::Notify(entity_id) => self.apply_notify_effect(entity_id),
219 }
220 }
221
222 let dirty_window_ids = self
223 .windows
224 .iter()
225 .filter_map(|(window_id, window)| {
226 let window = window.as_ref().unwrap();
227 if window.dirty {
228 Some(window_id)
229 } else {
230 None
231 }
232 })
233 .collect::<Vec<_>>();
234
235 for dirty_window_id in dirty_window_ids {
236 self.update_window(dirty_window_id, |cx| cx.draw())
237 .unwrap() // We know we have the window.
238 .log_err();
239 }
240 }
241
242 fn apply_notify_effect(&mut self, updated_entity: EntityId) {
243 if let Some(mut handlers) = self.observers.remove(&updated_entity) {
244 handlers.retain(|handler| handler(self));
245 if let Some(new_handlers) = self.observers.remove(&updated_entity) {
246 handlers.extend(new_handlers);
247 }
248 self.observers.insert(updated_entity, handlers);
249 }
250 }
251}
252
253impl Context for AppContext {
254 type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
255 type Result<T> = T;
256
257 fn entity<T: Send + Sync + 'static>(
258 &mut self,
259 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
260 ) -> Handle<T> {
261 let slot = self.entities.reserve();
262 let entity = build_entity(&mut ModelContext::mutable(self, slot.id));
263 self.entities.redeem(slot, entity)
264 }
265
266 fn update_entity<T: Send + Sync + 'static, R>(
267 &mut self,
268 handle: &Handle<T>,
269 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
270 ) -> R {
271 let mut entity = self.entities.lease(handle);
272 let result = update(&mut *entity, &mut ModelContext::mutable(self, handle.id));
273 self.entities.end_lease(entity);
274 result
275 }
276}
277
278pub(crate) enum Effect {
279 Notify(EntityId),
280}
281
282#[cfg(test)]
283mod tests {
284 use super::AppContext;
285
286 #[test]
287 fn test_app_context_send_sync() {
288 // This will not compile if `AppContext` does not implement `Send`
289 fn assert_send<T: Send>() {}
290 assert_send::<AppContext>();
291 }
292}