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