app.rs

  1mod async_context;
  2mod entity_map;
  3mod model_context;
  4#[cfg(any(test, feature = "test-support"))]
  5mod test_context;
  6
  7pub use async_context::*;
  8pub use entity_map::*;
  9pub use model_context::*;
 10use refineable::Refineable;
 11use smallvec::SmallVec;
 12#[cfg(any(test, feature = "test-support"))]
 13pub use test_context::*;
 14
 15use crate::{
 16    current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AnyWindowHandle,
 17    AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,
 18    Entity, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId,
 19    PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render, SharedString,
 20    SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem,
 21    View, Window, WindowContext, WindowHandle, WindowId,
 22};
 23use anyhow::{anyhow, Result};
 24use collections::{HashMap, HashSet, VecDeque};
 25use futures::{channel::oneshot, future::LocalBoxFuture, Future};
 26use parking_lot::Mutex;
 27use slotmap::SlotMap;
 28use std::{
 29    any::{type_name, Any, TypeId},
 30    cell::RefCell,
 31    marker::PhantomData,
 32    mem,
 33    ops::{Deref, DerefMut},
 34    path::{Path, PathBuf},
 35    rc::{Rc, Weak},
 36    sync::{atomic::Ordering::SeqCst, Arc},
 37    time::Duration,
 38};
 39use util::http::{self, HttpClient};
 40
 41pub struct App(Rc<RefCell<AppContext>>);
 42
 43/// Represents an application before it is fully launched. Once your app is
 44/// configured, you'll start the app with `App::run`.
 45impl App {
 46    /// Builds an app with the given asset source.
 47    pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
 48        Self(AppContext::new(
 49            current_platform(),
 50            asset_source,
 51            http::client(),
 52        ))
 53    }
 54
 55    /// Start the application. The provided callback will be called once the
 56    /// app is fully launched.
 57    pub fn run<F>(self, on_finish_launching: F)
 58    where
 59        F: 'static + FnOnce(&mut AppContext),
 60    {
 61        let this = self.0.clone();
 62        let platform = self.0.borrow().platform.clone();
 63        platform.run(Box::new(move || {
 64            let cx = &mut *this.borrow_mut();
 65            on_finish_launching(cx);
 66        }));
 67    }
 68
 69    /// Register a handler to be invoked when the platform instructs the application
 70    /// to open one or more URLs.
 71    pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
 72    where
 73        F: 'static + FnMut(Vec<String>, &mut AppContext),
 74    {
 75        let this = Rc::downgrade(&self.0);
 76        self.0.borrow().platform.on_open_urls(Box::new(move |urls| {
 77            if let Some(app) = this.upgrade() {
 78                callback(urls, &mut *app.borrow_mut());
 79            }
 80        }));
 81        self
 82    }
 83
 84    pub fn on_reopen<F>(&self, mut callback: F) -> &Self
 85    where
 86        F: 'static + FnMut(&mut AppContext),
 87    {
 88        let this = Rc::downgrade(&self.0);
 89        self.0.borrow_mut().platform.on_reopen(Box::new(move || {
 90            if let Some(app) = this.upgrade() {
 91                callback(&mut app.borrow_mut());
 92            }
 93        }));
 94        self
 95    }
 96
 97    pub fn metadata(&self) -> AppMetadata {
 98        self.0.borrow().app_metadata.clone()
 99    }
