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