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