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