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