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