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