100
101    pub fn background_executor(&self) -> BackgroundExecutor {
102        self.0.borrow().background_executor.clone()
103    }
104
105    pub fn foreground_executor(&self) -> ForegroundExecutor {
106        self.0.borrow().foreground_executor.clone()
107    }
108
109    pub fn text_system(&self) -> Arc<TextSystem> {
110        self.0.borrow().text_system.clone()
111    }
112}
113
114type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
115type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
116type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
117type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
118type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
119type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
120
121pub struct AppContext {
122    this: Weak<RefCell<AppContext>>,
123    pub(crate) platform: Rc<dyn Platform>,
124    app_metadata: AppMetadata,
125    text_system: Arc<TextSystem>,
126    flushing_effects: bool,
127    pending_updates: usize,
128    pub(crate) active_drag: Option<AnyDrag>,
129    pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
130    pub(crate) background_executor: BackgroundExecutor,
131    pub(crate) foreground_executor: ForegroundExecutor,
132    pub(crate) svg_renderer: SvgRenderer,
133    asset_source: Arc<dyn AssetSource>,
134    pub(crate) image_cache: ImageCache,
135    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
136    pub(crate) globals_by_type: HashMap<TypeId, AnyBox>,
137    pub(crate) entities: EntityMap,
138    pub(crate) windows: SlotMap<WindowId, Option<Window>>,
139    pub(crate) keymap: Arc<Mutex<Keymap>>,
140    pub(crate) global_action_listeners:
141        HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self)>>>,
142    action_builders: HashMap<SharedString, ActionBuilder>,
143    pending_effects: VecDeque<Effect>,
144    pub(crate) pending_notifications: HashSet<EntityId>,
145    pub(crate) pending_global_notifications: HashSet<TypeId>,
146    pub(crate) observers: SubscriberSet<EntityId, Handler>,
147    pub(crate) event_listeners: SubscriberSet<EntityId, Listener>,
148    pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
149    pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
150    pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
151    pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
152    pub(crate) propagate_event: bool,
153}
154
155impl AppContext {
156    pub(crate) fn new(
157        platform: Rc<dyn Platform>,
158        asset_source: Arc<dyn AssetSource>,
159        http_client: Arc<dyn HttpClient>,
160    ) -> Rc<RefCell<Self>> {
161        let executor = platform.background_executor();
162        let foreground_executor = platform.foreground_executor();
163        assert!(
164            executor.is_main_thread(),
165            "must construct App on main thread"
166        );
167
168        let text_system = Arc::new(TextSystem::new(platform.text_system()));
169        let entities = EntityMap::new();
170
171        let app_metadata = AppMetadata {
172            os_name: platform.os_name(),
173            os_version: platform.os_version().ok(),
174            app_version: platform.app_version().ok(),
175        };
176
177        Rc::new_cyclic(|this| {
178            RefCell::new(AppContext {
179                this: this.clone(),
180                text_system,
181                platform,
182                app_metadata,
183                flushing_effects: false,
184                pending_updates: 0,
185                next_frame_callbacks: Default::default(),
186                background_executor: executor,
187                foreground_executor,
188                svg_renderer: SvgRenderer::new(asset_source.clone()),
189                asset_source,
190                image_cache: ImageCache::new(http_client),
191                text_style_stack: Vec::new(),
192                globals_by_type: HashMap::default(),
193                entities,
194                windows: SlotMap::with_key(),
195                keymap: Arc::new(Mutex::new(Keymap::default())),
196                global_action_listeners: HashMap::default(),
197                action_builders: HashMap::default(),
198                pending_effects: VecDeque::new(),
199                pending_notifications: HashSet::default(),
200                pending_global_notifications: HashSet::default(),
201                observers: SubscriberSet::new(),
202                event_listeners: SubscriberSet::new(),
203                release_listeners: SubscriberSet::new(),
204                global_observers: SubscriberSet::new(),
205                quit_observers: SubscriberSet::new(),
206                layout_id_buffer: Default::default(),
207                propagate_event: true,
208                active_drag: None,
209            })
210        })
211    }
212
213    /// Quit the application gracefully. Handlers registered with `ModelContext::on_app_quit`
214    /// will be given 100ms to complete before exiting.
215    pub fn quit(&mut self) {
216        let mut futures = Vec::new();
217
218        for observer in self.quit_observers.remove(&()) {
219            futures.push(observer(self));
220        }
221
222        self.windows.clear();
223        self.flush_effects();
224
225        let futures = futures::future::join_all(futures);
226        if self
227            .background_executor
228            .block_with_timeout(Duration::from_millis(100), futures)
229            .is_err()
230        {
231            log::error!("timed out waiting on app_will_quit");
232        }
233
234        self.globals_by_type.clear();
235    }
236
237    pub fn app_metadata(&self) -> AppMetadata {
238        self.app_metadata.clone()
239    }
240
241    /// Schedules all windows in the application to be redrawn. This can be called
242    /// multiple times in an update cycle and still result in a single redraw.
243    pub fn refresh(&mut self) {
244        self.pending_effects.push_back(Effect::Refresh);
245    }
246    pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
247        self.pending_updates += 1;
248        let result = update(self);
249        if !self.flushing_effects && self.pending_updates == 1 {
250            self.flushing_effects = true;
251            self.flush_effects();
252            self.flushing_effects = false;
253        }
254        self.pending_updates -= 1;
255        result
256    }
257
258    pub fn windows(&self) -> Vec<AnyWindowHandle> {
259        self.windows
260            .values()
261            .filter_map(|window| Some(window.as_ref()?.handle.clone()))
262            .collect()
263    }
264
265    /// Opens a new window with the given option and the root view returned by the given function.
266    /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
267    /// functionality.
268    pub fn open_window<V: Render>(
269        &mut self,
270        options: crate::WindowOptions,
271        build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
272    ) -> WindowHandle<V> {
273        self.update(|cx| {
274            let id = cx.windows.insert(None);
275            let handle = WindowHandle::new(id);
276            let mut window = Window::new(handle.into(), options, cx);
277            let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
278            window.root_view.replace(root_view.into());
279            cx.windows.get_mut(id).unwrap().replace(window);
280            handle
281        })
282    }
283
284    /// Instructs the platform to activate the application by bringing it to the foreground.
285    pub fn activate(&self, ignoring_other_apps: bool) {
286        self.platform.activate(ignoring_other_apps);
287    }
288
289    /// Returns the list of currently active displays.
290    pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
291        self.platform.displays()
292    }
293
294    /// Writes data to the platform clipboard.
295    pub fn write_to_clipboard(&self, item: ClipboardItem) {
296        self.platform.write_to_clipboard(item)
297    }
298
299    /// Reads data from the platform clipboard.
300    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
301        self.platform.read_from_clipboard()
302    }
303
304    /// Writes credentials to the platform keychain.
305    pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
306        self.platform.write_credentials(url, username, password)
307    }
308
309    /// Reads credentials from the platform keychain.
310    pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
311        self.platform.read_credentials(url)
312    }
313
314    /// Deletes credentials from the platform keychain.
315    pub fn delete_credentials(&self, url: &str) -> Result<()> {
316        self.platform.delete_credentials(url)
317    }
318
319    /// Directs the platform's default browser to open the given URL.
320    pub fn open_url(&self, url: &str) {
321        self.platform.open_url(url);
322    }
323
324    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
325        self.platform.path_for_auxiliary_executable(name)
326    }
327
328    pub fn prompt_for_paths(
329        &self,
330        options: PathPromptOptions,
331    ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
332        self.platform.prompt_for_paths(options)
333    }
334
335    pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
336        self.platform.prompt_for_new_path(directory)
337    }
338
339    pub fn reveal_path(&self, path: &Path) {
340        self.platform.reveal_path(path)
341    }
342
343    pub(crate) fn push_effect(&mut self, effect: Effect) {
344        match &effect {
345            Effect::Notify { emitter } => {
346                if !self.pending_notifications.insert(*emitter) {
347                    return;
348                }
349            }
350            Effect::NotifyGlobalObservers { global_type } => {
351                if !self.pending_global_notifications.insert(*global_type) {
352                    return;
353                }
354            }
355            _ => {}
356        };
357
358        self.pending_effects.push_back(effect);
359    }
360
361    /// Called at the end of AppContext::update to complete any side effects
362    /// such as notifying observers, emitting events, etc. Effects can themselves
363    /// cause effects, so we continue looping until all effects are processed.
364    fn flush_effects(&mut self) {
365        loop {
366            self.release_dropped_entities();
367            self.release_dropped_focus_handles();
368            if let Some(effect) = self.pending_effects.pop_front() {
369                match effect {
370                    Effect::Notify { emitter } => {
371                        self.apply_notify_effect(emitter);
372                    }
373                    Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
374                    Effect::FocusChanged {
375                        window_handle,
376                        focused,
377                    } => {
378                        self.apply_focus_changed_effect(window_handle, focused);
379                    }
380                    Effect::Refresh => {
381                        self.apply_refresh_effect();
382                    }
383                    Effect::NotifyGlobalObservers { global_type } => {
384                        self.apply_notify_global_observers_effect(global_type);
385                    }
386                    Effect::Defer { callback } => {
387                        self.apply_defer_effect(callback);
388                    }
389                }
390            } else {
391                break;
392            }
393        }
394
395        let dirty_window_ids = self
396            .windows
397            .iter()
398            .filter_map(|(_, window)| {
399                let window = window.as_ref().unwrap();
400                if window.dirty {
401                    Some(window.handle.clone())
402                } else {
403                    None
404                }
405            })
406            .collect::<SmallVec<[_; 8]>>();
407
408        for dirty_window_handle in dirty_window_ids {
409            dirty_window_handle.update(self, |_, cx| cx.draw()).unwrap();
410        }
411    }
412
413    /// Repeatedly called during `flush_effects` to release any entities whose
414    /// reference count has become zero. We invoke any release observers before dropping
415    /// each entity.
416    fn release_dropped_entities(&mut self) {
417        loop {
418            let dropped = self.entities.take_dropped();
419            if dropped.is_empty() {
420                break;
421            }
422
423            for (entity_id, mut entity) in dropped {
424                self.observers.remove(&entity_id);
425                self.event_listeners.remove(&entity_id);
426                for release_callback in self.release_listeners.remove(&entity_id) {
427                    release_callback(entity.as_mut(), self);
428                }
429            }
430        }
431    }
432
433    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
434    /// For now, we simply blur the window if this happens, but we may want to support invoking
435    /// a window blur handler to restore focus to some logical element.
436    fn release_dropped_focus_handles(&mut self) {
437        for window_handle in self.windows() {
438            window_handle
439                .update(self, |_, cx| {
440                    let mut blur_window = false;
441                    let focus = cx.window.focus;
442                    cx.window.focus_handles.write().retain(|handle_id, count| {
443                        if count.load(SeqCst) == 0 {
444                            if focus == Some(handle_id) {
445                                blur_window = true;
446                            }
447                            false
448                        } else {
449                            true
450                        }
451                    });
452
453                    if blur_window {
454                        cx.blur();
455                    }
456                })
457                .unwrap();
458        }
459    }
460
461    fn apply_notify_effect(&mut self, emitter: EntityId) {
462        self.pending_notifications.remove(&emitter);
463        self.observers
464            .clone()
465            .retain(&emitter, |handler| handler(self));
466    }
467
468    fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
469        self.event_listeners
470            .clone()
471            .retain(&emitter, |handler| handler(event.as_ref(), self));
472    }
473
474    fn apply_focus_changed_effect(
475        &mut self,
476        window_handle: AnyWindowHandle,
477        focused: Option<FocusId>,
478    ) {
479        window_handle
480            .update(self, |_, cx| {
481                if cx.window.focus == focused {
482                    let mut listeners = mem::take(&mut cx.window.focus_listeners);
483                    let focused = focused
484                        .map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
485                    let blurred = cx
486                        .window
487                        .last_blur
488                        .take()
489                        .unwrap()
490                        .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
491                    if focused.is_some() || blurred.is_some() {
492                        let event = FocusEvent { focused, blurred };
493                        for listener in &listeners {
494                            listener(&event, cx);
495                        }
496                    }
497
498                    listeners.extend(cx.window.focus_listeners.drain(..));
499                    cx.window.focus_listeners = listeners;
500                }
501            })
502            .ok();
503    }
504
505    fn apply_refresh_effect(&mut self) {
506        for window in self.windows.values_mut() {
507            if let Some(window) = window.as_mut() {
508                window.dirty = true;
509            }
510        }
511    }
512
513    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
514        self.pending_global_notifications.remove(&type_id);
515        self.global_observers
516            .clone()
517            .retain(&type_id, |observer| observer(self));
518    }
519
520    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
521        callback(self);
522    }
523
524    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
525    /// so it can be held across `await` points.
526    pub fn to_async(&self) -> AsyncAppContext {
527        AsyncAppContext {
528            app: unsafe { mem::transmute(self.this.clone()) },
529            background_executor: self.background_executor.clone(),
530            foreground_executor: self.foreground_executor.clone(),
531        }
532    }
533
534    /// Obtains a reference to the executor, which can be used to spawn futures.
535    pub fn background_executor(&self) -> &BackgroundExecutor {
536        &self.background_executor
537    }
538
539    /// Obtains a reference to the executor, which can be used to spawn futures.
540    pub fn foreground_executor(&self) -> &ForegroundExecutor {
541        &self.foreground_executor
542    }
543
544    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
545    /// with AsyncAppContext, which allows the application state to be accessed across await points.
546    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
547    where
548        Fut: Future<Output = R> + 'static,
549        R: 'static,
550    {
551        self.foreground_executor.spawn(f(self.to_async()))
552    }
553
554    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
555    /// that are currently on the stack to be returned to the app.
556    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
557        self.push_effect(Effect::Defer {
558            callback: Box::new(f),
559        });
560    }
561
562    /// Accessor for the application's asset source, which is provided when constructing the `App`.
563    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
564        &self.asset_source
565    }
566
567    /// Accessor for the text system.
568    pub fn text_system(&self) -> &Arc<TextSystem> {
569        &self.text_system
570    }
571
572    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
573    pub fn text_style(&self) -> TextStyle {
574        let mut style = TextStyle::default();
575        for refinement in &self.text_style_stack {
576            style.refine(refinement);
577        }
578        style
579    }
580
581    /// Check whether a global of the given type has been assigned.
582    pub fn has_global<G: 'static>(&self) -> bool {
583        self.globals_by_type.contains_key(&TypeId::of::<G>())
584    }
585
586    /// Access the global of the given type. Panics if a global for that type has not been assigned.
587    pub fn global<G: 'static>(&self) -> &G {
588        self.globals_by_type
589            .get(&TypeId::of::<G>())
590            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
591            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
592            .unwrap()
593    }
594
595    /// Access the global of the given type if a value has been assigned.
596    pub fn try_global<G: 'static>(&self) -> Option<&G> {
597        self.globals_by_type
598            .get(&TypeId::of::<G>())
599            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
600    }
601
602    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
603    pub fn global_mut<G: 'static>(&mut self) -> &mut G {
604        let global_type = TypeId::of::<G>();
605        self.push_effect(Effect::NotifyGlobalObservers { global_type });
606        self.globals_by_type
607            .get_mut(&global_type)
608            .and_then(|any_state| any_state.downcast_mut::<G>())
609            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
610            .unwrap()
611    }
612
613    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
614    /// yet been assigned.
615    pub fn default_global<G: 'static + Default>(&mut self) -> &mut G {
616        let global_type = TypeId::of::<G>();
617        self.push_effect(Effect::NotifyGlobalObservers { global_type });
618        self.globals_by_type
619            .entry(global_type)
620            .or_insert_with(|| Box::new(G::default()))
621            .downcast_mut::<G>()
622            .unwrap()
623    }
624
625    /// Set the value of the global of the given type.
626    pub fn set_global<G: Any>(&mut self, global: G) {
627        let global_type = TypeId::of::<G>();
628        self.push_effect(Effect::NotifyGlobalObservers { global_type });
629        self.globals_by_type.insert(global_type, Box::new(global));
630    }
631
632    /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
633    /// your closure with mutable access to the `AppContext` and the global simultaneously.
634    pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
635        let mut global = self.lease_global::<G>();
636        let result = f(&mut global, self);
637        self.end_global_lease(global);
638        result
639    }
640
641    /// Register a callback to be invoked when a global of the given type is updated.
642    pub fn observe_global<G: 'static>(
643        &mut self,
644        mut f: impl FnMut(&mut Self) + 'static,
645    ) -> Subscription {
646        self.global_observers.insert(
647            TypeId::of::<G>(),
648            Box::new(move |cx| {
649                f(cx);
650                true
651            }),
652        )
653    }
654
655    pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = SharedString> + 'a {
656        self.action_builders.keys().cloned()
657    }
658
659    /// Move the global of the given type to the stack.
660    pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
661        GlobalLease::new(
662            self.globals_by_type
663                .remove(&TypeId::of::<G>())
664                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
665                .unwrap(),
666        )
667    }
668
669    /// Restore the global of the given type after it is moved to the stack.
670    pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
671        let global_type = TypeId::of::<G>();
672        self.push_effect(Effect::NotifyGlobalObservers { global_type });
673        self.globals_by_type.insert(global_type, lease.global);
674    }
675
676    pub fn observe_release<E, T>(
677        &mut self,
678        handle: &E,
679        on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
680    ) -> Subscription
681    where
682        E: Entity<T>,
683        T: 'static,
684    {
685        self.release_listeners.insert(
686            handle.entity_id(),
687            Box::new(move |entity, cx| {
688                let entity = entity.downcast_mut().expect("invalid entity type");
689                on_release(entity, cx)
690            }),
691        )
692    }
693
694    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
695        self.text_style_stack.push(text_style);
696    }
697
698    pub(crate) fn pop_text_style(&mut self) {
699        self.text_style_stack.pop();
700    }
701
702    /// Register key bindings.
703    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
704        self.keymap.lock().add_bindings(bindings);
705        self.pending_effects.push_back(Effect::Refresh);
706    }
707
708    /// Register a global listener for actions invoked via the keyboard.
709    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
710        self.global_action_listeners
711            .entry(TypeId::of::<A>())
712            .or_default()
713            .push(Box::new(move |action, phase, cx| {
714                if phase == DispatchPhase::Bubble {
715                    let action = action.as_any().downcast_ref().unwrap();
716                    listener(action, cx)
717                }
718            }));
719    }
720
721    /// Register an action type to allow it to be referenced in keymaps.
722    pub fn register_action_type<A: Action>(&mut self) {
723        self.action_builders.insert(A::qualified_name(), A::build);
724    }
725
726    /// Construct an action based on its name and parameters.
727    pub fn build_action(
728        &mut self,
729        name: &str,
730        params: Option<serde_json::Value>,
731    ) -> Result<Box<dyn Action>> {
732        let build = self
733            .action_builders
734            .get(name)
735            .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
736        (build)(params)
737    }
738
739    /// Halt propagation of a mouse event, keyboard event, or action. This prevents listeners
740    /// that have not yet been invoked from receiving the event.
741    pub fn stop_propagation(&mut self) {
742        self.propagate_event = false;
743    }
744}
745
746impl Context for AppContext {
747    type Result<T> = T;
748
749    /// Build an entity that is owned by the application. The given function will be invoked with
750    /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
751    /// which can be used to access the entity in a context.
752    fn build_model<T: 'static>(
753        &mut self,
754        build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
755    ) -> Model<T> {
756        self.update(|cx| {
757            let slot = cx.entities.reserve();
758            let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
759            cx.entities.insert(slot, entity)
760        })
761    }
762
763    /// Update the entity referenced by the given model. The function is passed a mutable reference to the
764    /// entity along with a `ModelContext` for the entity.
765    fn update_model<T: 'static, R>(
766        &mut self,
767        model: &Model<T>,
768        update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
769    ) -> R {
770        self.update(|cx| {
771            let mut entity = cx.entities.lease(model);
772            let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
773            cx.entities.end_lease(entity);
774            result
775        })
776    }
777
778    fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
779    where
780        F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
781    {
782        self.update(|cx| {
783            let mut window = cx
784                .windows
785                .get_mut(handle.id)
786                .ok_or_else(|| anyhow!("window not found"))?
787                .take()
788                .unwrap();
789
790            let root_view = window.root_view.clone().unwrap();
791            let result = update(root_view, &mut WindowContext::new(cx, &mut window));
792            cx.windows
793                .get_mut(handle.id)
794                .ok_or_else(|| anyhow!("window not found"))?
795                .replace(window);
796
797            Ok(result)
798        })
799    }
800}
801
802/// These effects are processed at the end of each application update cycle.
803pub(crate) enum Effect {
804    Notify {
805        emitter: EntityId,
806    },
807    Emit {
808        emitter: EntityId,
809        event: Box<dyn Any>,
810    },
811    FocusChanged {
812        window_handle: AnyWindowHandle,
813        focused: Option<FocusId>,
814    },
815    Refresh,
816    NotifyGlobalObservers {
817        global_type: TypeId,
818    },
819    Defer {
820        callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
821    },
822}
823
824/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
825pub(crate) struct GlobalLease<G: 'static> {
826    global: AnyBox,
827    global_type: PhantomData<G>,
828}
829
830impl<G: 'static> GlobalLease<G> {
831    fn new(global: AnyBox) -> Self {
832        GlobalLease {
833            global,
834            global_type: PhantomData,
835        }
836    }
837}
838
839impl<G: 'static> Deref for GlobalLease<G> {
840    type Target = G;
841
842    fn deref(&self) -> &Self::Target {
843        self.global.downcast_ref().unwrap()
844    }
845}
846
847impl<G: 'static> DerefMut for GlobalLease<G> {
848    fn deref_mut(&mut self) -> &mut Self::Target {
849        self.global.downcast_mut().unwrap()
850    }
851}
852
853/// Contains state associated with an active drag operation, started by dragging an element
854/// within the window or by dragging into the app from the underlying platform.
855pub(crate) struct AnyDrag {
856    pub view: AnyView,
857    pub cursor_offset: Point<Pixels>,
858}