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