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, Window, WindowContext,
22 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 push_effect(&mut self, effect: Effect) {
271 match &effect {
272 Effect::Notify { emitter } => {
273 if !self.pending_notifications.insert(*emitter) {
274 return;
275 }
276 }
277 Effect::NotifyGlobalObservers { global_type } => {
278 if !self.pending_global_notifications.insert(*global_type) {
279 return;
280 }
281 }
282 _ => {}
283 };
284
285 self.pending_effects.push_back(effect);
286 }
287
288 /// Called at the end of AppContext::update to complete any side effects
289 /// such as notifying observers, emitting events, etc. Effects can themselves
290 /// cause effects, so we continue looping until all effects are processed.
291 fn flush_effects(&mut self) {
292 loop {
293 self.release_dropped_entities();
294 self.release_dropped_focus_handles();
295 if let Some(effect) = self.pending_effects.pop_front() {
296 match effect {
297 Effect::Notify { emitter } => {
298 self.apply_notify_effect(emitter);
299 }
300 Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
301 Effect::FocusChanged {
302 window_handle,
303 focused,
304 } => {
305 self.apply_focus_changed_effect(window_handle, focused);
306 }
307 Effect::Refresh => {
308 self.apply_refresh_effect();
309 }
310 Effect::NotifyGlobalObservers { global_type } => {
311 self.apply_notify_global_observers_effect(global_type);
312 }
313 Effect::Defer { callback } => {
314 self.apply_defer_effect(callback);
315 }
316 }
317 } else {
318 break;
319 }
320 }
321
322 let dirty_window_ids = self
323 .windows
324 .iter()
325 .filter_map(|(_, window)| {
326 let window = window.as_ref().unwrap();
327 if window.dirty {
328 Some(window.handle.clone())
329 } else {
330 None
331 }
332 })
333 .collect::<SmallVec<[_; 8]>>();
334
335 for dirty_window_handle in dirty_window_ids {
336 self.update_window(dirty_window_handle, |_, cx| cx.draw())
337 .unwrap();
338 }
339 }
340
341 /// Repeatedly called during `flush_effects` to release any entities whose
342 /// reference count has become zero. We invoke any release observers before dropping
343 /// each entity.
344 fn release_dropped_entities(&mut self) {
345 loop {
346 let dropped = self.entities.take_dropped();
347 if dropped.is_empty() {
348 break;
349 }
350
351 for (entity_id, mut entity) in dropped {
352 self.observers.remove(&entity_id);
353 self.event_listeners.remove(&entity_id);
354 for release_callback in self.release_listeners.remove(&entity_id) {
355 release_callback(&mut entity, self);
356 }
357 }
358 }
359 }
360
361 /// Repeatedly called during `flush_effects` to handle a focused handle being dropped.
362 /// For now, we simply blur the window if this happens, but we may want to support invoking
363 /// a window blur handler to restore focus to some logical element.
364 fn release_dropped_focus_handles(&mut self) {
365 for window_handle in self.windows() {
366 self.update_window(window_handle, |_, cx| {
367 let mut blur_window = false;
368 let focus = cx.window.focus;
369 cx.window.focus_handles.write().retain(|handle_id, count| {
370 if count.load(SeqCst) == 0 {
371 if focus == Some(handle_id) {
372 blur_window = true;
373 }
374 false
375 } else {
376 true
377 }
378 });
379
380 if blur_window {
381 cx.blur();
382 }
383 })
384 .unwrap();
385 }
386 }
387
388 fn apply_notify_effect(&mut self, emitter: EntityId) {
389 self.pending_notifications.remove(&emitter);
390 self.observers
391 .clone()
392 .retain(&emitter, |handler| handler(self));
393 }
394
395 fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
396 self.event_listeners
397 .clone()
398 .retain(&emitter, |handler| handler(event.as_ref(), self));
399 }
400
401 fn apply_focus_changed_effect(
402 &mut self,
403 window_handle: AnyWindowHandle,
404 focused: Option<FocusId>,
405 ) {
406 self.update_window(window_handle, |_, cx| {
407 if cx.window.focus == focused {
408 let mut listeners = mem::take(&mut cx.window.focus_listeners);
409 let focused =
410 focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
411 let blurred = cx
412 .window
413 .last_blur
414 .take()
415 .unwrap()
416 .and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
417 if focused.is_some() || blurred.is_some() {
418 let event = FocusEvent { focused, blurred };
419 for listener in &listeners {
420 listener(&event, cx);
421 }
422 }
423
424 listeners.extend(cx.window.focus_listeners.drain(..));
425 cx.window.focus_listeners = listeners;
426 }
427 })
428 .ok();
429 }
430
431 fn apply_refresh_effect(&mut self) {
432 for window in self.windows.values_mut() {
433 if let Some(window) = window.as_mut() {
434 window.dirty = true;
435 }
436 }
437 }
438
439 fn apply_notify_global_observers_effect(&mut self, type_id: TypeId) {
440 self.pending_global_notifications.remove(&type_id);
441 self.global_observers
442 .clone()
443 .retain(&type_id, |observer| observer(self));
444 }
445
446 fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + 'static>) {
447 callback(self);
448 }
449
450 /// Creates an `AsyncAppContext`, which can be cloned and has a static lifetime
451 /// so it can be held across `await` points.
452 pub fn to_async(&self) -> AsyncAppContext {
453 AsyncAppContext {
454 app: unsafe { mem::transmute(self.this.clone()) },
455 executor: self.executor.clone(),
456 }
457 }
458
459 /// Obtains a reference to the executor, which can be used to spawn futures.
460 pub fn executor(&self) -> &Executor {
461 &self.executor
462 }
463
464 /// Runs the given closure on the main thread, where interaction with the platform
465 /// is possible. The given closure will be invoked with a `MainThread<AppContext>`, which
466 /// has platform-specific methods that aren't present on `AppContext`.
467 pub fn run_on_main<R>(
468 &mut self,
469 f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
470 ) -> Task<R>
471 where
472 R: Send + 'static,
473 {
474 if self.executor.is_main_thread() {
475 Task::ready(f(unsafe {
476 mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
477 }))
478 } else {
479 let this = self.this.upgrade().unwrap();
480 self.executor.run_on_main(move || {
481 let cx = &mut *this.lock();
482 cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
483 })
484 }
485 }
486
487 /// Spawns the future returned by the given function on the main thread, where interaction with
488 /// the platform is possible. The given closure will be invoked with a `MainThread<AsyncAppContext>`,
489 /// which has platform-specific methods that aren't present on `AsyncAppContext`. The future will be
490 /// polled exclusively on the main thread.
491 // todo!("I think we need somehow to prevent the MainThread<AsyncAppContext> from implementing Send")
492 pub fn spawn_on_main<F, R>(
493 &self,
494 f: impl FnOnce(MainThread<AsyncAppContext>) -> F + Send + 'static,
495 ) -> Task<R>
496 where
497 F: Future<Output = R> + 'static,
498 R: Send + 'static,
499 {
500 let cx = self.to_async();
501 self.executor.spawn_on_main(move || f(MainThread(cx)))
502 }
503
504 /// Spawns the future returned by the given function on the thread pool. The closure will be invoked
505 /// with AsyncAppContext, which allows the application state to be accessed across await points.
506 pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
507 where
508 Fut: Future<Output = R> + Send + 'static,
509 R: Send + 'static,
510 {
511 let cx = self.to_async();
512 self.executor.spawn(async move {
513 let future = f(cx);
514 future.await
515 })
516 }
517
518 /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
519 /// that are currently on the stack to be returned to the app.
520 pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send) {
521 self.push_effect(Effect::Defer {
522 callback: Box::new(f),
523 });
524 }
525
526 /// Accessor for the application's asset source, which is provided when constructing the `App`.
527 pub fn asset_source(&self) -> &Arc<dyn AssetSource> {
528 &self.asset_source
529 }
530
531 /// Accessor for the text system.
532 pub fn text_system(&self) -> &Arc<TextSystem> {
533 &self.text_system
534 }
535
536 /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
537 pub fn text_style(&self) -> TextStyle {
538 let mut style = TextStyle::default();
539 for refinement in &self.text_style_stack {
540 style.refine(refinement);
541 }
542 style
543 }
544
545 /// Check whether a global of the given type has been assigned.
546 pub fn has_global<G: 'static>(&self) -> bool {
547 self.globals_by_type.contains_key(&TypeId::of::<G>())
548 }
549
550 /// Access the global of the given type. Panics if a global for that type has not been assigned.
551 pub fn global<G: 'static>(&self) -> &G {
552 self.globals_by_type
553 .get(&TypeId::of::<G>())
554 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
555 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
556 .unwrap()
557 }
558
559 /// Access the global of the given type if a value has been assigned.
560 pub fn try_global<G: 'static>(&self) -> Option<&G> {
561 self.globals_by_type
562 .get(&TypeId::of::<G>())
563 .map(|any_state| any_state.downcast_ref::<G>().unwrap())
564 }
565
566 /// Access the global of the given type mutably. Panics if a global for that type has not been assigned.
567 pub fn global_mut<G: 'static>(&mut self) -> &mut G {
568 let global_type = TypeId::of::<G>();
569 self.push_effect(Effect::NotifyGlobalObservers { global_type });
570 self.globals_by_type
571 .get_mut(&global_type)
572 .and_then(|any_state| any_state.downcast_mut::<G>())
573 .ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
574 .unwrap()
575 }
576
577 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
578 /// yet been assigned.
579 pub fn default_global<G: 'static + Default + Send>(&mut self) -> &mut G {
580 let global_type = TypeId::of::<G>();
581 self.push_effect(Effect::NotifyGlobalObservers { global_type });
582 self.globals_by_type
583 .entry(global_type)
584 .or_insert_with(|| Box::new(G::default()))
585 .downcast_mut::<G>()
586 .unwrap()
587 }
588
589 /// Set the value of the global of the given type.
590 pub fn set_global<G: Any + Send>(&mut self, global: G) {
591 let global_type = TypeId::of::<G>();
592 self.push_effect(Effect::NotifyGlobalObservers { global_type });
593 self.globals_by_type.insert(global_type, Box::new(global));
594 }
595
596 /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
597 /// your closure with mutable access to the `AppContext` and the global simultaneously.
598 pub fn update_global<G: 'static, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R {
599 let mut global = self.lease_global::<G>();
600 let result = f(&mut global, self);
601 self.end_global_lease(global);
602 result
603 }
604
605 /// Register a callback to be invoked when a global of the given type is updated.
606 pub fn observe_global<G: 'static>(
607 &mut self,
608 mut f: impl FnMut(&mut Self) + Send + 'static,
609 ) -> Subscription {
610 self.global_observers.insert(
611 TypeId::of::<G>(),
612 Box::new(move |cx| {
613 f(cx);
614 true
615 }),
616 )
617 }
618
619 pub fn all_action_names<'a>(&'a self) -> impl Iterator<Item = SharedString> + 'a {
620 self.action_builders.keys().cloned()
621 }
622
623 /// Move the global of the given type to the stack.
624 pub(crate) fn lease_global<G: 'static>(&mut self) -> GlobalLease<G> {
625 GlobalLease::new(
626 self.globals_by_type
627 .remove(&TypeId::of::<G>())
628 .ok_or_else(|| anyhow!("no global registered of type {}", type_name::<G>()))
629 .unwrap(),
630 )
631 }
632
633 /// Restore the global of the given type after it is moved to the stack.
634 pub(crate) fn end_global_lease<G: 'static>(&mut self, lease: GlobalLease<G>) {
635 let global_type = TypeId::of::<G>();
636 self.push_effect(Effect::NotifyGlobalObservers { global_type });
637 self.globals_by_type.insert(global_type, lease.global);
638 }
639
640 pub fn observe_release<E, T>(
641 &mut self,
642 handle: &E,
643 on_release: impl FnOnce(&mut T, &mut AppContext) + Send + 'static,
644 ) -> Subscription
645 where
646 E: Entity<T>,
647 T: 'static,
648 {
649 self.release_listeners.insert(
650 handle.entity_id(),
651 Box::new(move |entity, cx| {
652 let entity = entity.downcast_mut().expect("invalid entity type");
653 on_release(entity, cx)
654 }),
655 )
656 }
657
658 pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
659 self.text_style_stack.push(text_style);
660 }
661
662 pub(crate) fn pop_text_style(&mut self) {
663 self.text_style_stack.pop();
664 }
665
666 /// Register key bindings.
667 pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
668 self.keymap.lock().add_bindings(bindings);
669 self.pending_effects.push_back(Effect::Refresh);
670 }
671
672 /// Register a global listener for actions invoked via the keyboard.
673 pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + Send + 'static) {
674 self.global_action_listeners
675 .entry(TypeId::of::<A>())
676 .or_default()
677 .push(Box::new(move |action, phase, cx| {
678 if phase == DispatchPhase::Bubble {
679 let action = action.as_any().downcast_ref().unwrap();
680 listener(action, cx)
681 }
682 }));
683 }
684
685 /// Register an action type to allow it to be referenced in keymaps.
686 pub fn register_action_type<A: Action>(&mut self) {
687 self.action_builders.insert(A::qualified_name(), A::build);
688 }
689
690 /// Construct an action based on its name and parameters.
691 pub fn build_action(
692 &mut self,
693 name: &str,
694 params: Option<serde_json::Value>,
695 ) -> Result<Box<dyn Action>> {
696 let build = self
697 .action_builders
698 .get(name)
699 .ok_or_else(|| anyhow!("no action type registered for {}", name))?;
700 (build)(params)
701 }
702
703 /// Halt propagation of a mouse event, keyboard event, or action. This prevents listeners
704 /// that have not yet been invoked from receiving the event.
705 pub fn stop_propagation(&mut self) {
706 self.propagate_event = false;
707 }
708}
709
710impl Context for AppContext {
711 type WindowContext<'a> = WindowContext<'a>;
712 type ModelContext<'a, T> = ModelContext<'a, T>;
713 type Result<T> = T;
714
715 /// Build an entity that is owned by the application. The given function will be invoked with
716 /// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
717 /// which can be used to access the entity in a context.
718 fn build_model<T: 'static + Send>(
719 &mut self,
720 build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
721 ) -> Model<T> {
722 self.update(|cx| {
723 let slot = cx.entities.reserve();
724 let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
725 cx.entities.insert(slot, entity)
726 })
727 }
728
729 /// Update the entity referenced by the given model. The function is passed a mutable reference to the
730 /// entity along with a `ModelContext` for the entity.
731 fn update_model<T: 'static, R>(
732 &mut self,
733 model: &Model<T>,
734 update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
735 ) -> R {
736 self.update(|cx| {
737 let mut entity = cx.entities.lease(model);
738 let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
739 cx.entities.end_lease(entity);
740 result
741 })
742 }
743
744 fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
745 where
746 F: FnOnce(AnyView, &mut Self::WindowContext<'_>) -> T,
747 {
748 self.update(|cx| {
749 let mut window = cx
750 .windows
751 .get_mut(handle.id)
752 .ok_or_else(|| anyhow!("window not found"))?
753 .take()
754 .unwrap();
755
756 let root_view = window.root_view.clone().unwrap();
757 let result = update(root_view, &mut WindowContext::new(cx, &mut window));
758 cx.windows
759 .get_mut(handle.id)
760 .ok_or_else(|| anyhow!("window not found"))?
761 .replace(window);
762
763 Ok(result)
764 })
765 }
766}
767
768impl<C> MainThread<C>
769where
770 C: Borrow<AppContext>,
771{
772 pub(crate) fn platform(&self) -> &dyn Platform {
773 self.0.borrow().platform.borrow_on_main_thread()
774 }
775
776 /// Instructs the platform to activate the application by bringing it to the foreground.
777 pub fn activate(&self, ignoring_other_apps: bool) {
778 self.platform().activate(ignoring_other_apps);
779 }
780
781 /// Writes data to the platform clipboard.
782 pub fn write_to_clipboard(&self, item: ClipboardItem) {
783 self.platform().write_to_clipboard(item)
784 }
785
786 /// Reads data from the platform clipboard.
787 pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
788 self.platform().read_from_clipboard()
789 }
790
791 /// Writes credentials to the platform keychain.
792 pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
793 self.platform().write_credentials(url, username, password)
794 }
795
796 /// Reads credentials from the platform keychain.
797 pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
798 self.platform().read_credentials(url)
799 }
800
801 /// Deletes credentials from the platform keychain.
802 pub fn delete_credentials(&self, url: &str) -> Result<()> {
803 self.platform().delete_credentials(url)
804 }
805
806 /// Directs the platform's default browser to open the given URL.
807 pub fn open_url(&self, url: &str) {
808 self.platform().open_url(url);
809 }
810
811 pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
812 self.platform().path_for_auxiliary_executable(name)
813 }
814
815 pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
816 self.platform().displays()
817 }
818
819 pub fn display_for_uuid(&self, uuid: Uuid) -> Option<Rc<dyn PlatformDisplay>> {
820 self.platform()
821 .displays()
822 .into_iter()
823 .find(|display| display.uuid().ok() == Some(uuid))
824 }
825}
826
827impl MainThread<AppContext> {
828 fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
829 self.0.update(|cx| {
830 update(unsafe {
831 std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
832 })
833 })
834 }
835
836 /// Opens a new window with the given option and the root view returned by the given function.
837 /// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
838 /// functionality.
839 pub fn open_window<V: Render>(
840 &mut self,
841 options: crate::WindowOptions,
842 build_root_view: impl FnOnce(&mut MainThread<WindowContext>) -> View<V> + Send + 'static,
843 ) -> WindowHandle<V> {
844 self.update(|cx| {
845 let id = cx.windows.insert(None);
846 let handle = WindowHandle::new(id);
847 let mut window = Window::new(handle.into(), options, cx);
848 let mut window_context = MainThread(WindowContext::new(cx, &mut window));
849 let root_view = build_root_view(&mut window_context);
850 window.root_view.replace(root_view.into());
851 cx.windows.get_mut(id).unwrap().replace(window);
852 handle
853 })
854 }
855
856 /// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
857 /// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.
858 pub fn update_global<G: 'static + Send, R>(
859 &mut self,
860 update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
861 ) -> R {
862 self.0.update_global(|global, cx| {
863 let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
864 update(global, cx)
865 })
866 }
867}
868
869/// These effects are processed at the end of each application update cycle.
870pub(crate) enum Effect {
871 Notify {
872 emitter: EntityId,
873 },
874 Emit {
875 emitter: EntityId,
876 event: Box<dyn Any + Send + 'static>,
877 },
878 FocusChanged {
879 window_handle: AnyWindowHandle,
880 focused: Option<FocusId>,
881 },
882 Refresh,
883 NotifyGlobalObservers {
884 global_type: TypeId,
885 },
886 Defer {
887 callback: Box<dyn FnOnce(&mut AppContext) + Send + 'static>,
888 },
889}
890
891/// Wraps a global variable value during `update_global` while the value has been moved to the stack.
892pub(crate) struct GlobalLease<G: 'static> {
893 global: AnyBox,
894 global_type: PhantomData<G>,
895}
896
897impl<G: 'static> GlobalLease<G> {
898 fn new(global: AnyBox) -> Self {
899 GlobalLease {
900 global,
901 global_type: PhantomData,
902 }
903 }
904}
905
906impl<G: 'static> Deref for GlobalLease<G> {
907 type Target = G;
908
909 fn deref(&self) -> &Self::Target {
910 self.global.downcast_ref().unwrap()
911 }
912}
913
914impl<G: 'static> DerefMut for GlobalLease<G> {
915 fn deref_mut(&mut self) -> &mut Self::Target {
916 self.global.downcast_mut().unwrap()
917 }
918}
919
920/// Contains state associated with an active drag operation, started by dragging an element
921/// within the window or by dragging into the app from the underlying platform.
922pub(crate) struct AnyDrag {
923 pub view: AnyView,
924 pub cursor_offset: Point<Pixels>,
925}
926
927#[cfg(test)]
928mod tests {
929 use super::AppContext;
930
931 #[test]
932 fn test_app_context_send_sync() {
933 // This will not compile if `AppContext` does not implement `Send`
934 fn assert_send<T: Send>() {}
935 assert_send::<AppContext>();
936 }
937}