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;
  9use smallvec::SmallVec;
 10
 11use crate::{
 12    current_platform, image_cache::ImageCache, AssetSource, Context, DisplayId, Executor,
 13    FocusEvent, FocusHandle, FocusId, LayoutId, MainThread, MainThreadOnly, Platform,
 14    SubscriberSet, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, Window,
 15    WindowContext, WindowHandle, WindowId,
 16};
 17use anyhow::{anyhow, Result};
 18use collections::{HashMap, HashSet, VecDeque};
 19use futures::Future;
 20use parking_lot::Mutex;
 21use slotmap::SlotMap;
 22use std::{
 23    any::{type_name, Any, TypeId},
 24    mem,
 25    sync::{atomic::Ordering::SeqCst, Arc, Weak},
 26};
 27use util::http::{self, HttpClient};
 28
 29#[derive(Clone)]
 30pub struct App(Arc<Mutex<AppContext>>);
 31
 32impl App {
 33    pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
 34        let http_client = http::client();
 35        Self::new(current_platform(), asset_source, http_client)
 36    }
 37
 38    #[cfg(any(test, feature = "test"))]
 39    pub fn test() -> Self {
 40        let platform = Arc::new(super::TestPlatform::new());
 41        let asset_source = Arc::new(());
 42        let http_client = util::http::FakeHttpClient::with_404_response();
 43        Self::new(platform, asset_source, http_client)
 44    }
 45
 46    fn new(
 47        platform: Arc<dyn Platform>,
 48        asset_source: Arc<dyn AssetSource>,
 49        http_client: Arc<dyn HttpClient>,
 50    ) -> Self {
 51        let executor = platform.executor();
 52        let entities = EntityMap::new();
 53        let unit_entity = entities.insert(entities.reserve(), ());
 54        Self(Arc::new_cyclic(|this| {
 55            Mutex::new(AppContext {
 56                this: this.clone(),
 57                text_system: Arc::new(TextSystem::new(platform.text_system())),
 58                pending_updates: 0,
 59                flushing_effects: false,
 60                next_frame_callbacks: Default::default(),
 61                platform: MainThreadOnly::new(platform, executor.clone()),
 62                executor,
 63                svg_renderer: SvgRenderer::new(asset_source),
 64                image_cache: ImageCache::new(http_client),
 65                text_style_stack: Vec::new(),
 66                global_stacks_by_type: HashMap::default(),
 67                unit_entity,
 68                entities,
 69                windows: SlotMap::with_key(),
 70                pending_notifications: Default::default(),
 71                pending_effects: Default::default(),
 72                observers: SubscriberSet::new(),
 73                event_handlers: SubscriberSet::new(),
 74                release_handlers: SubscriberSet::new(),
 75                layout_id_buffer: Default::default(),
 76            })
 77        }))
 78    }
 79
 80    pub fn run<F>(self, on_finish_launching: F)
 81    where
 82        F: 'static + FnOnce(&mut MainThread<AppContext>),
 83    {
 84        let this = self.clone();
 85        let platform = self.0.lock().platform.clone();
 86        platform.borrow_on_main_thread().run(Box::new(move || {
 87            let cx = &mut *this.0.lock();
 88            let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
 89            on_finish_launching(cx);
 90        }));
 91    }
 92}
 93
 94type Handler = Box<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>;
 95type EventHandler = Box<dyn Fn(&dyn Any, &mut AppContext) -> bool + Send + Sync + 'static>;
 96type ReleaseHandler = Box<dyn Fn(&mut dyn Any, &mut AppContext) + Send + Sync + 'static>;
 97type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
 98
 99pub struct AppContext {
100    this: Weak<Mutex<AppContext>>,
101    pub(crate) platform: MainThreadOnly<dyn Platform>,
102    text_system: Arc<TextSystem>,
103    flushing_effects: bool,
104    pending_updates: usize,
105    pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
106    pub(crate) executor: Executor,
107    pub(crate) svg_renderer: SvgRenderer,
108    pub(crate) image_cache: ImageCache,
109    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
110    pub(crate) global_stacks_by_type: HashMap<TypeId, Vec<Box<dyn Any + Send + Sync>>>,
111    pub(crate) unit_entity: Handle<()>,
112    pub(crate) entities: EntityMap,
113    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
114    pub(crate) pending_notifications: HashSet<EntityId>,
115    pending_effects: VecDeque<Effect>,
116    pub(crate) observers: SubscriberSet<EntityId, Handler>,
117    pub(crate) event_handlers: SubscriberSet<EntityId, EventHandler>,
118    pub(crate) release_handlers: SubscriberSet<EntityId, ReleaseHandler>,
119    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
120}
121
122impl AppContext {
123    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
124        self.pending_updates += 1;
125        let result = update(self);
126        if !self.flushing_effects && self.pending_updates == 1 {
127            self.flushing_effects = true;
128            self.flush_effects();
129            self.flushing_effects = false;
130        }
131        self.pending_updates -= 1;
132        result
133    }
134
135    pub(crate) fn update_window<R>(
136        &mut self,
137        id: WindowId,
138        update: impl FnOnce(&mut WindowContext) -> R,
139    ) -> Result<R> {
140        self.update(|cx| {
141            let mut window = cx
142                .windows
143                .get_mut(id)
144                .ok_or_else(|| anyhow!("window not found"))?
145                .take()
146                .unwrap();
147
148            let result = update(&mut WindowContext::mutable(cx, &mut window));
149
150            cx.windows
151                .get_mut(id)
152                .ok_or_else(|| anyhow!("window not found"))?
153                .replace(window);
154
155            Ok(result)
156        })
157    }
158
159    pub(crate) fn push_effect(&mut self, effect: Effect) {
160        match &effect {
161            Effect::Notify { emitter } => {
162                if self.pending_notifications.insert(*emitter) {
163                    self.pending_effects.push_back(effect);
164                }
165            }
166            Effect::Emit { .. } => self.pending_effects.push_back(effect),
167            Effect::FocusChanged { .. } => self.pending_effects.push_back(effect),
168        }
169    }
170
171    fn flush_effects(&mut self) {
172        loop {
173            self.release_dropped_entities();
174            self.release_dropped_focus_handles();
175            if let Some(effect) = self.pending_effects.pop_front() {
176                match effect {
177                    Effect::Notify { emitter } => self.apply_notify_effect(emitter),
178                    Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
179                    Effect::FocusChanged { window_id, focused } => {
180                        self.apply_focus_changed(window_id, focused)
181                    }
182                }
183            } else {
184                break;
185            }
186        }
187
188        let dirty_window_ids = self
189            .windows
190            .iter()
191            .filter_map(|(window_id, window)| {
192                let window = window.as_ref().unwrap();
193                if window.dirty {
194                    Some(window_id)
195                } else {
196                    None
197                }
198            })
199            .collect::<SmallVec<[_; 8]>>();
200
201        for dirty_window_id in dirty_window_ids {
202            self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
203        }
204    }
205
206    fn release_dropped_entities(&mut self) {
207        loop {
208            let dropped = self.entities.take_dropped();
209            if dropped.is_empty() {
210                break;
211            }
212
213            for (entity_id, mut entity) in dropped {
214                self.observers.remove(&entity_id);
215                self.event_handlers.remove(&entity_id);
216                for release_callback in self.release_handlers.remove(&entity_id) {
217                    release_callback(&mut entity, self);
218                }
219            }
220        }
221    }
222
223    fn release_dropped_focus_handles(&mut self) {
224        let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
225        for window_id in window_ids {
226            self.update_window(window_id, |cx| {
227                let mut blur_window = false;
228                let focus = cx.window.focus;
229                cx.window.focus_handles.write().retain(|handle_id, count| {
230                    if count.load(SeqCst) == 0 {
231                        if focus == Some(handle_id) {
232                            blur_window = true;
233                        }
234                        false
235                    } else {
236                        true
237                    }
238                });
239
240                if blur_window {
241                    cx.blur();
242                }
243            })
244            .unwrap();
245        }
246    }
247
248    fn apply_notify_effect(&mut self, emitter: EntityId) {
249        self.pending_notifications.remove(&emitter);
250        self.observers
251            .clone()
252            .retain(&emitter, |handler| handler(self));
253    }
254
255    fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
256        self.event_handlers
257            .clone()
258            .retain(&emitter, |handler| handler(&event, self));
259    }
260
261    fn apply_focus_changed(&mut self, window_id: WindowId, focused: Option<FocusId>) {
262        self.update_window(window_id, |cx| {
263            if cx.window.focus == focused {
264                let mut listeners = mem::take(&mut cx.window.focus_listeners);
265                let focused =
266                    focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
267                let blurred = cx
268                    .window
269                    .last_blur
270                    .take()
271                    .unwrap()
272                    .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
273                if focused.is_some() || blurred.is_some() {
274                    let event = FocusEvent { focused, blurred };
275                    for listener in &listeners {
276                        listener(&event, cx);
277                    }
278                }
279
280                listeners.extend(cx.window.focus_listeners.drain(..));
281                cx.window.focus_listeners = listeners;
282            }
283        })
284        .ok();
285    }
286
287    pub fn to_async(&self) -> AsyncAppContext {
288        AsyncAppContext(unsafe { mem::transmute(self.this.clone()) })
289    }
290
291    pub fn executor(&self) -> &Executor {
292        &self.executor
293    }
294
295    pub fn run_on_main<R>(
296        &mut self,
297        f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
298    ) -> Task<R>
299    where
300        R: Send + 'static,
301    {
302        if self.executor.is_main_thread() {
303            Task::ready(f(unsafe {
304                mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
305            }))
306        } else {
307            let this = self.this.upgrade().unwrap();
308            self.executor.run_on_main(move || {
309                let cx = &mut *this.lock();
310                cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
311            })
312        }
313    }
314
315    pub fn spawn_on_main<F, R>(
316        &self,
317        f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
318    ) -> Task<R>
319    where
320        F: Future<Output = R> + 'static,
321        R: Send + 'static,
322    {
323        let this = self.this.upgrade().unwrap();
324        self.executor.spawn_on_main(move || {
325            let cx = &mut *this.lock();
326            cx.update(|cx| {
327                f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
328            })
329        })
330    }
331
332    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
333    where
334        Fut: Future<Output = R> + Send + 'static,
335        R: Send + 'static,
336    {
337        let cx = self.to_async();
338        self.executor.spawn(async move {
339            let future = f(cx);
340            future.await
341        })
342    }
343
344    pub fn text_system(&self) -> &Arc<TextSystem> {
345        &self.text_system
346    }
347
348    pub fn text_style(&self) -> TextStyle {
349        let mut style = TextStyle::default();
350        for refinement in &self.text_style_stack {
351            style.refine(refinement);
352        }
353        style
354    }
355
356    pub fn global<G: 'static>(&self) -> &G {
357        self.global_stacks_by_type
358            .get(&TypeId::of::<G>())
359            .and_then(|stack| stack.last())
360            .and_then(|any_state| any_state.downcast_ref::<G>())
361            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
362            .unwrap()
363    }
364
365    pub fn global_mut<G: 'static>(&mut self) -> &mut G {
366        self.global_stacks_by_type
367            .get_mut(&TypeId::of::<G>())
368            .and_then(|stack| stack.last_mut())
369            .and_then(|any_state| any_state.downcast_mut::<G>())
370            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
371            .unwrap()
372    }
373
374    pub fn default_global<G: 'static + Default + Sync + Send>(&mut self) -> &mut G {
375        let stack = self
376            .global_stacks_by_type
377            .entry(TypeId::of::<G>())
378            .or_default();
379        if stack.is_empty() {
380            stack.push(Box::new(G::default()));
381        }
382        stack.last_mut().unwrap().downcast_mut::<G>().unwrap()
383    }
384
385    pub(crate) fn push_global<T: Send + Sync + 'static>(&mut self, state: T) {
386        self.global_stacks_by_type
387            .entry(TypeId::of::<T>())
388            .or_default()
389            .push(Box::new(state));
390    }
391
392    pub(crate) fn pop_global<T: 'static>(&mut self) {
393        self.global_stacks_by_type
394            .get_mut(&TypeId::of::<T>())
395            .and_then(|stack| stack.pop())
396            .expect("state stack underflow");
397    }
398
399    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
400        self.text_style_stack.push(text_style);
401    }
402
403    pub(crate) fn pop_text_style(&mut self) {
404        self.text_style_stack.pop();
405    }
406}
407
408impl Context for AppContext {
409    type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
410    type Result<T> = T;
411
412    fn entity<T: Send + Sync + 'static>(
413        &mut self,
414        build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
415    ) -> Handle<T> {
416        self.update(|cx| {
417            let slot = cx.entities.reserve();
418            let entity = build_entity(&mut ModelContext::mutable(cx, slot.id));
419            cx.entities.insert(slot, entity)
420        })
421    }
422
423    fn update_entity<T: Send + Sync + 'static, R>(
424        &mut self,
425        handle: &Handle<T>,
426        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
427    ) -> R {
428        self.update(|cx| {
429            let mut entity = cx.entities.lease(handle);
430            let result = update(&mut entity, &mut ModelContext::mutable(cx, handle.id));
431            cx.entities.end_lease(entity);
432            result
433        })
434    }
435}
436
437impl MainThread<AppContext> {
438    fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
439        self.0.update(|cx| {
440            update(unsafe {
441                std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
442            })
443        })
444    }
445
446    pub(crate) fn update_window<R>(
447        &mut self,
448        id: WindowId,
449        update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
450    ) -> Result<R> {
451        self.0.update_window(id, |cx| {
452            update(unsafe {
453                std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
454            })
455        })
456    }
457
458    pub(crate) fn platform(&self) -> &dyn Platform {
459        self.platform.borrow_on_main_thread()
460    }
461
462    pub fn activate(&mut self, ignoring_other_apps: bool) {
463        self.platform().activate(ignoring_other_apps);
464    }
465
466    pub fn open_window<S: 'static + Send + Sync>(
467        &mut self,
468        options: crate::WindowOptions,
469        build_root_view: impl FnOnce(&mut WindowContext) -> View<S> + Send + 'static,
470    ) -> WindowHandle<S> {
471        self.update(|cx| {
472            let id = cx.windows.insert(None);
473            let handle = WindowHandle::new(id);
474            let mut window = Window::new(handle.into(), options, cx);
475            let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
476            window.root_view.replace(root_view.into_any());
477            cx.windows.get_mut(id).unwrap().replace(window);
478            handle
479        })
480    }
481}
482
483pub(crate) enum Effect {
484    Notify {
485        emitter: EntityId,
486    },
487    Emit {
488        emitter: EntityId,
489        event: Box<dyn Any + Send + Sync + 'static>,
490    },
491    FocusChanged {
492        window_id: WindowId,
493        focused: Option<FocusId>,
494    },
495}
496
497#[cfg(test)]
498mod tests {
499    use super::AppContext;
500
501    #[test]
502    fn test_app_context_send_sync() {
503        // This will not compile if `AppContext` does not implement `Send`
504        fn assert_send<T: Send>() {}
505        assert_send::<AppContext>();
506    }
507}