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