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