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