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