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 smol::future::FutureExt;
13#[cfg(any(test, feature = "test-support"))]
14pub use test_context::*;
15use time::UtcOffset;
16
17use crate::WindowAppearance;
18use crate::{
19 current_platform, image_cache::ImageCache, init_app_menus, Action, ActionRegistry, Any,
20 AnyView, AnyWindowHandle, AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context,
21 DispatchPhase, DisplayId, Entity, EventEmitter, ForegroundExecutor, Global, KeyBinding, Keymap,
22 Keystroke, LayoutId, Menu, PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render,
23 SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,
24 TextSystem, View, ViewContext, Window, WindowContext, WindowHandle, WindowId,
25};
26use anyhow::{anyhow, Result};
27use collections::{FxHashMap, FxHashSet, VecDeque};
28use futures::{channel::oneshot, future::LocalBoxFuture, Future};
29
30use slotmap::SlotMap;
31use std::{
32 any::{type_name, TypeId},
33 cell::{Ref, RefCell, RefMut},
34 marker::PhantomData,
35 ops::{Deref, DerefMut},
36 path::{Path, PathBuf},
37 rc::{Rc, Weak},
38 sync::{atomic::Ordering::SeqCst, Arc},
39 time::Duration,
40};
41use util::{
42 http::{self, HttpClient},
43 ResultExt,
44};
45
46/// The duration for which futures returned from [AppContext::on_app_context] or [ModelContext::on_app_quit] can run before the application fully quits.
47pub const SHUTDOWN_TIMEOUT: Duration = Duration::from_millis(100);
48
49/// Temporary(?) wrapper around [`RefCell<AppContext>`] to help us debug any double borrows.
50/// Strongly consider removing after stabilization.
51#[doc(hidden)]
52pub struct AppCell {
53 app: RefCell<AppContext>,
54}
55
56impl AppCell {
57 #[doc(hidden)]
58 #[track_caller]
59 pub fn borrow(&self) -> AppRef {
60 if option_env!("TRACK_THREAD_BORROWS").is_some() {
61 let thread_id = std::thread::current().id();
62 eprintln!("borrowed {thread_id:?}");
63 }
64 AppRef(self.app.borrow())
65 }
66
67 #[doc(hidden)]
68 #[track_caller]
69 pub fn borrow_mut(&self) -> AppRefMut {
70 if option_env!("TRACK_THREAD_BORROWS").is_some() {
71 let thread_id = std::thread::current().id();
72 eprintln!("borrowed {thread_id:?}");
73 }
74 AppRefMut(self.app.borrow_mut())
75 }
76}
77
78#[doc(hidden)]
79#[derive(Deref, DerefMut)]
80pub struct AppRef<'a>(Ref<'a, AppContext>);
81
82impl<'a> Drop for AppRef<'a> {
83 fn drop(&mut self) {
84 if option_env!("TRACK_THREAD_BORROWS").is_some() {
85 let thread_id = std::thread::current().id();
86 eprintln!("dropped borrow from {thread_id:?}");
87 }
88 }
89}
90
91#[doc(hidden)]
92#[derive(Deref, DerefMut)]
93pub struct AppRefMut<'a>(RefMut<'a, AppContext>);
94
95impl<'a> Drop for AppRefMut<'a> {
96 fn drop(&mut self) {
97 if option_env!("TRACK_THREAD_BORROWS").is_some() {
98 let thread_id = std::thread::current().id();
99 eprintln!("dropped {thread_id:?}");
100 }
101 }
102}
103
104/// A reference to a GPUI application, typically constructed in the `main` function of your app.
105/// You won't interact with this type much outside of initial configuration and startup.
106pub struct App(Rc<AppCell>);
107
108/// Represents an application before it is fully launched. Once your app is
109/// configured, you'll start the app with `App::run`.
110impl App {
111 /// Builds an app with the given asset source.
112 #[allow(clippy::new_without_default)]
113 pub fn new() -> Self {
114 Self(AppContext::new(
115 current_platform(),
116 Arc::new(()),
117 http::client(),
118 ))
119 }
120
121 /// Assign
122 pub fn with_assets(self, asset_source: impl AssetSource) -> Self {
123 let mut context_lock = self.0.borrow_mut();
124 let asset_source = Arc::new(asset_source);
125 context_lock.asset_source = asset_source.clone();
126 context_lock.svg_renderer = SvgRenderer::new(asset_source);
127 drop(context_lock);
128 self
129 }
130
131 /// Start the application. The provided callback will be called once the
132 /// app is fully launched.
133 pub fn run<F>(self, on_finish_launching: F)
134 where
135 F: 'static + FnOnce(&mut AppContext),
136 {
137 let this = self.0.clone();
138 let platform = self.0.borrow().platform.clone();
139 platform.run(Box::new(move || {
140 let cx = &mut *this.borrow_mut();
141 on_finish_launching(cx);
142 }));
143 }
144
145 /// Register a handler to be invoked when the platform instructs the application
146 /// to open one or more URLs.
147 pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
148 where
149 F: 'static + FnMut(Vec<String>, &mut AppContext),
150 {
151 let this = Rc::downgrade(&self.0);
152 self.0.borrow().platform.on_open_urls(Box::new(move |urls| {
153 if let Some(app) = this.upgrade() {
154 callback(urls, &mut app.borrow_mut());
155 }
156 }));
157 self
158 }
159
160 /// Invokes a handler when an already-running application is launched.
161 /// On macOS, this can occur when the application icon is double-clicked or the app is launched via the dock.
162 pub fn on_reopen<F>(&self, mut callback: F) -> &Self
163 where
164 F: 'static + FnMut(&mut AppContext),
165 {
166 let this = Rc::downgrade(&self.0);
167 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
168 if let Some(app) = this.upgrade() {
169 callback(&mut app.borrow_mut());
170 }
171 }));
172 self
173 }
174
175 /// Returns metadata associated with the application
176 pub fn metadata(&self) -> AppMetadata {
177 self.0.borrow().app_metadata.clone()
178 }
179
180 /// Returns a handle to the [`BackgroundExecutor`] associated with this app, which can be used to spawn futures in the background.
181 pub fn background_executor(&self) -> BackgroundExecutor {
182 self.0.borrow().background_executor.clone()
183 }
184
185 /// Returns a handle to the [`ForegroundExecutor`] associated with this app, which can be used to spawn futures in the foreground.
186 pub fn foreground_executor(&self) -> ForegroundExecutor {
187 self.0.borrow().foreground_executor.clone()
188 }
189
190 /// Returns a reference to the [`TextSystem`] associated with this app.
191 pub fn text_system(&self) -> Arc<TextSystem> {
192 self.0.borrow().text_system.clone()
193 }
194}
195
196pub(crate) type FrameCallback = Box<dyn FnOnce(&mut AppContext)>;
197type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
198type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
199type KeystrokeObserver = Box<dyn FnMut(&KeystrokeEvent, &mut WindowContext) + 'static>;
200type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
201type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + 'static>;
202type NewViewListener = Box<dyn FnMut(AnyView, &mut WindowContext) + 'static>;
203
204/// Contains the state of the full application, and passed as a reference to a variety of callbacks.
205/// Other contexts such as [ModelContext], [WindowContext], and [ViewContext] deref to this type, making it the most general context type.
206/// You need a reference to an `AppContext` to access the state of a [Model].
207pub struct AppContext {
208 pub(crate) this: Weak<AppCell>,
209 pub(crate) platform: Rc<dyn Platform>,
210 app_metadata: AppMetadata,
211 text_system: Arc<TextSystem>,
212 flushing_effects: bool,
213 pending_updates: usize,
214 pub(crate) actions: Rc<ActionRegistry>,
215 pub(crate) active_drag: Option<AnyDrag>,
216 pub(crate) next_frame_callbacks: FxHashMap<DisplayId, Vec<FrameCallback>>,
217 pub(crate) frame_consumers: FxHashMap<DisplayId, Task<()>>,
218 pub(crate) background_executor: BackgroundExecutor,
219 pub(crate) foreground_executor: ForegroundExecutor,
220 pub(crate) svg_renderer: SvgRenderer,
221 asset_source: Arc<dyn AssetSource>,
222 pub(crate) image_cache: ImageCache,
223 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
224 pub(crate) globals_by_type: FxHashMap<TypeId, Box<dyn Any>>,
225 pub(crate) entities: EntityMap,
226 pub(crate) new_view_observers: SubscriberSet<TypeId, NewViewListener>,
227 pub(crate) windows: SlotMap<WindowId, Option<Window>>,
228 pub(crate) keymap: Rc<RefCell<Keymap>>,
229 pub(crate) global_action_listeners:
230 FxHashMap<TypeId, Vec<Rc<dyn Fn(&dyn Any, DispatchPhase, &mut Self)>>>,
231 pending_effects: VecDeque<Effect>,
232 pub(crate) pending_notifications: FxHashSet<EntityId>,
233 pub(crate) pending_global_notifications: FxHashSet<TypeId>,
234 pub(crate) observers: SubscriberSet<EntityId, Handler>,
235 // TypeId is the type of the event that the listener callback expects
236 pub(crate) event_listeners: SubscriberSet<EntityId, (TypeId, Listener)>,
237 pub(crate) keystroke_observers: SubscriberSet<(), KeystrokeObserver>,
238 pub(crate) release_listeners: SubscriberSet<EntityId, ReleaseListener>,
239 pub(crate) global_observers: SubscriberSet<TypeId, Handler>,
240 pub(crate) quit_observers: SubscriberSet<(), QuitHandler>,
241 pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
242 pub(crate) propagate_event: bool,
243}
244
245impl AppContext {
246 #[allow(clippy::new_ret_no_self)]
247 pub(crate) fn new(
248 platform: Rc<dyn Platform>,
249 asset_source: Arc<dyn AssetSource>,
250 http_client: Arc<dyn HttpClient>,
251 ) -> Rc<AppCell> {
252 let executor = platform.background_executor();
253 let foreground_executor = platform.foreground_executor();
254 assert!(
255 executor.is_main_thread(),
256 "must construct App on main thread"
257 );
258
259 let text_system = Arc::new(TextSystem::new(platform.text_system()));
260 let entities = EntityMap::new();
261
262 let app_metadata = AppMetadata {
263 os_name: platform.os_name(),
264 os_version: platform.os_version().ok(),
265 app_version: platform.app_version().ok(),
266 };
267
268 let app = Rc::new_cyclic(|this| AppCell {
269 app: RefCell::new(AppContext {
270 this: this.clone(),
271 platform: platform.clone(),
272 app_metadata,
273 text_system,
274 actions: Rc::new(ActionRegistry::default()),
275 flushing_effects: false,
276 pending_updates: 0,
277 active_drag: None,
278 next_frame_callbacks: FxHashMap::default(),
279 frame_consumers: FxHashMap::default(),
280 background_executor: executor,
281 foreground_executor,
282 svg_renderer: SvgRenderer::new(asset_source.clone()),
283 asset_source,
284 image_cache: ImageCache::new(http_client),
285 text_style_stack: Vec::new(),
286 globals_by_type: FxHashMap::default(),
287 entities,
288 new_view_observers: SubscriberSet::new(),
289 windows: SlotMap::with_key(),
290 keymap: Rc::new(RefCell::new(Keymap::default())),
291 global_action_listeners: FxHashMap::default(),
292 pending_effects: VecDeque::new(),
293 pending_notifications: FxHashSet::default(),
294 pending_global_notifications: FxHashSet::default(),
295 observers: SubscriberSet::new(),
296 event_listeners: SubscriberSet::new(),
297 release_listeners: SubscriberSet::new(),
298 keystroke_observers: SubscriberSet::new(),
299 global_observers: SubscriberSet::new(),
300 quit_observers: SubscriberSet::new(),
301 layout_id_buffer: Default::default(),
302 propagate_event: true,
303 }),
304 });
305
306 init_app_menus(platform.as_ref(), &mut app.borrow_mut());
307
308 platform.on_quit(Box::new({
309 let cx = app.clone();
310 move || {
311 cx.borrow_mut().shutdown();
312 }
313 }));
314
315 app
316 }
317
318 /// Quit the application gracefully. Handlers registered with [`ModelContext::on_app_quit`]
319 /// will be given 100ms to complete before exiting.
320 pub fn shutdown(&mut self) {
321 let mut futures = Vec::new();
322
323 for observer in self.quit_observers.remove(&()) {
324 futures.push(observer(self));
325 }
326
327 self.windows.clear();
328 self.flush_effects();
329
330 let futures = futures::future::join_all(futures);
331 if self
332 .background_executor
333 .block_with_timeout(SHUTDOWN_TIMEOUT, futures)
334 .is_err()
335 {
336 log::error!("timed out waiting on app_will_quit");
337 }
338 }
339
340 /// Gracefully quit the application via the platform's standard routine.
341 pub fn quit(&mut self) {
342 self.platform.quit();
343 }
344
345 /// Get metadata about the app and platform.
346 pub fn app_metadata(&self) -> AppMetadata {
347 self.app_metadata.clone()
348 }
349
350 /// Schedules all windows in the application to be redrawn. This can be called
351 /// multiple times in an update cycle and still result in a single redraw.
352 pub fn refresh(&mut self) {
353 self.pending_effects.push_back(Effect::Refresh);
354 }
355
356 pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
357 self.pending_updates += 1;
358 let result = update(self);
359 if !self.flushing_effects && self.pending_updates == 1 {
360 self.flushing_effects = true;
361 self.flush_effects();
362 self.flushing_effects = false;
363 }
364 self.pending_updates -= 1;
365 result
366 }
367
368 /// Arrange a callback to be invoked when the given model or view calls `notify` on its respective context.
369 pub fn observe<W, E>(
370 &mut self,
371 entity: &E,
372 mut on_notify: impl FnMut(E, &mut AppContext) + 'static,
373 ) -> Subscription
374 where
375 W: 'static,
376 E: Entity<W>,
377 {
378 self.observe_internal(entity, move |e, cx| {
379 on_notify(e, cx);
380 true
381 })
382 }
383
384 pub(crate) fn new_observer(&mut self, key: EntityId, value: Handler) -> Subscription {
385 let (subscription, activate) = self.observers.insert(key, value);
386 self.defer(move |_| activate());
387 subscription
388 }
389 pub(crate) fn observe_internal<W, E>(
390 &mut self,
391 entity: &E,
392 mut on_notify: impl FnMut(E, &mut AppContext) -> bool + 'static,
393 ) -> Subscription
394 where
395 W: 'static,
396 E: Entity<W>,
397 {
398 let entity_id = entity.entity_id();
399 let handle = entity.downgrade();
400 self.new_observer(
401 entity_id,
402 Box::new(move |cx| {
403 if let Some(handle) = E::upgrade_from(&handle) {
404 on_notify(handle, cx)
405 } else {
406 false
407 }
408 }),
409 )
410 }
411
412 /// Arrange for the given callback to be invoked whenever the given model or view emits an event of a given type.
413 /// The callback is provided a handle to the emitting entity and a reference to the emitted event.
414 pub fn subscribe<T, E, Event>(
415 &mut self,
416 entity: &E,
417 mut on_event: impl FnMut(E, &Event, &mut AppContext) + 'static,
418 ) -> Subscription
419 where
420 T: 'static + EventEmitter<Event>,
421 E: Entity<T>,
422 Event: 'static,
423 {
424 self.subscribe_internal(entity, move |entity, event, cx| {
425 on_event(entity, event, cx);
426 true
427 })
428 }
429
430 pub(crate) fn new_subscription(
431 &mut self,
432 key: EntityId,
433 value: (TypeId, Listener),
434 ) -> Subscription {
435 let (subscription, activate) = self.event_listeners.insert(key, value);
436 self.defer(move |_| activate());
437 subscription
438 }
439 pub(crate) fn subscribe_internal<T, E, Evt>(
440 &mut self,
441 entity: &E,
442 mut on_event: impl FnMut(E, &Evt, &mut AppContext) -> bool + 'static,
443 ) -> Subscription
444 where
445 T: 'static + EventEmitter<Evt>,
446 E: Entity<T>,
447 Evt: 'static,
448 {
449 let entity_id = entity.entity_id();
450 let entity = entity.downgrade();
451 self.new_subscription(
452 entity_id,
453 (
454 TypeId::of::<Evt>(),
455 Box::new(move |event, cx| {
456 let event: &Evt = event.downcast_ref().expect("invalid event type");
457 if let Some(handle) = E::upgrade_from(&entity) {
458 on_event(handle, event, cx)
459 } else {
460 false
461 }
462 }),
463 ),
464 )
465 }
466
467 /// Returns handles to all open windows in the application.
468 /// Each handle could be downcast to a handle typed for the root view of that window.
469 /// To find all windows of a given type, you could filter on
470 pub fn windows(&self) -> Vec<AnyWindowHandle> {
471 self.windows
472 .values()
473 .filter_map(|window| Some(window.as_ref()?.handle))
474 .collect()
475 }
476
477 /// Returns a handle to the window that is currently focused at the platform level, if one exists.
478 pub fn active_window(&self) -> Option<AnyWindowHandle> {
479 self.platform.active_window()
480 }
481
482 /// Opens a new window with the given option and the root view returned by the given function.
483 /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
484 /// functionality.
485 pub fn open_window<V: 'static + Render>(
486 &mut self,
487 options: crate::WindowOptions,
488 build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
489 ) -> WindowHandle<V> {
490 self.update(|cx| {
491 let id = cx.windows.insert(None);
492 let handle = WindowHandle::new(id);
493 let mut window = Window::new(handle.into(), options, cx);
494 let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
495 window.root_view.replace(root_view.into());
496 cx.windows.get_mut(id).unwrap().replace(window);
497 handle
498 })
499 }
500
501 /// Instructs the platform to activate the application by bringing it to the foreground.
502 pub fn activate(&self, ignoring_other_apps: bool) {
503 self.platform.activate(ignoring_other_apps);
504 }
505
506 /// Hide the application at the platform level.
507 pub fn hide(&self) {
508 self.platform.hide();
509 }
510
511 /// Hide other applications at the platform level.
512 pub fn hide_other_apps(&self) {
513 self.platform.hide_other_apps();
514 }
515
516 /// Unhide other applications at the platform level.
517 pub fn unhide_other_apps(&self) {
518 self.platform.unhide_other_apps();
519 }
520
521 /// Returns the list of currently active displays.
522 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
523 self.platform.displays()
524 }
525
526 /// Returns the appearance of the application's windows.
527 pub fn window_appearance(&self) -> WindowAppearance {
528 self.platform.window_appearance()
529 }
530
531 /// Writes data to the platform clipboard.
532 pub fn write_to_clipboard(&self, item: ClipboardItem) {
533 self.platform.write_to_clipboard(item)
534 }
535
536 /// Reads data from the platform clipboard.
537 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
538 self.platform.read_from_clipboard()
539 }
540
541 /// Writes credentials to the platform keychain.
542 pub fn write_credentials(
543 &self,
544 url: &str,
545 username: &str,
546 password: &[u8],
547 ) -> Task<Result<()>> {
548 self.platform.write_credentials(url, username, password)
549 }
550
551 /// Reads credentials from the platform keychain.
552 pub fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {
553 self.platform.read_credentials(url)
554 }
555
556 /// Deletes credentials from the platform keychain.
557 pub fn delete_credentials(&self, url: &str) -> Task<Result<()>> {
558 self.platform.delete_credentials(url)
559 }
560
561 /// Directs the platform's default browser to open the given URL.
562 pub fn open_url(&self, url: &str) {
563 self.platform.open_url(url);
564 }
565
566 /// Returns the full pathname of the current app bundle.
567 /// If the app is not being run from a bundle, returns an error.
568 pub fn app_path(&self) -> Result<PathBuf> {
569 self.platform.app_path()
570 }
571
572 /// Returns the file URL of the executable with the specified name in the application bundle
573 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
574 self.platform.path_for_auxiliary_executable(name)
575 }
576
577 /// Returns the maximum duration in which a second mouse click must occur for an event to be a double-click event.
578 pub fn double_click_interval(&self) -> Duration {
579 self.platform.double_click_interval()
580 }
581
582 /// Displays a platform modal for selecting paths.
583 /// When one or more paths are selected, they'll be relayed asynchronously via the returned oneshot channel.
584 /// If cancelled, a `None` will be relayed instead.
585 pub fn prompt_for_paths(
586 &self,
587 options: PathPromptOptions,
588 ) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
589 self.platform.prompt_for_paths(options)
590 }
591
592 /// Displays a platform modal for selecting a new path where a file can be saved.
593 /// The provided directory will be used to set the initial location.
594 /// When a path is selected, it is relayed asynchronously via the returned oneshot channel.
595 /// If cancelled, a `None` will be relayed instead.
596 pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
597 self.platform.prompt_for_new_path(directory)
598 }
599
600 /// Reveals the specified path at the platform level, such as in Finder on macOS.
601 pub fn reveal_path(&self, path: &Path) {
602 self.platform.reveal_path(path)
603 }
604
605 /// Returns whether the user has configured scrollbars to auto-hide at the platform level.
606 pub fn should_auto_hide_scrollbars(&self) -> bool {
607 self.platform.should_auto_hide_scrollbars()
608 }
609
610 /// Restart the application.
611 pub fn restart(&self) {
612 self.platform.restart()
613 }
614
615 /// Returns the local timezone at the platform level.
616 pub fn local_timezone(&self) -> UtcOffset {
617 self.platform.local_timezone()
618 }
619
620 pub(crate) fn push_effect(&mut self, effect: Effect) {
621 match &effect {
622 Effect::Notify { emitter } => {
623 if !self.pending_notifications.insert(*emitter) {
624 return;
625 }
626 }
627 Effect::NotifyGlobalObservers { global_type } => {
628 if !self.pending_global_notifications.insert(*global_type) {
629 return;
630 }
631 }
632 _ => {}
633 };
634
635 self.pending_effects.push_back(effect);
636 }
637
638 /// Called at the end of [`AppContext::update`] to complete any side effects
639 /// such as notifying observers, emitting events, etc. Effects can themselves
640 /// cause effects, so we continue looping until all effects are processed.
641 fn flush_effects(&mut self) {
642 loop {
643 self.release_dropped_entities();
644 self.release_dropped_focus_handles();
645
646 if let Some(effect) = self.pending_effects.pop_front() {
647 match effect {
648 Effect::Notify { emitter } => {
649 self.apply_notify_effect(emitter);
650 }
651
652 Effect::Emit {
653 emitter,
654 event_type,
655 event,
656 } => self.apply_emit_effect(emitter, event_type, event),
657
658 Effect::Refresh => {
659 self.apply_refresh_effect();
660 }
661
662 Effect::NotifyGlobalObservers { global_type } => {
663 self.apply_notify_global_observers_effect(global_type);
664 }
665
666 Effect::Defer { callback } => {
667 self.apply_defer_effect(callback);
668 }
669 }
670 } else {
671 #[cfg(any(test, feature = "test-support"))]
672 for window in self
673 .windows
674 .values()
675 .filter_map(|window| {
676 let window = window.as_ref()?;
677 window.dirty.get().then_some(window.handle)
678 })
679 .collect::<Vec<_>>()
680 {
681 self.update_window(window, |_, cx| cx.draw()).unwrap();
682 }
683
684 #[allow(clippy::collapsible_else_if)]
685 if self.pending_effects.is_empty() {
686 break;
687 }
688 }
689 }
690 }
691
692 /// Repeatedly called during `flush_effects` to release any entities whose
693 /// reference count has become zero. We invoke any release observers before dropping
694 /// each entity.
695 fn release_dropped_entities(&mut self) {
696 loop {
697 let dropped = self.entities.take_dropped();
698 if dropped.is_empty() {
699 break;
700 }
701
702 for (entity_id, mut entity) in dropped {
703 self.observers.remove(&entity_id);
704 self.event_listeners.remove(&entity_id);
705 for release_callback in self.release_listeners.remove(&entity_id) {
706 release_callback(entity.as_mut(), self);
707 }
708 }
709 }
710 }
711
712 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
713 fn release_dropped_focus_handles(&mut self) {
714 for window_handle in self.windows() {
715 window_handle
716 .update(self, |_, cx| {
717 let mut blur_window = false;
718 let focus = cx.window.focus;
719 cx.window.focus_handles.write().retain(|handle_id, count| {
720 if count.load(SeqCst) == 0 {
721 if focus == Some(handle_id) {
722 blur_window = true;
723 }
724 false
725 } else {
726 true
727 }
728 });
729
730 if blur_window {
731 cx.blur();
732 }
733 })
734 .unwrap();
735 }
736 }
737
738 fn apply_notify_effect(&mut self, emitter: EntityId) {
739 self.pending_notifications.remove(&emitter);
740
741 self.observers
742 .clone()
743 .retain(&emitter, |handler| handler(self));
744 }
745
746 fn apply_emit_effect(&mut self, emitter: EntityId, event_type: TypeId, event: Box<dyn Any>) {
747 self.event_listeners
748 .clone()
749 .retain(&emitter, |(stored_type, handler)| {
750 if *stored_type == event_type {
751 handler(event.as_ref(), self)
752 } else {
753 true
754 }
755 });
756 }
757
758 fn apply_refresh_effect(&mut self) {
759 for window in self.windows.values_mut() {
760 if let Some(window) = window.as_mut() {
761 window.dirty.set(true);
762 }
763 }
764 }
765
766 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
767 self.pending_global_notifications.remove(&type_id);
768 self.global_observers
769 .clone()
770 .retain(&type_id, |observer| observer(self));
771 }
772
773 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
774 callback(self);
775 }
776
777 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
778 /// so it can be held across `await` points.
779 pub fn to_async(&self) -> AsyncAppContext {
780 AsyncAppContext {
781 app: self.this.clone(),
782 background_executor: self.background_executor.clone(),
783 foreground_executor: self.foreground_executor.clone(),
784 }
785 }
786
787 /// Obtains a reference to the executor, which can be used to spawn futures.
788 pub fn background_executor(&self) -> &BackgroundExecutor {
789 &self.background_executor
790 }
791
792 /// Obtains a reference to the executor, which can be used to spawn futures.
793 pub fn foreground_executor(&self) -> &ForegroundExecutor {
794 &self.foreground_executor
795 }
796
797 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
798 /// with [AsyncAppContext], which allows the application state to be accessed across await points.
799 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
800 where
801 Fut: Future<Output = R> + 'static,
802 R: 'static,
803 {
804 self.foreground_executor.spawn(f(self.to_async()))
805 }
806
807 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
808 /// that are currently on the stack to be returned to the app.
809 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
810 self.push_effect(Effect::Defer {
811 callback: Box::new(f),
812 });
813 }
814
815 /// Accessor for the application's asset source, which is provided when constructing the `App`.
816 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
817 &self.asset_source
818 }
819
820 /// Accessor for the text system.
821 pub fn text_system(&self) -> &Arc<TextSystem> {
822 &self.text_system
823 }
824
825 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
826 pub fn text_style(&self) -> TextStyle {
827 let mut style = TextStyle::default();
828 for refinement in &self.text_style_stack {
829 style.refine(refinement);
830 }
831 style
832 }
833
834 /// Check whether a global of the given type has been assigned.
835 pub fn has_global<G: Global>(&self) -> bool {
836 self.globals_by_type.contains_key(&TypeId::of::<G>())
837 }
838
839 /// Access the global of the given type. Panics if a global for that type has not been assigned.
840 #[track_caller]
841 pub fn global<G: Global>(&self) -> &G {
842 self.globals_by_type
843 .get(&TypeId::of::<G>())
844 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
845 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
846 .unwrap()
847 }
848
849 /// Access the global of the given type if a value has been assigned.
850 pub fn try_global<G: Global>(&self) -> Option<&G> {
851 self.globals_by_type
852 .get(&TypeId::of::<G>())
853 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
854 }
855
856 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
857 #[track_caller]
858 pub fn global_mut<G: Global>(&mut self) -> &mut G {
859 let global_type = TypeId::of::<G>();
860 self.push_effect(Effect::NotifyGlobalObservers { global_type });
861 self.globals_by_type
862 .get_mut(&global_type)
863 .and_then(|any_state| any_state.downcast_mut::<G>())
864 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
865 .unwrap()
866 }
867
868 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
869 /// yet been assigned.
870 pub fn default_global<G: Global + Default>(&mut self) -> &mut G {
871 let global_type = TypeId::of::<G>();
872 self.push_effect(Effect::NotifyGlobalObservers { global_type });
873 self.globals_by_type
874 .entry(global_type)
875 .or_insert_with(|| Box::<G>::default())
876 .downcast_mut::<G>()
877 .unwrap()
878 }
879
880 /// Sets the value of the global of the given type.
881 pub fn set_global<G: Global>(&mut self, global: G) {
882 let global_type = TypeId::of::<G>();
883 self.push_effect(Effect::NotifyGlobalObservers { global_type });
884 self.globals_by_type.insert(global_type, Box::new(global));
885 }
886
887 /// Clear all stored globals. Does not notify global observers.
888 #[cfg(any(test, feature = "test-support"))]
889 pub fn clear_globals(&mut self) {
890 self.globals_by_type.drain();
891 }
892
893 /// Remove the global of the given type from the app context. Does not notify global observers.
894 pub fn remove_global<G: Global>(&mut self) -> G {
895 let global_type = TypeId::of::<G>();
896 self.push_effect(Effect::NotifyGlobalObservers { global_type });
897 *self
898 .globals_by_type
899 .remove(&global_type)
900 .unwrap_or_else(|| panic!("no global added for {}", std::any::type_name::<G>()))
901 .downcast()
902 .unwrap()
903 }
904
905 /// Updates the global of the given type with a closure. Unlike `global_mut`, this method provides
906 /// your closure with mutable access to the `AppContext` and the global simultaneously.
907 pub fn update_global<G: Global, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
908 self.update(|cx| {
909 let mut global = cx.lease_global::<G>();
910 let result = f(&mut global, cx);
911 cx.end_global_lease(global);
912 result
913 })
914 }
915
916 /// Register a callback to be invoked when a global of the given type is updated.
917 pub fn observe_global<G: Global>(
918 &mut self,
919 mut f: impl FnMut(&mut Self) + 'static,
920 ) -> Subscription {
921 let (subscription, activate) = self.global_observers.insert(
922 TypeId::of::<G>(),
923 Box::new(move |cx| {
924 f(cx);
925 true
926 }),
927 );
928 self.defer(move |_| activate());
929 subscription
930 }
931
932 /// Move the global of the given type to the stack.
933 pub(crate) fn lease_global<G: Global>(&mut self) -> GlobalLease<G> {
934 GlobalLease::new(
935 self.globals_by_type
936 .remove(&TypeId::of::<G>())
937 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
938 .unwrap(),
939 )
940 }
941
942 /// Restore the global of the given type after it is moved to the stack.
943 pub(crate) fn end_global_lease<G: Global>(&mut self, lease: GlobalLease<G>) {
944 let global_type = TypeId::of::<G>();
945 self.push_effect(Effect::NotifyGlobalObservers { global_type });
946 self.globals_by_type.insert(global_type, lease.global);
947 }
948
949 pub(crate) fn new_view_observer(
950 &mut self,
951 key: TypeId,
952 value: NewViewListener,
953 ) -> Subscription {
954 let (subscription, activate) = self.new_view_observers.insert(key, value);
955 activate();
956 subscription
957 }
958 /// Arrange for the given function to be invoked whenever a view of the specified type is created.
959 /// The function will be passed a mutable reference to the view along with an appropriate context.
960 pub fn observe_new_views<V: 'static>(
961 &mut self,
962 on_new: impl 'static + Fn(&mut V, &mut ViewContext<V>),
963 ) -> Subscription {
964 self.new_view_observer(
965 TypeId::of::<V>(),
966 Box::new(move |any_view: AnyView, cx: &mut WindowContext| {
967 any_view
968 .downcast::<V>()
969 .unwrap()
970 .update(cx, |view_state, cx| {
971 on_new(view_state, cx);
972 })
973 }),
974 )
975 }
976
977 /// Observe the release of a model or view. The callback is invoked after the model or view
978 /// has no more strong references but before it has been dropped.
979 pub fn observe_release<E, T>(
980 &mut self,
981 handle: &E,
982 on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
983 ) -> Subscription
984 where
985 E: Entity<T>,
986 T: 'static,
987 {
988 let (subscription, activate) = self.release_listeners.insert(
989 handle.entity_id(),
990 Box::new(move |entity, cx| {
991 let entity = entity.downcast_mut().expect("invalid entity type");
992 on_release(entity, cx)
993 }),
994 );
995 activate();
996 subscription
997 }
998
999 /// Register a callback to be invoked when a keystroke is received by the application
1000 /// in any window. Note that this fires after all other action and event mechanisms have resolved
1001 /// and that this API will not be invoked if the event's propagation is stopped.
1002 pub fn observe_keystrokes(
1003 &mut self,
1004 f: impl FnMut(&KeystrokeEvent, &mut WindowContext) + 'static,
1005 ) -> Subscription {
1006 fn inner(
1007 keystroke_observers: &mut SubscriberSet<(), KeystrokeObserver>,
1008 handler: KeystrokeObserver,
1009 ) -> Subscription {
1010 let (subscription, activate) = keystroke_observers.insert((), handler);
1011 activate();
1012 subscription
1013 }
1014 inner(&mut self.keystroke_observers, Box::new(f))
1015 }
1016
1017 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
1018 self.text_style_stack.push(text_style);
1019 }
1020
1021 pub(crate) fn pop_text_style(&mut self) {
1022 self.text_style_stack.pop();
1023 }
1024
1025 /// Register key bindings.
1026 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
1027 self.keymap.borrow_mut().add_bindings(bindings);
1028 self.pending_effects.push_back(Effect::Refresh);
1029 }
1030
1031 /// Clear all key bindings in the app.
1032 pub fn clear_key_bindings(&mut self) {
1033 self.keymap.borrow_mut().clear();
1034 self.pending_effects.push_back(Effect::Refresh);
1035 }
1036
1037 /// Register a global listener for actions invoked via the keyboard.
1038 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
1039 self.global_action_listeners
1040 .entry(TypeId::of::<A>())
1041 .or_default()
1042 .push(Rc::new(move |action, phase, cx| {
1043 if phase == DispatchPhase::Bubble {
1044 let action = action.downcast_ref().unwrap();
1045 listener(action, cx)
1046 }
1047 }));
1048 }
1049
1050 /// Event handlers propagate events by default. Call this method to stop dispatching to
1051 /// event handlers with a lower z-index (mouse) or higher in the tree (keyboard). This is
1052 /// the opposite of [`Self::propagate`]. It's also possible to cancel a call to [`Self::propagate`] by
1053 /// calling this method before effects are flushed.
1054 pub fn stop_propagation(&mut self) {
1055 self.propagate_event = false;
1056 }
1057
1058 /// Action handlers stop propagation by default during the bubble phase of action dispatch
1059 /// dispatching to action handlers higher in the element tree. This is the opposite of
1060 /// [`Self::stop_propagation`]. It's also possible to cancel a call to [`Self::stop_propagation`] by calling
1061 /// this method before effects are flushed.
1062 pub fn propagate(&mut self) {
1063 self.propagate_event = true;
1064 }
1065
1066 /// Build an action from some arbitrary data, typically a keymap entry.
1067 pub fn build_action(
1068 &self,
1069 name: &str,
1070 data: Option<serde_json::Value>,
1071 ) -> Result<Box<dyn Action>> {
1072 self.actions.build_action(name, data)
1073 }
1074
1075 /// Get a list of all action names that have been registered.
1076 /// in the application. Note that registration only allows for
1077 /// actions to be built dynamically, and is unrelated to binding
1078 /// actions in the element tree.
1079 pub fn all_action_names(&self) -> &[SharedString] {
1080 self.actions.all_action_names()
1081 }
1082
1083 /// Register a callback to be invoked when the application is about to quit.
1084 /// It is not possible to cancel the quit event at this point.
1085 pub fn on_app_quit<Fut>(
1086 &mut self,
1087 mut on_quit: impl FnMut(&mut AppContext) -> Fut + 'static,
1088 ) -> Subscription
1089 where
1090 Fut: 'static + Future<Output = ()>,
1091 {
1092 let (subscription, activate) = self.quit_observers.insert(
1093 (),
1094 Box::new(move |cx| {
1095 let future = on_quit(cx);
1096 future.boxed_local()
1097 }),
1098 );
1099 activate();
1100 subscription
1101 }
1102
1103 pub(crate) fn clear_pending_keystrokes(&mut self) {
1104 for window in self.windows() {
1105 window
1106 .update(self, |_, cx| {
1107 cx.window
1108 .rendered_frame
1109 .dispatch_tree
1110 .clear_pending_keystrokes();
1111 cx.window
1112 .next_frame
1113 .dispatch_tree
1114 .clear_pending_keystrokes();
1115 })
1116 .ok();
1117 }
1118 }
1119
1120 /// Checks if the given action is bound in the current context, as defined by the app's current focus,
1121 /// the bindings in the element tree, and any global action listeners.
1122 pub fn is_action_available(&mut self, action: &dyn Action) -> bool {
1123 if let Some(window) = self.active_window() {
1124 if let Ok(window_action_available) =
1125 window.update(self, |_, cx| cx.is_action_available(action))
1126 {
1127 return window_action_available;
1128 }
1129 }
1130
1131 self.global_action_listeners
1132 .contains_key(&action.as_any().type_id())
1133 }
1134
1135 /// Sets the menu bar for this application. This will replace any existing menu bar.
1136 pub fn set_menus(&mut self, menus: Vec<Menu>) {
1137 self.platform.set_menus(menus, &self.keymap.borrow());
1138 }
1139
1140 /// Dispatch an action to the currently active window or global action handler
1141 /// See [action::Action] for more information on how actions work
1142 pub fn dispatch_action(&mut self, action: &dyn Action) {
1143 if let Some(active_window) = self.active_window() {
1144 active_window
1145 .update(self, |_, cx| cx.dispatch_action(action.boxed_clone()))
1146 .log_err();
1147 } else {
1148 self.propagate_event = true;
1149
1150 if let Some(mut global_listeners) = self
1151 .global_action_listeners
1152 .remove(&action.as_any().type_id())
1153 {
1154 for listener in &global_listeners {
1155 listener(action.as_any(), DispatchPhase::Capture, self);
1156 if !self.propagate_event {
1157 break;
1158 }
1159 }
1160
1161 global_listeners.extend(
1162 self.global_action_listeners
1163 .remove(&action.as_any().type_id())
1164 .unwrap_or_default(),
1165 );
1166
1167 self.global_action_listeners
1168 .insert(action.as_any().type_id(), global_listeners);
1169 }
1170
1171 if self.propagate_event {
1172 if let Some(mut global_listeners) = self
1173 .global_action_listeners
1174 .remove(&action.as_any().type_id())
1175 {
1176 for listener in global_listeners.iter().rev() {
1177 listener(action.as_any(), DispatchPhase::Bubble, self);
1178 if !self.propagate_event {
1179 break;
1180 }
1181 }
1182
1183 global_listeners.extend(
1184 self.global_action_listeners
1185 .remove(&action.as_any().type_id())
1186 .unwrap_or_default(),
1187 );
1188
1189 self.global_action_listeners
1190 .insert(action.as_any().type_id(), global_listeners);
1191 }
1192 }
1193 }
1194 }
1195
1196 /// Is there currently something being dragged?
1197 pub fn has_active_drag(&self) -> bool {
1198 self.active_drag.is_some()
1199 }
1200}
1201
1202impl Context for AppContext {
1203 type Result<T> = T;
1204
1205 /// Build an entity that is owned by the application. The given function will be invoked with
1206 /// a `ModelContext` and must return an object representing the entity. A `Model` handle will be returned,
1207 /// which can be used to access the entity in a context.
1208 fn new_model<T: 'static>(
1209 &mut self,
1210 build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
1211 ) -> Model<T> {
1212 self.update(|cx| {
1213 let slot = cx.entities.reserve();
1214 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
1215 cx.entities.insert(slot, entity)
1216 })
1217 }
1218
1219 /// Updates the entity referenced by the given model. The function is passed a mutable reference to the
1220 /// entity along with a `ModelContext` for the entity.
1221 fn update_model<T: 'static, R>(
1222 &mut self,
1223 model: &Model<T>,
1224 update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
1225 ) -> R {
1226 self.update(|cx| {
1227 let mut entity = cx.entities.lease(model);
1228 let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
1229 cx.entities.end_lease(entity);
1230 result
1231 })
1232 }
1233
1234 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
1235 where
1236 F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
1237 {
1238 self.update(|cx| {
1239 let mut window = cx
1240 .windows
1241 .get_mut(handle.id)
1242 .ok_or_else(|| anyhow!("window not found"))?
1243 .take()
1244 .unwrap();
1245
1246 let root_view = window.root_view.clone().unwrap();
1247 let result = update(root_view, &mut WindowContext::new(cx, &mut window));
1248
1249 if window.removed {
1250 cx.windows.remove(handle.id);
1251 } else {
1252 cx.windows
1253 .get_mut(handle.id)
1254 .ok_or_else(|| anyhow!("window not found"))?
1255 .replace(window);
1256 }
1257
1258 Ok(result)
1259 })
1260 }
1261
1262 fn read_model<T, R>(
1263 &self,
1264 handle: &Model<T>,
1265 read: impl FnOnce(&T, &AppContext) -> R,
1266 ) -> Self::Result<R>
1267 where
1268 T: 'static,
1269 {
1270 let entity = self.entities.read(handle);
1271 read(entity, self)
1272 }
1273
1274 fn read_window<T, R>(
1275 &self,
1276 window: &WindowHandle<T>,
1277 read: impl FnOnce(View<T>, &AppContext) -> R,
1278 ) -> Result<R>
1279 where
1280 T: 'static,
1281 {
1282 let window = self
1283 .windows
1284 .get(window.id)
1285 .ok_or_else(|| anyhow!("window not found"))?
1286 .as_ref()
1287 .unwrap();
1288
1289 let root_view = window.root_view.clone().unwrap();
1290 let view = root_view
1291 .downcast::<T>()
1292 .map_err(|_| anyhow!("root view's type has changed"))?;
1293
1294 Ok(read(view, self))
1295 }
1296}
1297
1298/// These effects are processed at the end of each application update cycle.
1299pub(crate) enum Effect {
1300 Notify {
1301 emitter: EntityId,
1302 },
1303 Emit {
1304 emitter: EntityId,
1305 event_type: TypeId,
1306 event: Box<dyn Any>,
1307 },
1308 Refresh,
1309 NotifyGlobalObservers {
1310 global_type: TypeId,
1311 },
1312 Defer {
1313 callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
1314 },
1315}
1316
1317/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
1318pub(crate) struct GlobalLease<G: Global> {
1319 global: Box<dyn Any>,
1320 global_type: PhantomData<G>,
1321}
1322
1323impl<G: Global> GlobalLease<G> {
1324 fn new(global: Box<dyn Any>) -> Self {
1325 GlobalLease {
1326 global,
1327 global_type: PhantomData,
1328 }
1329 }
1330}
1331
1332impl<G: Global> Deref for GlobalLease<G> {
1333 type Target = G;
1334
1335 fn deref(&self) -> &Self::Target {
1336 self.global.downcast_ref().unwrap()
1337 }
1338}
1339
1340impl<G: Global> DerefMut for GlobalLease<G> {
1341 fn deref_mut(&mut self) -> &mut Self::Target {
1342 self.global.downcast_mut().unwrap()
1343 }
1344}
1345
1346/// Contains state associated with an active drag operation, started by dragging an element
1347/// within the window or by dragging into the app from the underlying platform.
1348pub struct AnyDrag {
1349 /// The view used to render this drag
1350 pub view: AnyView,
1351
1352 /// The value of the dragged item, to be dropped
1353 pub value: Box<dyn Any>,
1354
1355 /// This is used to render the dragged item in the same place
1356 /// on the original element that the drag was initiated
1357 pub cursor_offset: Point<Pixels>,
1358}
1359
1360/// Contains state associated with a tooltip. You'll only need this struct if you're implementing
1361/// tooltip behavior on a custom element. Otherwise, use [Div::tooltip].
1362#[derive(Clone)]
1363pub struct AnyTooltip {
1364 /// The view used to display the tooltip
1365 pub view: AnyView,
1366
1367 /// The offset from the cursor to use, relative to the parent view
1368 pub cursor_offset: Point<Pixels>,
1369}
1370
1371/// A keystroke event, and potentially the associated action
1372#[derive(Debug)]
1373pub struct KeystrokeEvent {
1374 /// The keystroke that occurred
1375 pub keystroke: Keystroke,
1376
1377 /// The action that was resolved for the keystroke, if any
1378 pub action: Option<Box<dyn Action>>,
1379}