app.rs

  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, DisplayLinker, Executor,
 12    LayoutId, 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<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 entities = EntityMap::new();
 55        let unit_entity = entities.insert(entities.reserve(), ());
 56        Self(Arc::new_cyclic(|this| {
 57            Mutex::new(AppContext {
 58                this: this.clone(),
 59                display_linker: Arc::new(DisplayLinker::new(platform.display_linker())),
 60                text_system: Arc::new(TextSystem::new(platform.text_system())),
 61                platform: MainThreadOnly::new(platform, executor.clone()),
 62                executor,
 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            let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
 87            on_finish_launching(cx);
 88        }));
 89    }
 90}
 91
 92type Handlers = SmallVec<[Arc<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>; 2]>;
 93
 94pub struct AppContext {
 95    this: Weak<Mutex<AppContext>>,
 96    platform: MainThreadOnly<dyn Platform>,
 97    text_system: Arc<TextSystem>,
 98    pending_updates: usize,
 99    pub(crate) executor: Executor,
100    pub(crate) display_linker: Arc<DisplayLinker>,
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        dbg!("flush effects");
150        while let Some(effect) = self.pending_effects.pop_front() {
151            match effect {
152                Effect::Notify(entity_id) => self.apply_notify_effect(entity_id),
153            }
154        }
155
156        let dirty_window_ids = self
157            .windows
158            .iter()
159            .filter_map(|(window_id, window)| {
160                let window = window.as_ref().unwrap();
161                if window.dirty {
162                    Some(window_id)
163                } else {
164                    None
165                }
166            })
167            .collect::<Vec<_>>();
168
169        for dirty_window_id in dirty_window_ids {
170            self.update_window(dirty_window_id, |cx| cx.draw())
171                .unwrap()
172                .log_err();
173        }
174    }
175
176    fn apply_notify_effect(&mut self, updated_entity: EntityId) {
177        if let Some(mut handlers) = self.observers.remove(&updated_entity) {
178            handlers.retain(|handler| handler(self));
179            if let Some(new_handlers) = self.observers.remove(&updated_entity) {
180                handlers.extend(new_handlers);
181            }
182            self.observers.insert(updated_entity, handlers);
183        }
184    }
185
186    pub fn to_async(&self) -> AsyncAppContext {
187        AsyncAppContext(unsafe { mem::transmute(self.this.clone()) })
188    }
189
190    pub fn executor(&self) -> &Executor {
191        &self.executor
192    }
193
194    pub fn run_on_main<R>(
195        &mut self,
196        f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
197    ) -> Task<R>
198    where
199        R: Send + 'static,
200    {
201        if self.executor.is_main_thread() {
202            Task::ready(f(unsafe {
203                mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
204            }))
205        } else {
206            let this = self.this.upgrade().unwrap();
207            self.executor.run_on_main(move || {
208                let cx = &mut *this.lock();
209                cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
210            })
211        }
212    }
213
214    pub fn spawn_on_main<F, R>(
215        &self,
216        f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
217    ) -> Task<R>
218    where
219        F: Future<Output = R> + Send + 'static,
220        R: Send + 'static,
221    {
222        let this = self.this.upgrade().unwrap();
223        self.executor.spawn_on_main(move || {
224            let cx = &mut *this.lock();
225            cx.update(|cx| {
226                f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
227            })
228        })
229    }
230
231    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
232    where
233        Fut: Future<Output = R> + Send + 'static,
234        R: Send + 'static,
235    {
236        let cx = self.to_async();
237        self.executor.spawn(async move {
238            let future = f(cx);
239            future.await
240        })
241    }
242
243    pub fn text_system(&self) -> &Arc<TextSystem> {
244        &self.text_system
245    }
246
247    pub fn text_style(&self) -> TextStyle {
248        let mut style = TextStyle::default();
249        for refinement in &self.text_style_stack {
250            style.refine(refinement);
251        }
252        style
253    }
254
255    pub fn state<S: 'static>(&self) -> &S {
256        self.state_stacks_by_type
257            .get(&TypeId::of::<S>())
258            .and_then(|stack| stack.last())
259            .and_then(|any_state| any_state.downcast_ref::<S>())
260            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
261            .unwrap()
262    }
263
264    pub fn state_mut<S: 'static>(&mut self) -> &mut S {
265        self.state_stacks_by_type
266            .get_mut(&TypeId::of::<S>())
267            .and_then(|stack| stack.last_mut())
268            .and_then(|any_state| any_state.downcast_mut::<S>())
269            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
270            .unwrap()
271    }
272
273    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
274        self.text_style_stack.push(text_style);
275    }
276
277    pub(crate) fn pop_text_style(&mut self) {
278        self.text_style_stack.pop();
279    }
280
281    pub(crate) fn push_state<T: Send + Sync + 'static>(&mut self, state: T) {
282        self.state_stacks_by_type
283            .entry(TypeId::of::<T>())
284            .or_default()
285            .push(Box::new(state));
286    }
287
288    pub(crate) fn pop_state<T: 'static>(&mut self) {
289        self.state_stacks_by_type
290            .get_mut(&TypeId::of::<T>())
291            .and_then(|stack| stack.pop())
292            .expect("state stack underflow");
293    }
294}
295
296impl Context for AppContext {
297    type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
298    type Result<T> = T;
299
300    fn entity<T: Send + Sync + 'static>(
301        &mut self,
302        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
303    ) -> Handle<T> {
304        self.update(|cx| {
305            let slot = cx.entities.reserve();
306            let entity = build_entity(&mut ModelContext::mutable(cx, slot.id));
307            cx.entities.insert(slot, entity)
308        })
309    }
310
311    fn update_entity<T: Send + Sync + 'static, R>(
312        &mut self,
313        handle: &Handle<T>,
314        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
315    ) -> R {
316        self.update(|cx| {
317            let mut entity = cx.entities.lease(handle);
318            let result = update(&mut entity, &mut ModelContext::mutable(cx, handle.id));
319            cx.entities.end_lease(entity);
320            result
321        })
322    }
323}
324
325impl MainThread<AppContext> {
326    fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
327        self.0.update(|cx| {
328            update(unsafe {
329                std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
330            })
331        })
332    }
333
334    pub(crate) fn update_window<R>(
335        &mut self,
336        id: WindowId,
337        update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
338    ) -> Result<R> {
339        self.0.update_window(id, |cx| {
340            update(unsafe {
341                std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
342            })
343        })
344    }
345
346    pub(crate) fn platform(&self) -> &dyn Platform {
347        self.platform.borrow_on_main_thread()
348    }
349
350    pub fn activate(&mut self, ignoring_other_apps: bool) {
351        self.platform().activate(ignoring_other_apps);
352    }
353
354    pub fn open_window<S: 'static + Send + Sync>(
355        &mut self,
356        options: crate::WindowOptions,
357        build_root_view: impl FnOnce(&mut WindowContext) -> RootView<S> + Send + 'static,
358    ) -> WindowHandle<S> {
359        self.update(|cx| {
360            let id = cx.windows.insert(None);
361            let handle = WindowHandle::new(id);
362            let mut window = Window::new(handle.into(), options, cx);
363            let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
364            window.root_view.replace(root_view.into_any());
365            cx.windows.get_mut(id).unwrap().replace(window);
366            handle
367        })
368    }
369}
370
371pub(crate) enum Effect {
372    Notify(EntityId),
373}
374
375#[cfg(test)]
376mod tests {
377    use super::AppContext;
378
379    #[test]
380    fn test_app_context_send_sync() {
381        // This will not compile if `AppContext` does not implement `Send`
382        fn assert_send<T: Send>() {}
383        assert_send::<AppContext>();
384    }
385}