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