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