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 // The window might change focus multiple times in an effect cycle.
621 // We only honor effects for the most recently focused handle.
622 if cx.window.focus == focused {
623 let focused = focused
624 .map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
625 let blurred = cx
626 .window
627 .last_blur
628 .take()
629 .unwrap()
630 .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
631 let focus_changed = focused.is_some() || blurred.is_some();
632 let event = FocusEvent { focused, blurred };
633
634 let mut listeners = mem::take(&mut cx.window.current_frame.focus_listeners);
635 if focus_changed {
636 for listener in &mut listeners {
637 listener(&event, cx);
638 }
639 }
640 listeners.extend(cx.window.current_frame.focus_listeners.drain(..));
641 cx.window.current_frame.focus_listeners = listeners;
642
643 if focus_changed {
644 cx.window
645 .focus_listeners
646 .clone()
647 .retain(&(), |listener| listener(&event, cx));
648 }
649 }
650 })
651 .ok();
652 }
653
654 fn apply_refresh_effect(&mut self) {
655 for window in self.windows.values_mut() {
656 if let Some(window) = window.as_mut() {
657 window.dirty = true;
658 }
659 }
660 }
661
662 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
663 self.pending_global_notifications.remove(&type_id);
664 self.global_observers
665 .clone()
666 .retain(&type_id, |observer| observer(self));
667 }
668
669 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
670 callback(self);
671 }
672
673 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
674 /// so it can be held across `await` points.
675 pub fn to_async(&self) -> AsyncAppContext {
676 AsyncAppContext {
677 app: unsafe { mem::transmute(self.this.clone()) },
678 background_executor: self.background_executor.clone(),
679 foreground_executor: self.foreground_executor.clone(),
680 }
681 }
682
683 /// Obtains a reference to the executor, which can be used to spawn futures.
684 pub fn background_executor(&self) -> &BackgroundExecutor {
685 &self.background_executor
686 }
687
688 /// Obtains a reference to the executor, which can be used to spawn futures.
689 pub fn foreground_executor(&self) -> &ForegroundExecutor {
690 &self.foreground_executor
691 }
692
693 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
694 /// with AsyncAppContext, which allows the application state to be accessed across await points.
695 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
696 where
697 Fut: Future<Output = R> + 'static,
698 R: 'static,
699 {
700 self.foreground_executor.spawn(f(self.to_async()))
701 }
702
703 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
704 /// that are currently on the stack to be returned to the app.
705 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
706 self.push_effect(Effect::Defer {
707 callback: Box::new(f),
708 });
709 }
710
711 /// Accessor for the application's asset source, which is provided when constructing the `App`.
712 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
713 &self.asset_source
714 }
715
716 /// Accessor for the text system.
717 pub fn text_system(&self) -> &Arc<TextSystem> {
718 &self.text_system
719 }
720
721 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
722 pub fn text_style(&self) -> TextStyle {
723 let mut style = TextStyle::default();
724 for refinement in &self.text_style_stack {
725 style.refine(refinement);
726 }
727 style
728 }
729
730 /// Check whether a global of the given type has been assigned.
731 pub fn has_global<G: 'static>(&self) -> bool {
732 self.globals_by_type.contains_key(&TypeId::of::<G>())
733 }
734
735 /// Access the global of the given type. Panics if a global for that type has not been assigned.
736 #[track_caller]
737 pub fn global<G: 'static>(&self) -> &G {
738 self.globals_by_type
739 .get(&TypeId::of::<G>())
740 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
741 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
742 .unwrap()
743 }
744
745 /// Access the global of the given type if a value has been assigned.
746 pub fn try_global<G: 'static>(&self) -> Option<&G> {
747 self.globals_by_type
748 .get(&TypeId::of::<G>())
749 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
750 }
751
752 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
753 #[track_caller]
754 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
755 let global_type = TypeId::of::<G>();
756 self.push_effect(Effect::NotifyGlobalObservers { global_type });
757 self.globals_by_type
758 .get_mut(&global_type)
759 .and_then(|any_state| any_state.downcast_mut::<G>())
760 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
761 .unwrap()
762 }
763
764 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
765 /// yet been assigned.
766 pub fn default_global<G: 'static + Default>(&mut self) -> &mut G {
767 let global_type = TypeId::of::<G>();
768 self.push_effect(Effect::NotifyGlobalObservers { global_type });
769 self.globals_by_type
770 .entry(global_type)
771 .or_insert_with(|| Box::new(G::default()))
772 .downcast_mut::<G>()
773 .unwrap()
774 }
775
776 /// Set the value of the global of the given type.
777 pub fn set_global<G: Any>(&mut self, global: G) {
778 let global_type = TypeId::of::<G>();
779 self.push_effect(Effect::NotifyGlobalObservers { global_type });
780 self.globals_by_type.insert(global_type, Box::new(global));
781 }
782
783 /// Clear all stored globals. Does not notify global observers.
784 #[cfg(any(test, feature = "test-support"))]
785 pub fn clear_globals(&mut self) {
786 self.globals_by_type.drain();
787 }
788
789 /// Remove the global of the given type from the app context. Does not notify global observers.
790 #[cfg(any(test, feature = "test-support"))]
791 pub fn remove_global<G: Any>(&mut self) -> G {
792 let global_type = TypeId::of::<G>();
793 *self
794 .globals_by_type
795 .remove(&global_type)
796 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
797 .downcast()
798 .unwrap()
799 }
800
801 /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
802 /// your closure with mutable access to the `AppContext` and the global simultaneously.
803 pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
804 let mut global = self.lease_global::<G>();
805 let result = f(&mut global, self);
806 self.end_global_lease(global);
807 result
808 }
809
810 /// Register a callback to be invoked when a global of the given type is updated.
811 pub fn observe_global<G: 'static>(
812 &mut self,
813 mut f: impl FnMut(&mut Self) + 'static,
814 ) -> Subscription {
815 self.global_observers.insert(
816 TypeId::of::<G>(),
817 Box::new(move |cx| {
818 f(cx);
819 true
820 }),
821 )
822 }
823
824 /// Move the global of the given type to the stack.
825 pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
826 GlobalLease::new(
827 self.globals_by_type
828 .remove(&TypeId::of::<G>())
829 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
830 .unwrap(),
831 )
832 }
833
834 /// Restore the global of the given type after it is moved to the stack.
835 pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
836 let global_type = TypeId::of::<G>();
837 self.push_effect(Effect::NotifyGlobalObservers { global_type });
838 self.globals_by_type.insert(global_type, lease.global);
839 }
840
841 pub fn observe_release<E, T>(
842 &mut self,
843 handle: &E,
844 on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
845 ) -> Subscription
846 where
847 E: Entity<T>,
848 T: 'static,
849 {
850 self.release_listeners.insert(
851 handle.entity_id(),
852 Box::new(move |entity, cx| {
853 let entity = entity.downcast_mut().expect("invalid entity type");
854 on_release(entity, cx)
855 }),
856 )
857 }
858
859 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
860 self.text_style_stack.push(text_style);
861 }
862
863 pub(crate) fn pop_text_style(&mut self) {
864 self.text_style_stack.pop();
865 }
866
867 /// Register key bindings.
868 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
869 self.keymap.lock().add_bindings(bindings);
870 self.pending_effects.push_back(Effect::Refresh);
871 }
872
873 /// Register a global listener for actions invoked via the keyboard.
874 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
875 self.global_action_listeners
876 .entry(TypeId::of::<A>())
877 .or_default()
878 .push(Box::new(move |action, phase, cx| {
879 if phase == DispatchPhase::Bubble {
880 let action = action.as_any().downcast_ref().unwrap();
881 listener(action, cx)
882 }
883 }));
884 }
885
886 /// Event handlers propagate events by default. Call this method to stop dispatching to
887 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
888 /// the opposite of [propagate]. It's also possible to cancel a call to [propagate] by
889 /// calling this method before effects are flushed.
890 pub fn stop_propagation(&mut self) {
891 self.propagate_event = false;
892 }
893
894 /// Action handlers stop propagation by default during the bubble phase of action dispatch
895 /// dispatching to action handlers higher in the element tree. This is the opposite of
896 /// [stop_propagation]. It's also possible to cancel a call to [stop_propagate] by calling
897 /// this method before effects are flushed.
898 pub fn propagate(&mut self) {
899 self.propagate_event = true;
900 }
901}
902
903impl Context for AppContext {
904 type Result<T> = T;
905
906 /// Build an entity that is owned by the application. The given function will be invoked with
907 /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
908 /// which can be used to access the entity in a context.
909 fn build_model<T: 'static>(
910 &mut self,
911 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
912 ) -> Model<T> {
913 self.update(|cx| {
914 let slot = cx.entities.reserve();
915 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
916 cx.entities.insert(slot, entity)
917 })
918 }
919
920 /// Update the entity referenced by the given model. The function is passed a mutable reference to the
921 /// entity along with a `ModelContext` for the entity.
922 fn update_model<T: 'static, R>(
923 &mut self,
924 model: &Model<T>,
925 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
926 ) -> R {
927 self.update(|cx| {
928 let mut entity = cx.entities.lease(model);
929 let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
930 cx.entities.end_lease(entity);
931 result
932 })
933 }
934
935 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
936 where
937 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
938 {
939 self.update(|cx| {
940 let mut window = cx
941 .windows
942 .get_mut(handle.id)
943 .ok_or_else(|| anyhow!("window not found"))?
944 .take()
945 .unwrap();
946
947 let root_view = window.root_view.clone().unwrap();
948 let result = update(root_view, &mut WindowContext::new(cx, &mut window));
949
950 if !window.removed {
951 cx.windows
952 .get_mut(handle.id)
953 .ok_or_else(|| anyhow!("window not found"))?
954 .replace(window);
955 }
956
957 Ok(result)
958 })
959 }
960
961 fn read_model<T, R>(
962 &self,
963 handle: &Model<T>,
964 read: impl FnOnce(&T, &AppContext) -> R,
965 ) -> Self::Result<R>
966 where
967 T: 'static,
968 {
969 let entity = self.entities.read(handle);
970 read(entity, self)
971 }
972}
973
974/// These effects are processed at the end of each application update cycle.
975pub(crate) enum Effect {
976 Notify {
977 emitter: EntityId,
978 },
979 Emit {
980 emitter: EntityId,
981 event: Box<dyn Any>,
982 },
983 FocusChanged {
984 window_handle: AnyWindowHandle,
985 focused: Option<FocusId>,
986 },
987 Refresh,
988 NotifyGlobalObservers {
989 global_type: TypeId,
990 },
991 Defer {
992 callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
993 },
994}
995
996/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
997pub(crate) struct GlobalLease<G: 'static> {
998 global: AnyBox,
999 global_type: PhantomData<G>,
1000}
1001
1002impl<G: 'static> GlobalLease<G> {
1003 fn new(global: AnyBox) -> Self {
1004 GlobalLease {
1005 global,
1006 global_type: PhantomData,
1007 }
1008 }
1009}
1010
1011impl<G: 'static> Deref for GlobalLease<G> {
1012 type Target = G;
1013
1014 fn deref(&self) -> &Self::Target {
1015 self.global.downcast_ref().unwrap()
1016 }
1017}
1018
1019impl<G: 'static> DerefMut for GlobalLease<G> {
1020 fn deref_mut(&mut self) -> &mut Self::Target {
1021 self.global.downcast_mut().unwrap()
1022 }
1023}
1024
1025/// Contains state associated with an active drag operation, started by dragging an element
1026/// within the window or by dragging into the app from the underlying platform.
1027pub(crate) struct AnyDrag {
1028 pub view: AnyView,
1029 pub cursor_offset: Point<Pixels>,
1030}
1031
1032#[derive(Clone)]
1033pub(crate) struct AnyTooltip {
1034 pub view: AnyView,
1035 pub cursor_offset: Point<Pixels>,
1036}