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, Window, WindowContext, WindowHandle,
 21    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(crate) fn push_effect(&mut self, effect: Effect) {
307        match &effect {
308            Effect::Notify { emitter } => {
309                if !self.pending_notifications.insert(*emitter) {
310                    return;
311                }
312            }
313            Effect::NotifyGlobalObservers { global_type } => {
314                if !self.pending_global_notifications.insert(*global_type) {
315                    return;
316                }
317            }
318            _ => {}
319        };
320
321        self.pending_effects.push_back(effect);
322    }
323
324    /// Called at the end of AppContext::update to complete any side effects
325    /// such as notifying observers, emitting events, etc. Effects can themselves
326    /// cause effects, so we continue looping until all effects are processed.
327    fn flush_effects(&mut self) {
328        loop {
329            self.release_dropped_entities();
330            self.release_dropped_focus_handles();
331            if let Some(effect) = self.pending_effects.pop_front() {
332                match effect {
333                    Effect::Notify { emitter } => {
334                        self.apply_notify_effect(emitter);
335                    }
336                    Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
337                    Effect::FocusChanged {
338                        window_handle,
339                        focused,
340                    } => {
341                        self.apply_focus_changed_effect(window_handle, focused);
342                    }
343                    Effect::Refresh => {
344                        self.apply_refresh_effect();
345                    }
346                    Effect::NotifyGlobalObservers { global_type } => {
347                        self.apply_notify_global_observers_effect(global_type);
348                    }
349                    Effect::Defer { callback } => {
350                        self.apply_defer_effect(callback);
351                    }
352                }
353            } else {
354                break;
355            }
356        }
357
358        let dirty_window_ids = self
359            .windows
360            .iter()
361            .filter_map(|(_, window)| {
362                let window = window.as_ref().unwrap();
363                if window.dirty {
364                    Some(window.handle.clone())
365                } else {
366                    None
367                }
368            })
369            .collect::<SmallVec<[_; 8]>>();
370
371        for dirty_window_handle in dirty_window_ids {
372            self.update_window(dirty_window_handle, |cx| cx.draw())
373                .unwrap();
374        }
375    }
376
377    /// Repeatedly called during `flush_effects` to release any entities whose
378    /// reference count has become zero. We invoke any release observers before dropping
379    /// each entity.
380    fn release_dropped_entities(&mut self) {
381        loop {
382            let dropped = self.entities.take_dropped();
383            if dropped.is_empty() {
384                break;
385            }
386
387            for (entity_id, mut entity) in dropped {
388                self.observers.remove(&entity_id);
389                self.event_listeners.remove(&entity_id);
390                for mut release_callback in self.release_listeners.remove(&entity_id) {
391                    release_callback(&mut entity, self);
392                }
393            }
394        }
395    }
396
397    /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
398    /// For now, we simply blur the window if this happens, but we may want to support invoking
399    /// a window blur handler to restore focus to some logical element.
400    fn release_dropped_focus_handles(&mut self) {
401        for window_handle in self.windows() {
402            self.update_window(window_handle, |cx| {
403                let mut blur_window = false;
404                let focus = cx.window.focus;
405                cx.window.focus_handles.write().retain(|handle_id, count| {
406                    if count.load(SeqCst) == 0 {
407                        if focus == Some(handle_id) {
408                            blur_window = true;
409                        }
410                        false
411                    } else {
412                        true
413                    }
414                });
415
416                if blur_window {
417                    cx.blur();
418                }
419            })
420            .unwrap();
421        }
422    }
423
424    fn apply_notify_effect(&mut self, emitter: EntityId) {
425        self.pending_notifications.remove(&emitter);
426        self.observers
427            .clone()
428            .retain(&emitter, |handler| handler(self));
429    }
430
431    fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
432        self.event_listeners
433            .clone()
434            .retain(&emitter, |handler| handler(event.as_ref(), self));
435    }
436
437    fn apply_focus_changed_effect(
438        &mut self,
439        window_handle: AnyWindowHandle,
440        focused: Option<FocusId>,
441    ) {
442        self.update_window(window_handle, |cx| {
443            if cx.window.focus == focused {
444                let mut listeners = mem::take(&mut cx.window.focus_listeners);
445                let focused =
446                    focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
447                let blurred = cx
448                    .window
449                    .last_blur
450                    .take()
451                    .unwrap()
452                    .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
453                if focused.is_some() || blurred.is_some() {
454                    let event = FocusEvent { focused, blurred };
455                    for listener in &listeners {
456                        listener(&event, cx);
457                    }
458                }
459
460                listeners.extend(cx.window.focus_listeners.drain(..));
461                cx.window.focus_listeners = listeners;
462            }
463        })
464        .ok();
465    }
466
467    fn apply_refresh_effect(&mut self) {
468        for window in self.windows.values_mut() {
469            if let Some(window) = window.as_mut() {
470                window.dirty = true;
471            }
472        }
473    }
474
475    fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
476        self.pending_global_notifications.remove(&type_id);
477        self.global_observers
478            .clone()
479            .retain(&type_id, |observer| observer(self));
480    }
481
482    fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + 'static>) {
483        callback(self);
484    }
485
486    /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
487    /// so it can be held across `await` points.
488    pub fn to_async(&self) -> AsyncAppContext {
489        AsyncAppContext {
490            app: unsafe { mem::transmute(self.this.clone()) },
491            executor: self.executor.clone(),
492        }
493    }
494
495    /// Obtains a reference to the executor, which can be used to spawn futures.
496    pub fn executor(&self) -> &Executor {
497        &self.executor
498    }
499
500    /// Runs the given closure on the main thread, where interaction with the platform
501    /// is possible. The given closure will be invoked with a `MainThread<AppContext>`, which
502    /// has platform-specific methods that aren't present on `AppContext`.
503    pub fn run_on_main<R>(
504        &mut self,
505        f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
506    ) -> Task<R>
507    where
508        R: Send + 'static,
509    {
510        if self.executor.is_main_thread() {
511            Task::ready(f(unsafe {
512                mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
513            }))
514        } else {
515            let this = self.this.upgrade().unwrap();
516            self.executor.run_on_main(move || {
517                let cx = &mut *this.lock();
518                cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
519            })
520        }
521    }
522
523    /// Spawns the future returned by the given function on the main thread, where interaction with
524    /// the platform is possible. The given closure will be invoked with a `MainThread<AsyncAppContext>`,
525    /// which has platform-specific methods that aren't present on `AsyncAppContext`. The future will be
526    /// polled exclusively on the main thread.
527    // todo!("I think we need somehow to prevent the MainThread<AsyncAppContext> from implementing Send")
528    pub fn spawn_on_main<F, R>(
529        &self,
530        f: impl FnOnce(MainThread<AsyncAppContext>) -> F + Send + 'static,
531    ) -> Task<R>
532    where
533        F: Future<Output = R> + 'static,
534        R: Send + 'static,
535    {
536        let cx = self.to_async();
537        self.executor.spawn_on_main(move || f(MainThread(cx)))
538    }
539
540    /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
541    /// with AsyncAppContext, which allows the application state to be accessed across await points.
542    pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
543    where
544        Fut: Future<Output = R> + Send + 'static,
545        R: Send + 'static,
546    {
547        let cx = self.to_async();
548        self.executor.spawn(async move {
549            let future = f(cx);
550            future.await
551        })
552    }
553
554    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
555    /// that are currently on the stack to be returned to the app.
556    pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send) {
557        self.push_effect(Effect::Defer {
558            callback: Box::new(f),
559        });
560    }
561
562    /// Accessor for the application's asset source, which is provided when constructing the `App`.
563    pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
564        &self.asset_source
565    }
566
567    /// Accessor for the text system.
568    pub fn text_system(&self) -> &Arc<TextSystem> {
569        &self.text_system
570    }
571
572    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
573    pub fn text_style(&self) -> TextStyle {
574        let mut style = TextStyle::default();
575        for refinement in &self.text_style_stack {
576            style.refine(refinement);
577        }
578        style
579    }
580
581    /// Check whether a global of the given type has been assigned.
582    pub fn has_global<G: 'static>(&self) -> bool {
583        self.globals_by_type.contains_key(&TypeId::of::<G>())
584    }
585
586    /// Access the global of the given type. Panics if a global for that type has not been assigned.
587    pub fn global<G: 'static>(&self) -> &G {
588        self.globals_by_type
589            .get(&TypeId::of::<G>())
590            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
591            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
592            .unwrap()
593    }
594
595    /// Access the global of the given type if a value has been assigned.
596    pub fn try_global<G: 'static>(&self) -> Option<&G> {
597        self.globals_by_type
598            .get(&TypeId::of::<G>())
599            .map(|any_state| any_state.downcast_ref::<G>().unwrap())
600    }
601
602    /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
603    pub fn global_mut<G: 'static>(&mut self) -> &mut G {
604        let global_type = TypeId::of::<G>();
605        self.push_effect(Effect::NotifyGlobalObservers { global_type });
606        self.globals_by_type
607            .get_mut(&global_type)
608            .and_then(|any_state| any_state.downcast_mut::<G>())
609            .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
610            .unwrap()
611    }
612
613    /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
614    /// yet been assigned.
615    pub fn default_global<G: 'static + Default + Send>(&mut self) -> &mut G {
616        let global_type = TypeId::of::<G>();
617        self.push_effect(Effect::NotifyGlobalObservers { global_type });
618        self.globals_by_type
619            .entry(global_type)
620            .or_insert_with(|| Box::new(G::default()))
621            .downcast_mut::<G>()
622            .unwrap()
623    }
624
625    /// Set the value of the global of the given type.
626    pub fn set_global<G: Any + Send>(&mut self, global: G) {
627        let global_type = TypeId::of::<G>();
628        self.push_effect(Effect::NotifyGlobalObservers { global_type });
629        self.globals_by_type.insert(global_type, Box::new(global));
630    }
631
632    /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
633    /// your closure with mutable access to the `AppContext` and the global simultaneously.
634    pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
635        let mut global = self.lease_global::<G>();
636        let result = f(&mut global, self);
637        self.end_global_lease(global);
638        result
639    }
640
641    /// Register a callback to be invoked when a global of the given type is updated.
642    pub fn observe_global<G: 'static>(
643        &mut self,
644        mut f: impl FnMut(&mut Self) + Send + 'static,
645    ) -> Subscription {
646        self.global_observers.insert(
647            TypeId::of::<G>(),
648            Box::new(move |cx| {
649                f(cx);
650                true
651            }),
652        )
653    }
654
655    /// Move the global of the given type to the stack.
656    pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
657        GlobalLease::new(
658            self.globals_by_type
659                .remove(&TypeId::of::<G>())
660                .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
661                .unwrap(),
662        )
663    }
664
665    /// Restore the global of the given type after it is moved to the stack.
666    pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
667        let global_type = TypeId::of::<G>();
668        self.push_effect(Effect::NotifyGlobalObservers { global_type });
669        self.globals_by_type.insert(global_type, lease.global);
670    }
671
672    pub fn observe_release<E: 'static>(
673        &mut self,
674        handle: &Handle<E>,
675        mut on_release: impl FnMut(&mut E, &mut AppContext) + Send + 'static,
676    ) -> Subscription {
677        self.release_listeners.insert(
678            handle.entity_id,
679            Box::new(move |entity, cx| {
680                let entity = entity.downcast_mut().expect("invalid entity type");
681                on_release(entity, cx)
682            }),
683        )
684    }
685
686    pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
687        self.text_style_stack.push(text_style);
688    }
689
690    pub(crate) fn pop_text_style(&mut self) {
691        self.text_style_stack.pop();
692    }
693
694    /// Register key bindings.
695    pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
696        self.keymap.lock().add_bindings(bindings);
697        self.pending_effects.push_back(Effect::Refresh);
698    }
699
700    /// Register a global listener for actions invoked via the keyboard.
701    pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + Send + 'static) {
702        self.global_action_listeners
703            .entry(TypeId::of::<A>())
704            .or_default()
705            .push(Box::new(move |action, phase, cx| {
706                if phase == DispatchPhase::Bubble {
707                    let action = action.as_any().downcast_ref().unwrap();
708                    listener(action, cx)
709                }
710            }));
711    }
712
713    /// Register an action type to allow it to be referenced in keymaps.
714    pub fn register_action_type<A: Action>(&mut self) {
715        self.action_builders.insert(A::qualified_name(), A::build);
716    }
717
718    /// Construct an action based on its name and parameters.
719    pub fn build_action(
720        &mut self,
721        name: &str,
722        params: Option<serde_json::Value>,
723    ) -> Result<Box<dyn Action>> {
724        let build = self
725            .action_builders
726            .get(name)
727            .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
728        (build)(params)
729    }
730
731    /// Halt propagation of a mouse event, keyboard event, or action. This prevents listeners
732    /// that have not yet been invoked from receiving the event.
733    pub fn stop_propagation(&mut self) {
734        self.propagate_event = false;
735    }
736}
737
738impl Context for AppContext {
739    type EntityContext<'a, T> = ModelContext<'a, T>;
740    type Result<T> = T;
741
742    /// Build an entity that is owned by the application. The given function will be invoked with
743    /// a `ModelContext` and must return an object representing the entity. A `Handle` will be returned
744    /// which can be used to access the entity in a context.
745    fn entity<T: 'static + Send>(
746        &mut self,
747        build_entity: impl FnOnce(&mut Self::EntityContext<'_, T>) -> T,
748    ) -> Handle<T> {
749        self.update(|cx| {
750            let slot = cx.entities.reserve();
751            let entity = build_entity(&mut ModelContext::mutable(cx, slot.downgrade()));
752            cx.entities.insert(slot, entity)
753        })
754    }
755
756    /// Update the entity referenced by the given handle. The function is passed a mutable reference to the
757    /// entity along with a `ModelContext` for the entity.
758    fn update_entity<T: 'static, R>(
759        &mut self,
760        handle: &Handle<T>,
761        update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, T>) -> R,
762    ) -> R {
763        self.update(|cx| {
764            let mut entity = cx.entities.lease(handle);
765            let result = update(
766                &mut entity,
767                &mut ModelContext::mutable(cx, handle.downgrade()),
768            );
769            cx.entities.end_lease(entity);
770            result
771        })
772    }
773}
774
775impl<C> MainThread<C>
776where
777    C: Borrow<AppContext>,
778{
779    pub(crate) fn platform(&self) -> &dyn Platform {
780        self.0.borrow().platform.borrow_on_main_thread()
781    }
782
783    /// Instructs the platform to activate the application by bringing it to the foreground.
784    pub fn activate(&self, ignoring_other_apps: bool) {
785        self.platform().activate(ignoring_other_apps);
786    }
787
788    /// Writes data to the platform clipboard.
789    pub fn write_to_clipboard(&self, item: ClipboardItem) {
790        self.platform().write_to_clipboard(item)
791    }
792
793    /// Reads data from the platform clipboard.
794    pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
795        self.platform().read_from_clipboard()
796    }
797
798    /// Writes credentials to the platform keychain.
799    pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
800        self.platform().write_credentials(url, username, password)
801    }
802
803    /// Reads credentials from the platform keychain.
804    pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
805        self.platform().read_credentials(url)
806    }
807
808    /// Deletes credentials from the platform keychain.
809    pub fn delete_credentials(&self, url: &str) -> Result<()> {
810        self.platform().delete_credentials(url)
811    }
812
813    /// Directs the platform's default browser to open the given URL.
814    pub fn open_url(&self, url: &str) {
815        self.platform().open_url(url);
816    }
817
818    pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
819        self.platform().path_for_auxiliary_executable(name)
820    }
821}
822
823impl MainThread<AppContext> {
824    fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
825        self.0.update(|cx| {
826            update(unsafe {
827                std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
828            })
829        })
830    }
831
832    pub fn update_window<R>(
833        &mut self,
834        handle: AnyWindowHandle,
835        update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
836    ) -> Result<R> {
837        self.0.update_window(handle, |cx| {
838            update(unsafe {
839                std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
840            })
841        })
842    }
843
844    /// Opens a new window with the given option and the root view returned by the given function.
845    /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
846    /// functionality.
847    pub fn open_window<V: 'static>(
848        &mut self,
849        options: crate::WindowOptions,
850        build_root_view: impl FnOnce(&mut WindowContext) -> View<V> + Send + 'static,
851    ) -> WindowHandle<V> {
852        self.update(|cx| {
853            let id = cx.windows.insert(None);
854            let handle = WindowHandle::new(id);
855            let mut window = Window::new(handle.into(), options, cx);
856            let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
857            window.root_view.replace(root_view.into_any());
858            cx.windows.get_mut(id).unwrap().replace(window);
859            handle
860        })
861    }
862
863    /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
864    /// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.
865    pub fn update_global<G: 'static + Send, R>(
866        &mut self,
867        update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
868    ) -> R {
869        self.0.update_global(|global, cx| {
870            let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
871            update(global, cx)
872        })
873    }
874}
875
876/// These effects are processed at the end of each application update cycle.
877pub(crate) enum Effect {
878    Notify {
879        emitter: EntityId,
880    },
881    Emit {
882        emitter: EntityId,
883        event: Box<dyn Any + Send + 'static>,
884    },
885    FocusChanged {
886        window_handle: AnyWindowHandle,
887        focused: Option<FocusId>,
888    },
889    Refresh,
890    NotifyGlobalObservers {
891        global_type: TypeId,
892    },
893    Defer {
894        callback: Box<dyn FnOnce(&mut AppContext) + Send + 'static>,
895    },
896}
897
898/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
899pub(crate) struct GlobalLease<G: 'static> {
900    global: AnyBox,
901    global_type: PhantomData<G>,
902}
903
904impl<G: 'static> GlobalLease<G> {
905    fn new(global: AnyBox) -> Self {
906        GlobalLease {
907            global,
908            global_type: PhantomData,
909        }
910    }
911}
912
913impl<G: 'static> Deref for GlobalLease<G> {
914    type Target = G;
915
916    fn deref(&self) -> &Self::Target {
917        self.global.downcast_ref().unwrap()
918    }
919}
920
921impl<G: 'static> DerefMut for GlobalLease<G> {
922    fn deref_mut(&mut self) -> &mut Self::Target {
923        self.global.downcast_mut().unwrap()
924    }
925}
926
927/// Contains state associated with an active drag operation, started by dragging an element
928/// within the window or by dragging into the app from the underlying platform.
929pub(crate) struct AnyDrag {
930    pub drag_handle_view: Option<AnyView>,
931    pub cursor_offset: Point<Pixels>,
932    pub state: AnyBox,
933    pub state_type: TypeId,
934}
935
936#[cfg(test)]
937mod tests {
938    use super::AppContext;
939
940    #[test]
941    fn test_app_context_send_sync() {
942        // This will not compile if `AppContext` does not implement `Send`
943        fn assert_send<T: Send>() {}
944        assert_send::<AppContext>();
945    }
946}