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