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