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