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, run_on_main, spawn_on_main, AssetSource, Context,
 12    LayoutId, MainThread, MainThreadOnly, Platform, PlatformDispatcher, RootView, SvgRenderer,
 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<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 dispatcher = platform.dispatcher();
 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, dispatcher.clone()),
 61                dispatcher,
 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    dispatcher: Arc<dyn PlatformDispatcher>,
 97    text_system: Arc<TextSystem>,
 98    pending_updates: usize,
 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 run_on_main<R>(
188        &self,
189        f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
190    ) -> impl Future<Output = R>
191    where
192        R: Send + 'static,
193    {
194        let this = self.this.upgrade().unwrap();
195        run_on_main(self.dispatcher.clone(), move || {
196            let cx = &mut *this.lock();
197            cx.update(|cx| {
198                f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
199            })
200        })
201    }
202
203    pub fn spawn_on_main<F, R>(
204        &self,
205        f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
206    ) -> impl Future<Output = R>
207    where
208        F: Future<Output = R> + 'static,
209        R: Send + 'static,
210    {
211        let this = self.this.upgrade().unwrap();
212        spawn_on_main(self.dispatcher.clone(), move || {
213            let cx = &mut *this.lock();
214            cx.update(|cx| {
215                f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
216            })
217        })
218    }
219
220    pub fn text_system(&self) -> &Arc<TextSystem> {
221        &self.text_system
222    }
223
224    pub fn text_style(&self) -> TextStyle {
225        let mut style = TextStyle::default();
226        for refinement in &self.text_style_stack {
227            style.refine(refinement);
228        }
229        style
230    }
231
232    pub fn state<S: 'static>(&self) -> &S {
233        self.state_stacks_by_type
234            .get(&TypeId::of::<S>())
235            .and_then(|stack| stack.last())
236            .and_then(|any_state| any_state.downcast_ref::<S>())
237            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
238            .unwrap()
239    }
240
241    pub fn state_mut<S: 'static>(&mut self) -> &mut S {
242        self.state_stacks_by_type
243            .get_mut(&TypeId::of::<S>())
244            .and_then(|stack| stack.last_mut())
245            .and_then(|any_state| any_state.downcast_mut::<S>())
246            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<S>()))
247            .unwrap()
248    }
249
250    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
251        self.text_style_stack.push(text_style);
252    }
253
254    pub(crate) fn pop_text_style(&mut self) {
255        self.text_style_stack.pop();
256    }
257
258    pub(crate) fn push_state<T: Send + Sync + 'static>(&mut self, state: T) {
259        self.state_stacks_by_type
260            .entry(TypeId::of::<T>())
261            .or_default()
262            .push(Box::new(state));
263    }
264
265    pub(crate) fn pop_state<T: 'static>(&mut self) {
266        self.state_stacks_by_type
267            .get_mut(&TypeId::of::<T>())
268            .and_then(|stack| stack.pop())
269            .expect("state stack underflow");
270    }
271}
272
273impl Context for AppContext {
274    type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
275    type Result<T> = T;
276
277    fn entity<T: Send + Sync + 'static>(
278        &mut self,
279        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
280    ) -> Handle<T> {
281        let slot = self.entities.reserve();
282        let entity = build_entity(&mut ModelContext::mutable(self, slot.id));
283        self.entities.redeem(slot, entity)
284    }
285
286    fn update_entity<T: Send + Sync + 'static, R>(
287        &mut self,
288        handle: &Handle<T>,
289        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
290    ) -> R {
291        let mut entity = self.entities.lease(handle);
292        let result = update(&mut *entity, &mut ModelContext::mutable(self, handle.id));
293        self.entities.end_lease(entity);
294        result
295    }
296}
297
298impl MainThread<AppContext> {
299    fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
300        self.0.update(|cx| {
301            update(unsafe {
302                std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
303            })
304        })
305    }
306
307    pub(crate) fn update_window<R>(
308        &mut self,
309        id: WindowId,
310        update: impl FnOnce(&mut WindowContext) -> R,
311    ) -> Result<R> {
312        self.0.update_window(id, |cx| {
313            update(unsafe {
314                std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
315            })
316        })
317    }
318
319    pub(crate) fn platform(&self) -> &dyn Platform {
320        self.platform.borrow_on_main_thread()
321    }
322
323    pub fn activate(&mut self, ignoring_other_apps: bool) {
324        self.platform().activate(ignoring_other_apps);
325    }
326
327    pub fn open_window<S: 'static + Send + Sync>(
328        &mut self,
329        options: crate::WindowOptions,
330        build_root_view: impl FnOnce(&mut WindowContext) -> RootView<S> + Send + 'static,
331    ) -> WindowHandle<S> {
332        self.update(|cx| {
333            let id = cx.windows.insert(None);
334            let handle = WindowHandle::new(id);
335            let mut window = Window::new(handle.into(), options, cx);
336            let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
337            window.root_view.replace(root_view.into_any());
338            cx.windows.get_mut(id).unwrap().replace(window);
339            handle
340        })
341    }
342}
343
344pub(crate) enum Effect {
345    Notify(EntityId),
346}
347
348#[cfg(test)]
349mod tests {
350    use super::AppContext;
351
352    #[test]
353    fn test_app_context_send_sync() {
354        // This will not compile if `AppContext` does not implement `Send`
355        fn assert_send<T: Send>() {}
356        assert_send::<AppContext>();
357    }
358}