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