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