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