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