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, image_cache::ImageCache, AssetSource, Context, DisplayId, Executor, LayoutId,
12 MainThread, MainThreadOnly, Platform, PlatformDisplayLinker, RootView, SvgRenderer, Task,
13 TextStyle, TextStyleRefinement, TextSystem, Window, WindowContext, WindowHandle, WindowId,
14};
15use anyhow::{anyhow, Result};
16use collections::{HashMap, VecDeque};
17use futures::Future;
18use parking_lot::Mutex;
19use slotmap::SlotMap;
20use smallvec::SmallVec;
21use std::{
22 any::{type_name, Any, TypeId},
23 mem,
24 sync::{Arc, Weak},
25};
26use util::http::{self, HttpClient};
27
28#[derive(Clone)]
29pub struct App(Arc<Mutex<AppContext>>);
30
31impl App {
32 pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
33 let http_client = http::client();
34 Self::new(current_platform(), asset_source, http_client)
35 }
36
37 #[cfg(any(test, feature = "test"))]
38 pub fn test() -> Self {
39 let platform = Arc::new(super::TestPlatform::new());
40 let asset_source = Arc::new(());
41 let http_client = util::http::FakeHttpClient::with_404_response();
42 Self::new(platform, asset_source, http_client)
43 }
44
45 fn new(
46 platform: Arc<dyn Platform>,
47 asset_source: Arc<dyn AssetSource>,
48 http_client: Arc<dyn HttpClient>,
49 ) -> Self {
50 let executor = platform.executor();
51 let entities = EntityMap::new();
52 let unit_entity = entities.insert(entities.reserve(), ());
53 Self(Arc::new_cyclic(|this| {
54 Mutex::new(AppContext {
55 this: this.clone(),
56 text_system: Arc::new(TextSystem::new(platform.text_system())),
57 pending_updates: 0,
58 display_linker: platform.display_linker(),
59 next_frame_callbacks: Default::default(),
60 platform: MainThreadOnly::new(platform, executor.clone()),
61 executor,
62 svg_renderer: SvgRenderer::new(asset_source),
63 image_cache: ImageCache::new(http_client),
64 text_style_stack: Vec::new(),
65 state_stacks_by_type: HashMap::default(),
66 unit_entity,
67 entities,
68 windows: SlotMap::with_key(),
69 pending_effects: Default::default(),
70 observers: Default::default(),
71 layout_id_buffer: Default::default(),
72 })
73 }))
74 }
75
76 pub fn run<F>(self, on_finish_launching: F)
77 where
78 F: 'static + FnOnce(&mut MainThread<AppContext>),
79 {
80 let this = self.clone();
81 let platform = self.0.lock().platform.clone();
82 platform.borrow_on_main_thread().run(Box::new(move || {
83 let cx = &mut *this.0.lock();
84 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
85 on_finish_launching(cx);
86 }));
87 }
88}
89
90type Handlers = SmallVec<[Arc<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>; 2]>;
91type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
92
93pub struct AppContext {
94 this: Weak<Mutex<AppContext>>,
95 platform: MainThreadOnly<dyn Platform>,
96 text_system: Arc<TextSystem>,
97 pending_updates: usize,
98 pub(crate) display_linker: Arc<dyn PlatformDisplayLinker>,
99 pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
100 pub(crate) executor: Executor,
101 pub(crate) svg_renderer: SvgRenderer,
102 pub(crate) image_cache: ImageCache,
103 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
104 pub(crate) state_stacks_by_type: HashMap<TypeId, Vec<Box<dyn Any + Send + Sync>>>,
105 pub(crate) unit_entity: Handle<()>,
106 pub(crate) entities: EntityMap,
107 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
108 pub(crate) pending_effects: VecDeque<Effect>,
109 pub(crate) observers: HashMap<EntityId, Handlers>,
110 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
111}
112
113impl AppContext {
114 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
115 self.pending_updates += 1;
116 let result = update(self);
117 if self.pending_updates == 1 {
118 self.flush_effects();
119 }
120 self.pending_updates -= 1;
121 result
122 }
123
124 pub(crate) fn update_window<R>(
125 &mut self,
126 id: WindowId,
127 update: impl FnOnce(&mut WindowContext) -> R,
128 ) -> Result<R> {
129 self.update(|cx| {
130 let mut window = cx
131 .windows
132 .get_mut(id)
133 .ok_or_else(|| anyhow!("window not found"))?
134 .take()
135 .unwrap();
136
137 let result = update(&mut WindowContext::mutable(cx, &mut window));
138
139 cx.windows
140 .get_mut(id)
141 .ok_or_else(|| anyhow!("window not found"))?
142 .replace(window);
143
144 Ok(result)
145 })
146 }
147
148 fn flush_effects(&mut self) {
149 while let Some(effect) = self.pending_effects.pop_front() {
150 match effect {
151 Effect::Notify(entity_id) => self.apply_notify_effect(entity_id),
152 }
153 }
154
155 let dirty_window_ids = self
156 .windows
157 .iter()
158 .filter_map(|(window_id, window)| {
159 let window = window.as_ref().unwrap();
160 if window.dirty {
161 Some(window_id)
162 } else {
163 None
164 }
165 })
166 .collect::<Vec<_>>();
167
168 for dirty_window_id in dirty_window_ids {
169 self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
170 }
171 }
172
173 fn apply_notify_effect(&mut self, updated_entity: EntityId) {
174 if let Some(mut handlers) = self.observers.remove(&updated_entity) {
175 handlers.retain(|handler| handler(self));
176 if let Some(new_handlers) = self.observers.remove(&updated_entity) {
177 handlers.extend(new_handlers);
178 }
179 self.observers.insert(updated_entity, handlers);
180 }
181 }
182
183 pub fn to_async(&self) -> AsyncAppContext {
184 AsyncAppContext(unsafe { mem::transmute(self.this.clone()) })
185 }
186
187 pub fn executor(&self) -> &Executor {
188 &self.executor
189 }
190
191 pub fn run_on_main<R>(
192 &mut self,
193 f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
194 ) -> Task<R>
195 where
196 R: Send + 'static,
197 {
198 if self.executor.is_main_thread() {
199 Task::ready(f(unsafe {
200 mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
201 }))
202 } else {
203 let this = self.this.upgrade().unwrap();
204 self.executor.run_on_main(move || {
205 let cx = &mut *this.lock();
206 cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
207 })
208 }
209 }
210
211 pub fn spawn_on_main<F, R>(
212 &self,
213 f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
214 ) -> Task<R>
215 where
216 F: Future<Output = R> + Send + 'static,
217 R: Send + 'static,
218 {
219 let this = self.this.upgrade().unwrap();
220 self.executor.spawn_on_main(move || {
221 let cx = &mut *this.lock();
222 cx.update(|cx| {
223 f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
224 })
225 })
226 }
227
228 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
229 where
230 Fut: Future<Output = R> + Send + 'static,
231 R: Send + 'static,
232 {
233 let cx = self.to_async();
234 self.executor.spawn(async move {
235 let future = f(cx);
236 future.await
237 })
238 }
239
240 pub fn text_system(&self) -> &Arc<TextSystem> {
241 &self.text_system
242 }
243
244 pub fn text_style(&self) -> TextStyle {
245 let mut style = TextStyle::default();
246 for refinement in &self.text_style_stack {
247 style.refine(refinement);
248 }
249 style
250 }
251
252 pub fn state<S: 'static>(&self) -> &S {
253 self.state_stacks_by_type
254 .get(&TypeId::of::<S>())
255 .and_then(|stack| stack.last())
256 .and_then(|any_state| any_state.downcast_ref::<S>())
257 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
258 .unwrap()
259 }
260
261 pub fn state_mut<S: 'static>(&mut self) -> &mut S {
262 self.state_stacks_by_type
263 .get_mut(&TypeId::of::<S>())
264 .and_then(|stack| stack.last_mut())
265 .and_then(|any_state| any_state.downcast_mut::<S>())
266 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
267 .unwrap()
268 }
269
270 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
271 self.text_style_stack.push(text_style);
272 }
273
274 pub(crate) fn pop_text_style(&mut self) {
275 self.text_style_stack.pop();
276 }
277
278 pub(crate) fn push_state<T: Send + Sync + 'static>(&mut self, state: T) {
279 self.state_stacks_by_type
280 .entry(TypeId::of::<T>())
281 .or_default()
282 .push(Box::new(state));
283 }
284
285 pub(crate) fn pop_state<T: 'static>(&mut self) {
286 self.state_stacks_by_type
287 .get_mut(&TypeId::of::<T>())
288 .and_then(|stack| stack.pop())
289 .expect("state stack underflow");
290 }
291}
292
293impl Context for AppContext {
294 type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
295 type Result<T> = T;
296
297 fn entity<T: Send + Sync + 'static>(
298 &mut self,
299 build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
300 ) -> Handle<T> {
301 self.update(|cx| {
302 let slot = cx.entities.reserve();
303 let entity = build_entity(&mut ModelContext::mutable(cx, slot.id));
304 cx.entities.insert(slot, entity)
305 })
306 }
307
308 fn update_entity<T: Send + Sync + 'static, R>(
309 &mut self,
310 handle: &Handle<T>,
311 update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
312 ) -> R {
313 self.update(|cx| {
314 let mut entity = cx.entities.lease(handle);
315 let result = update(&mut entity, &mut ModelContext::mutable(cx, handle.id));
316 cx.entities.end_lease(entity);
317 result
318 })
319 }
320}
321
322impl MainThread<AppContext> {
323 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
324 self.0.update(|cx| {
325 update(unsafe {
326 std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
327 })
328 })
329 }
330
331 pub(crate) fn update_window<R>(
332 &mut self,
333 id: WindowId,
334 update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
335 ) -> Result<R> {
336 self.0.update_window(id, |cx| {
337 update(unsafe {
338 std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
339 })
340 })
341 }
342
343 pub(crate) fn platform(&self) -> &dyn Platform {
344 self.platform.borrow_on_main_thread()
345 }
346
347 pub fn activate(&mut self, ignoring_other_apps: bool) {
348 self.platform().activate(ignoring_other_apps);
349 }
350
351 pub fn open_window<S: 'static + Send + Sync>(
352 &mut self,
353 options: crate::WindowOptions,
354 build_root_view: impl FnOnce(&mut WindowContext) -> RootView<S> + Send + 'static,
355 ) -> WindowHandle<S> {
356 self.update(|cx| {
357 let id = cx.windows.insert(None);
358 let handle = WindowHandle::new(id);
359 let mut window = Window::new(handle.into(), options, cx);
360 let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
361 window.root_view.replace(root_view.into_any());
362 cx.windows.get_mut(id).unwrap().replace(window);
363 handle
364 })
365 }
366}
367
368pub(crate) enum Effect {
369 Notify(EntityId),
370}
371
372#[cfg(test)]
373mod tests {
374 use super::AppContext;
375
376 #[test]
377 fn test_app_context_send_sync() {
378 // This will not compile if `AppContext` does not implement `Send`
379 fn assert_send<T: Send>() {}
380 assert_send::<AppContext>();
381 }
382}