zed/crates/gpui2/src/app.rs

727 lines
23 KiB
Rust
Raw Normal View History

2023-09-28 05:23:59 +00:00
mod async_context;
2023-09-28 07:16:42 +00:00
mod entity_map;
2023-09-28 05:19:32 +00:00
mod model_context;
2023-09-28 05:23:59 +00:00
pub use async_context::*;
2023-09-28 07:16:42 +00:00
pub use entity_map::*;
2023-09-28 05:19:32 +00:00
pub use model_context::*;
2023-09-29 19:22:53 +00:00
use refineable::Refineable;
2023-10-18 15:27:59 +00:00
use smallvec::SmallVec;
2023-09-28 05:19:32 +00:00
2023-09-20 16:17:29 +00:00
use crate::{
2023-10-22 14:27:23 +00:00
current_platform, image_cache::ImageCache, Action, AppMetadata, AssetSource, Context,
DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId, KeyBinding, Keymap,
LayoutId, MainThread, MainThreadOnly, Platform, SemanticVersion, SharedString, SubscriberSet,
2023-10-22 10:21:28 +00:00
SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem, View, Window, WindowContext,
WindowHandle, WindowId,
2023-09-20 16:17:29 +00:00
};
2023-09-19 19:19:22 +00:00
use anyhow::{anyhow, Result};
2023-10-12 12:58:31 +00:00
use collections::{HashMap, HashSet, VecDeque};
2023-10-04 17:59:24 +00:00
use futures::Future;
2023-10-19 17:26:52 +00:00
use parking_lot::{Mutex, RwLock};
2023-09-19 19:19:22 +00:00
use slotmap::SlotMap;
2023-09-29 19:22:53 +00:00
use std::{
any::{type_name, Any, TypeId},
2023-10-02 18:47:45 +00:00
mem,
2023-10-18 15:27:59 +00:00
sync::{atomic::Ordering::SeqCst, Arc, Weak},
2023-09-29 19:22:53 +00:00
};
2023-10-11 04:14:47 +00:00
use util::http::{self, HttpClient};
2023-09-19 19:19:22 +00:00
2023-10-04 21:05:04 +00:00
pub struct App(Arc<Mutex<AppContext>>);
2023-09-19 19:19:22 +00:00
2023-09-20 16:17:29 +00:00
impl App {
2023-10-04 08:51:47 +00:00
pub fn production(asset_source: Arc<dyn AssetSource>) -> Self {
2023-10-04 13:03:21 +00:00
let http_client = http::client();
Self::new(current_platform(), asset_source, http_client)
2023-09-22 16:02:11 +00:00
}
#[cfg(any(test, feature = "test"))]
pub fn test() -> Self {
2023-10-04 08:51:47 +00:00
let platform = Arc::new(super::TestPlatform::new());
let asset_source = Arc::new(());
2023-10-04 13:03:21 +00:00
let http_client = util::http::FakeHttpClient::with_404_response();
Self::new(platform, asset_source, http_client)
2023-09-22 16:02:11 +00:00
}
2023-10-04 13:03:21 +00:00
fn new(
platform: Arc<dyn Platform>,
asset_source: Arc<dyn AssetSource>,
http_client: Arc<dyn HttpClient>,
) -> Self {
2023-10-04 17:53:29 +00:00
let executor = platform.executor();
2023-10-22 14:27:23 +00:00
assert!(
executor.is_main_thread(),
"must construct App on main thread"
);
let text_system = Arc::new(TextSystem::new(platform.text_system()));
2023-09-28 06:46:15 +00:00
let entities = EntityMap::new();
2023-10-04 21:05:04 +00:00
let unit_entity = entities.insert(entities.reserve(), ());
2023-10-22 14:27:23 +00:00
let app_metadata = AppMetadata {
os_name: platform.os_name(),
os_version: platform.os_version().unwrap_or_default(),
app_version: platform.app_version().unwrap_or_default(),
};
2023-09-22 16:02:11 +00:00
Self(Arc::new_cyclic(|this| {
2023-10-04 21:05:04 +00:00
Mutex::new(AppContext {
2023-09-22 16:02:11 +00:00
this: this.clone(),
2023-10-22 14:27:23 +00:00
text_system,
2023-10-21 15:52:47 +00:00
platform: MainThreadOnly::new(platform, executor.clone()),
2023-10-22 14:27:23 +00:00
app_metadata,
2023-10-18 13:17:22 +00:00
flushing_effects: false,
2023-10-21 15:52:47 +00:00
pending_updates: 0,
2023-10-05 08:57:16 +00:00
next_frame_callbacks: Default::default(),
2023-10-04 17:53:29 +00:00
executor,
2023-10-04 08:51:47 +00:00
svg_renderer: SvgRenderer::new(asset_source),
2023-10-04 13:03:21 +00:00
image_cache: ImageCache::new(http_client),
2023-09-29 19:22:53 +00:00
text_style_stack: Vec::new(),
2023-10-11 23:18:33 +00:00
global_stacks_by_type: HashMap::default(),
2023-09-26 17:29:44 +00:00
unit_entity,
2023-09-22 16:02:11 +00:00
entities,
windows: SlotMap::with_key(),
2023-10-19 17:26:52 +00:00
keymap: Arc::new(RwLock::new(Keymap::default())),
2023-10-22 10:21:28 +00:00
global_action_listeners: HashMap::default(),
2023-10-21 15:52:47 +00:00
action_builders: HashMap::default(),
2023-10-12 12:58:31 +00:00
pending_notifications: Default::default(),
2023-09-25 17:47:37 +00:00
pending_effects: Default::default(),
2023-10-11 10:45:09 +00:00
observers: SubscriberSet::new(),
event_handlers: SubscriberSet::new(),
2023-10-12 12:49:06 +00:00
release_handlers: SubscriberSet::new(),
2023-09-22 16:02:11 +00:00
layout_id_buffer: Default::default(),
2023-10-22 10:21:28 +00:00
propagate_event: true,
2023-10-04 21:05:04 +00:00
})
2023-09-22 16:02:11 +00:00
}))
2023-09-20 18:03:37 +00:00
}
pub fn run<F>(self, on_finish_launching: F)
where
2023-10-02 18:47:45 +00:00
F: 'static + FnOnce(&mut MainThread<AppContext>),
2023-09-20 18:03:37 +00:00
{
2023-10-21 16:41:09 +00:00
let this = self.0.clone();
let platform = self.0.lock().platform.clone();
platform.borrow_on_main_thread().run(Box::new(move || {
2023-10-21 16:41:09 +00:00
let cx = &mut *this.lock();
2023-10-04 21:05:04 +00:00
let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
2023-09-22 16:02:11 +00:00
on_finish_launching(cx);
2023-09-20 18:03:37 +00:00
}));
2023-09-20 16:17:29 +00:00
}
2023-10-21 15:52:47 +00:00
2023-10-21 16:41:09 +00:00
pub fn on_open_urls<F>(&self, mut callback: F) -> &Self
where
F: 'static + FnMut(Vec<String>, &mut AppContext),
{
let this = Arc::downgrade(&self.0);
self.0
.lock()
.platform
.borrow_on_main_thread()
.on_open_urls(Box::new(move |urls| {
if let Some(app) = this.upgrade() {
callback(urls, &mut app.lock());
}
}));
self
}
pub fn on_reopen<F>(&self, mut callback: F) -> &Self
where
F: 'static + FnMut(&mut AppContext),
{
let this = Arc::downgrade(&self.0);
self.0
.lock()
.platform
.borrow_on_main_thread()
.on_reopen(Box::new(move || {
if let Some(app) = this.upgrade() {
callback(&mut app.lock());
}
}));
self
}
2023-10-22 14:27:23 +00:00
pub fn metadata(&self) -> AppMetadata {
self.0.lock().app_metadata.clone()
2023-10-21 17:07:59 +00:00
}
2023-10-21 15:52:47 +00:00
pub fn executor(&self) -> Executor {
self.0.lock().executor.clone()
}
2023-10-21 16:33:08 +00:00
pub fn text_system(&self) -> Arc<TextSystem> {
self.0.lock().text_system.clone()
}
2023-09-20 16:17:29 +00:00
}
2023-09-19 19:19:22 +00:00
2023-10-11 10:47:19 +00:00
type Handler = Box<dyn Fn(&mut AppContext) -> bool + Send + Sync + 'static>;
type EventHandler = Box<dyn Fn(&dyn Any, &mut AppContext) -> bool + Send + Sync + 'static>;
2023-10-12 12:49:06 +00:00
type ReleaseHandler = Box<dyn Fn(&mut dyn Any, &mut AppContext) + Send + Sync + 'static>;
2023-10-05 08:57:16 +00:00
type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
2023-10-21 15:52:47 +00:00
type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
2023-09-25 17:47:37 +00:00
2023-10-02 18:47:45 +00:00
pub struct AppContext {
2023-10-04 21:05:04 +00:00
this: Weak<Mutex<AppContext>>,
2023-10-11 15:53:29 +00:00
pub(crate) platform: MainThreadOnly<dyn Platform>,
2023-10-22 14:27:23 +00:00
app_metadata: AppMetadata,
2023-09-20 18:03:37 +00:00
text_system: Arc<TextSystem>,
2023-10-18 13:17:22 +00:00
flushing_effects: bool,
2023-09-28 05:23:59 +00:00
pending_updates: usize,
2023-10-05 08:57:16 +00:00
pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
2023-10-04 17:53:29 +00:00
pub(crate) executor: Executor,
2023-10-04 08:51:47 +00:00
pub(crate) svg_renderer: SvgRenderer,
2023-10-04 13:03:21 +00:00
pub(crate) image_cache: ImageCache,
2023-09-29 19:22:53 +00:00
pub(crate) text_style_stack: Vec<TextStyleRefinement>,
2023-10-11 23:18:33 +00:00
pub(crate) global_stacks_by_type: HashMap<TypeId, Vec<Box<dyn Any + Send + Sync>>>,
2023-09-26 17:29:44 +00:00
pub(crate) unit_entity: Handle<()>,
2023-09-28 06:46:15 +00:00
pub(crate) entities: EntityMap,
2023-09-19 19:19:22 +00:00
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
2023-10-19 17:43:28 +00:00
pub(crate) keymap: Arc<RwLock<Keymap>>,
2023-10-22 10:21:28 +00:00
pub(crate) global_action_listeners:
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send + Sync>>>,
2023-10-21 15:52:47 +00:00
action_builders: HashMap<SharedString, ActionBuilder>,
2023-10-12 12:58:31 +00:00
pub(crate) pending_notifications: HashSet<EntityId>,
pending_effects: VecDeque<Effect>,
2023-10-11 10:45:09 +00:00
pub(crate) observers: SubscriberSet<EntityId, Handler>,
pub(crate) event_handlers: SubscriberSet<EntityId, EventHandler>,
2023-10-12 12:49:06 +00:00
pub(crate) release_handlers: SubscriberSet<EntityId, ReleaseHandler>,
2023-09-28 05:23:59 +00:00
pub(crate) layout_id_buffer: Vec<LayoutId>, // We recycle this memory across layout requests.
2023-10-22 10:21:28 +00:00
pub(crate) propagate_event: bool,
2023-09-19 19:19:22 +00:00
}
2023-10-02 18:47:45 +00:00
impl AppContext {
2023-10-22 14:27:23 +00:00
pub fn app_metadata(&self) -> AppMetadata {
self.app_metadata.clone()
}
2023-10-22 11:15:29 +00:00
pub fn refresh(&mut self) {
self.push_effect(Effect::Refresh);
}
2023-10-04 21:05:04 +00:00
pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
2023-10-02 18:47:45 +00:00
self.pending_updates += 1;
let result = update(self);
2023-10-18 13:17:22 +00:00
if !self.flushing_effects && self.pending_updates == 1 {
self.flushing_effects = true;
2023-10-02 18:47:45 +00:00
self.flush_effects();
2023-10-18 13:17:22 +00:00
self.flushing_effects = false;
2023-10-02 18:47:45 +00:00
}
self.pending_updates -= 1;
result
}
2023-10-21 15:52:47 +00:00
pub(crate) fn read_window<R>(
&mut self,
id: WindowId,
read: impl FnOnce(&WindowContext) -> R,
) -> Result<R> {
let window = self
.windows
.get(id)
.ok_or_else(|| anyhow!("window not found"))?
.as_ref()
.unwrap();
Ok(read(&WindowContext::immutable(self, &window)))
}
2023-10-02 18:47:45 +00:00
pub(crate) fn update_window<R>(
&mut self,
id: WindowId,
update: impl FnOnce(&mut WindowContext) -> R,
) -> Result<R> {
self.update(|cx| {
let mut window = cx
.windows
.get_mut(id)
.ok_or_else(|| anyhow!("window not found"))?
.take()
.unwrap();
let result = update(&mut WindowContext::mutable(cx, &mut window));
cx.windows
.get_mut(id)
.ok_or_else(|| anyhow!("window not found"))?
.replace(window);
Ok(result)
})
}
2023-10-12 12:58:31 +00:00
pub(crate) fn push_effect(&mut self, effect: Effect) {
match &effect {
Effect::Notify { emitter } => {
if self.pending_notifications.insert(*emitter) {
self.pending_effects.push_back(effect);
}
}
Effect::Emit { .. } => self.pending_effects.push_back(effect),
2023-10-18 13:17:22 +00:00
Effect::FocusChanged { .. } => self.pending_effects.push_back(effect),
2023-10-19 17:47:50 +00:00
Effect::Refresh => self.pending_effects.push_back(effect),
2023-10-12 12:58:31 +00:00
}
}
2023-10-02 18:47:45 +00:00
fn flush_effects(&mut self) {
2023-10-12 12:49:06 +00:00
loop {
self.release_dropped_entities();
2023-10-18 15:27:59 +00:00
self.release_dropped_focus_handles();
2023-10-12 12:49:06 +00:00
if let Some(effect) = self.pending_effects.pop_front() {
match effect {
Effect::Notify { emitter } => self.apply_notify_effect(emitter),
Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
2023-10-18 13:17:22 +00:00
Effect::FocusChanged { window_id, focused } => {
self.apply_focus_changed(window_id, focused)
}
2023-10-19 17:47:50 +00:00
Effect::Refresh => {
self.apply_refresh();
}
2023-10-12 12:49:06 +00:00
}
} else {
break;
2023-10-02 18:47:45 +00:00
}
}
let dirty_window_ids = self
.windows
.iter()
.filter_map(|(window_id, window)| {
let window = window.as_ref().unwrap();
if window.dirty {
Some(window_id)
} else {
None
}
})
2023-10-18 15:27:59 +00:00
.collect::<SmallVec<[_; 8]>>();
2023-10-02 18:47:45 +00:00
for dirty_window_id in dirty_window_ids {
2023-10-11 04:14:47 +00:00
self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
2023-10-02 18:47:45 +00:00
}
}
2023-10-12 12:49:06 +00:00
fn release_dropped_entities(&mut self) {
loop {
let dropped = self.entities.take_dropped();
if dropped.is_empty() {
break;
}
for (entity_id, mut entity) in dropped {
self.observers.remove(&entity_id);
self.event_handlers.remove(&entity_id);
for release_callback in self.release_handlers.remove(&entity_id) {
release_callback(&mut entity, self);
}
}
}
}
2023-10-18 15:27:59 +00:00
fn release_dropped_focus_handles(&mut self) {
let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
for window_id in window_ids {
self.update_window(window_id, |cx| {
let mut blur_window = false;
let focus = cx.window.focus;
cx.window.focus_handles.write().retain(|handle_id, count| {
if count.load(SeqCst) == 0 {
if focus == Some(handle_id) {
blur_window = true;
}
false
} else {
true
}
});
if blur_window {
cx.blur();
}
})
.unwrap();
}
}
2023-10-12 11:25:49 +00:00
fn apply_notify_effect(&mut self, emitter: EntityId) {
2023-10-12 12:58:31 +00:00
self.pending_notifications.remove(&emitter);
2023-10-11 10:45:09 +00:00
self.observers
.clone()
2023-10-12 11:25:49 +00:00
.retain(&emitter, |handler| handler(self));
2023-09-19 19:19:22 +00:00
}
2023-10-12 11:25:49 +00:00
fn apply_emit_effect(&mut self, emitter: EntityId, event: Box<dyn Any>) {
2023-10-11 10:45:09 +00:00
self.event_handlers
.clone()
2023-10-12 11:25:49 +00:00
.retain(&emitter, |handler| handler(&event, self));
2023-10-11 08:45:57 +00:00
}
2023-10-18 13:17:22 +00:00
fn apply_focus_changed(&mut self, window_id: WindowId, focused: Option<FocusId>) {
self.update_window(window_id, |cx| {
if cx.window.focus == focused {
2023-10-18 13:46:17 +00:00
let mut listeners = mem::take(&mut cx.window.focus_listeners);
2023-10-18 16:39:29 +00:00
let focused =
focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
2023-10-18 15:27:59 +00:00
let blurred = cx
.window
.last_blur
2023-10-18 16:39:29 +00:00
.take()
2023-10-18 15:27:59 +00:00
.unwrap()
2023-10-18 16:39:29 +00:00
.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
2023-10-18 17:30:53 +00:00
if focused.is_some() || blurred.is_some() {
let event = FocusEvent { focused, blurred };
for listener in &listeners {
listener(&event, cx);
}
2023-10-18 13:17:22 +00:00
}
2023-10-18 13:46:17 +00:00
listeners.extend(cx.window.focus_listeners.drain(..));
cx.window.focus_listeners = listeners;
2023-10-18 13:17:22 +00:00
}
})
.ok();
}
2023-10-21 17:07:59 +00:00
fn apply_refresh(&mut self) {
2023-10-19 17:47:50 +00:00
for window in self.windows.values_mut() {
if let Some(window) = window.as_mut() {
window.dirty = true;
}
}
}
2023-10-04 21:05:04 +00:00
pub fn to_async(&self) -> AsyncAppContext {
2023-10-22 14:27:23 +00:00
AsyncAppContext {
app: unsafe { mem::transmute(self.this.clone()) },
executor: self.executor.clone(),
}
2023-09-26 17:29:44 +00:00
}
2023-10-04 17:53:29 +00:00
pub fn executor(&self) -> &Executor {
&self.executor
}
2023-09-30 00:51:45 +00:00
pub fn run_on_main<R>(
2023-10-04 15:48:28 +00:00
&mut self,
2023-10-02 18:47:45 +00:00
f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
2023-10-04 17:59:24 +00:00
) -> Task<R>
2023-09-30 00:51:45 +00:00
where
R: Send + 'static,
{
2023-10-04 17:53:29 +00:00
if self.executor.is_main_thread() {
2023-10-04 17:59:24 +00:00
Task::ready(f(unsafe {
2023-10-04 15:48:28 +00:00
mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
2023-10-04 17:59:24 +00:00
}))
2023-10-04 15:48:28 +00:00
} else {
let this = self.this.upgrade().unwrap();
2023-10-04 17:59:24 +00:00
self.executor.run_on_main(move || {
let cx = &mut *this.lock();
cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
})
2023-10-04 15:48:28 +00:00
}
2023-09-30 00:51:45 +00:00
}
pub fn spawn_on_main<F, R>(
&self,
2023-10-02 18:47:45 +00:00
f: impl FnOnce(&mut MainThread<AppContext>) -> F + Send + 'static,
2023-10-04 17:53:29 +00:00
) -> Task<R>
2023-09-30 00:51:45 +00:00
where
2023-10-11 13:08:28 +00:00
F: Future<Output = R> + 'static,
2023-09-30 00:51:45 +00:00
R: Send + 'static,
{
let this = self.this.upgrade().unwrap();
2023-10-04 17:53:29 +00:00
self.executor.spawn_on_main(move || {
2023-09-30 00:51:45 +00:00
let cx = &mut *this.lock();
2023-10-02 18:47:45 +00:00
cx.update(|cx| {
f(unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) })
})
2023-09-30 00:51:45 +00:00
})
}
2023-10-04 21:05:04 +00:00
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
2023-10-04 18:09:55 +00:00
where
Fut: Future<Output = R> + Send + 'static,
R: Send + 'static,
{
2023-10-04 21:05:04 +00:00
let cx = self.to_async();
2023-10-04 18:09:55 +00:00
self.executor.spawn(async move {
2023-10-04 21:05:04 +00:00
let future = f(cx);
2023-10-04 18:09:55 +00:00
future.await
})
}
2023-10-02 18:47:45 +00:00
pub fn text_system(&self) -> &Arc<TextSystem> {
&self.text_system
}
2023-09-29 19:22:53 +00:00
pub fn text_style(&self) -> TextStyle {
let mut style = TextStyle::default();
for refinement in &self.text_style_stack {
style.refine(refinement);
}
style
}
2023-10-22 11:15:29 +00:00
pub fn has_global<G: 'static>(&self) -> bool {
self.global_stacks_by_type
.get(&TypeId::of::<G>())
.map_or(false, |stack| !stack.is_empty())
}
2023-10-11 23:18:33 +00:00
pub fn global<G: 'static>(&self) -> &G {
self.global_stacks_by_type
.get(&TypeId::of::<G>())
2023-09-29 19:22:53 +00:00
.and_then(|stack| stack.last())
2023-10-22 11:15:29 +00:00
.map(|any_state| any_state.downcast_ref::<G>().unwrap())
2023-10-11 23:18:33 +00:00
.ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
2023-09-29 19:22:53 +00:00
.unwrap()
}
2023-10-22 11:15:29 +00:00
pub fn try_global<G: 'static>(&self) -> Option<&G> {
self.global_stacks_by_type
.get(&TypeId::of::<G>())
.and_then(|stack| stack.last())
.map(|any_state| any_state.downcast_ref::<G>().unwrap())
}
2023-10-11 23:18:33 +00:00
pub fn global_mut<G: 'static>(&mut self) -> &mut G {
self.global_stacks_by_type
.get_mut(&TypeId::of::<G>())
2023-09-29 19:22:53 +00:00
.and_then(|stack| stack.last_mut())
2023-10-11 23:18:33 +00:00
.and_then(|any_state| any_state.downcast_mut::<G>())
.ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
2023-09-29 19:22:53 +00:00
.unwrap()
}
2023-10-11 23:18:33 +00:00
pub fn default_global<G: 'static + Default + Sync + Send>(&mut self) -> &mut G {
let stack = self
.global_stacks_by_type
.entry(TypeId::of::<G>())
.or_default();
if stack.is_empty() {
stack.push(Box::new(G::default()));
}
stack.last_mut().unwrap().downcast_mut::<G>().unwrap()
2023-09-29 19:22:53 +00:00
}
2023-10-21 15:52:47 +00:00
pub fn set_global<T: Send + Sync + 'static>(&mut self, global: T) {
let global = Box::new(global);
let stack = self
.global_stacks_by_type
.entry(TypeId::of::<T>())
.or_default();
if let Some(last) = stack.last_mut() {
*last = global;
} else {
stack.push(global)
}
}
2023-10-22 11:15:29 +00:00
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
where
G: 'static + Send + Sync,
{
let mut global = self
.global_stacks_by_type
.get_mut(&TypeId::of::<G>())
.and_then(|stack| stack.pop())
.ok_or_else(|| anyhow!("no state of type {} exists", type_name::<G>()))
.unwrap();
let result = f(global.downcast_mut().unwrap(), self);
self.global_stacks_by_type
.get_mut(&TypeId::of::<G>())
.unwrap()
.push(global);
result
}
2023-10-21 16:21:14 +00:00
pub(crate) fn push_global<T: Send + Sync + 'static>(&mut self, global: T) {
2023-10-11 23:18:33 +00:00
self.global_stacks_by_type
2023-09-29 19:22:53 +00:00
.entry(TypeId::of::<T>())
.or_default()
2023-10-21 16:21:14 +00:00
.push(Box::new(global));
2023-09-29 19:22:53 +00:00
}
2023-10-21 16:21:14 +00:00
pub(crate) fn pop_global<T: 'static>(&mut self) -> Box<T> {
2023-10-11 23:18:33 +00:00
self.global_stacks_by_type
2023-09-29 19:22:53 +00:00
.get_mut(&TypeId::of::<T>())
.and_then(|stack| stack.pop())
2023-10-21 16:21:14 +00:00
.expect("state stack underflow")
.downcast()
.unwrap()
2023-09-29 19:22:53 +00:00
}
2023-10-11 23:18:33 +00:00
pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
self.text_style_stack.push(text_style);
}
pub(crate) fn pop_text_style(&mut self) {
self.text_style_stack.pop();
}
2023-10-19 17:26:52 +00:00
pub fn bind_keys(&mut self, bindings: impl IntoIterator<Item = KeyBinding>) {
self.keymap.write().add_bindings(bindings);
2023-10-19 17:47:50 +00:00
self.push_effect(Effect::Refresh);
2023-10-19 17:26:52 +00:00
}
2023-10-21 15:52:47 +00:00
2023-10-22 10:21:28 +00:00
pub fn on_action<A: Action>(
&mut self,
listener: impl Fn(&A, &mut Self) + Send + Sync + 'static,
) {
self.global_action_listeners
.entry(TypeId::of::<A>())
.or_default()
.push(Box::new(move |action, phase, cx| {
if phase == DispatchPhase::Bubble {
let action = action.as_any().downcast_ref().unwrap();
listener(action, cx)
}
}));
}
2023-10-21 15:52:47 +00:00
pub fn register_action_type<A: Action>(&mut self) {
self.action_builders.insert(A::qualified_name(), A::build);
}
pub fn build_action(
&mut self,
name: &str,
params: Option<serde_json::Value>,
) -> Result<Box<dyn Action>> {
let build = self
.action_builders
.get(name)
.ok_or_else(|| anyhow!("no action type registered for {}", name))?;
(build)(params)
}
2023-10-22 10:21:28 +00:00
pub fn stop_propagation(&mut self) {
self.propagate_event = false;
}
2023-09-19 19:19:22 +00:00
}
impl Context for AppContext {
type EntityContext<'a, 'w, T: Send + Sync + 'static> = ModelContext<'a, T>;
2023-09-26 17:29:44 +00:00
type Result<T> = T;
2023-09-19 19:19:22 +00:00
2023-09-25 17:47:37 +00:00
fn entity<T: Send + Sync + 'static>(
2023-09-19 19:19:22 +00:00
&mut self,
build_entity: impl FnOnce(&mut Self::EntityContext<'_, '_, T>) -> T,
) -> Handle<T> {
2023-10-04 21:05:04 +00:00
self.update(|cx| {
let slot = cx.entities.reserve();
let entity = build_entity(&mut ModelContext::mutable(cx, slot.id));
cx.entities.insert(slot, entity)
})
2023-09-19 19:19:22 +00:00
}
2023-09-25 17:47:37 +00:00
fn update_entity<T: Send + Sync + 'static, R>(
2023-09-19 19:19:22 +00:00
&mut self,
handle: &Handle<T>,
update: impl FnOnce(&mut T, &mut Self::EntityContext<'_, '_, T>) -> R,
) -> R {
2023-10-04 21:05:04 +00:00
self.update(|cx| {
let mut entity = cx.entities.lease(handle);
let result = update(&mut entity, &mut ModelContext::mutable(cx, handle.id));
cx.entities.end_lease(entity);
result
})
2023-09-19 19:19:22 +00:00
}
}
2023-10-02 18:47:45 +00:00
impl MainThread<AppContext> {
fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
self.0.update(|cx| {
update(unsafe {
std::mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx)
})
})
}
2023-10-02 19:34:07 +00:00
pub(crate) fn update_window<R>(
&mut self,
id: WindowId,
2023-10-04 15:48:28 +00:00
update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
2023-10-02 19:34:07 +00:00
) -> Result<R> {
self.0.update_window(id, |cx| {
update(unsafe {
std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
})
})
}
2023-09-30 00:51:45 +00:00
pub(crate) fn platform(&self) -> &dyn Platform {
2023-09-29 20:34:40 +00:00
self.platform.borrow_on_main_thread()
2023-09-29 20:04:58 +00:00
}
2023-10-22 14:27:23 +00:00
pub fn activate(&self, ignoring_other_apps: bool) {
2023-09-29 20:34:40 +00:00
self.platform().activate(ignoring_other_apps);
2023-09-29 20:04:58 +00:00
}
2023-10-22 10:21:28 +00:00
pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
self.platform().write_credentials(url, username, password)
}
pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
self.platform().read_credentials(url)
}
pub fn delete_credentials(&self, url: &str) -> Result<()> {
self.platform().delete_credentials(url)
}
2023-10-22 14:27:23 +00:00
pub fn open_url(&self, url: &str) {
self.platform().open_url(url);
}
2023-09-29 20:04:58 +00:00
pub fn open_window<S: 'static + Send + Sync>(
&mut self,
options: crate::WindowOptions,
2023-10-12 17:30:00 +00:00
build_root_view: impl FnOnce(&mut WindowContext) -> View<S> + Send + 'static,
2023-09-29 20:04:58 +00:00
) -> WindowHandle<S> {
2023-09-30 16:01:59 +00:00
self.update(|cx| {
let id = cx.windows.insert(None);
let handle = WindowHandle::new(id);
let mut window = Window::new(handle.into(), options, cx);
2023-10-02 18:47:45 +00:00
let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
2023-09-30 16:01:59 +00:00
window.root_view.replace(root_view.into_any());
cx.windows.get_mut(id).unwrap().replace(window);
handle
})
2023-09-29 20:04:58 +00:00
}
2023-10-22 11:15:29 +00:00
pub fn update_global<G: 'static + Send + Sync, R>(
&mut self,
update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
) -> R {
self.0.update_global(|global, cx| {
let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
update(global, cx)
})
}
2023-09-29 20:04:58 +00:00
}
2023-09-25 17:47:37 +00:00
pub(crate) enum Effect {
2023-10-12 11:25:49 +00:00
Notify {
emitter: EntityId,
},
2023-10-11 08:45:57 +00:00
Emit {
2023-10-12 11:25:49 +00:00
emitter: EntityId,
2023-10-11 08:45:57 +00:00
event: Box<dyn Any + Send + Sync + 'static>,
},
2023-10-18 13:17:22 +00:00
FocusChanged {
window_id: WindowId,
focused: Option<FocusId>,
},
2023-10-19 17:47:50 +00:00
Refresh,
2023-09-25 17:47:37 +00:00
}
#[cfg(test)]
mod tests {
use super::AppContext;
#[test]
fn test_app_context_send_sync() {
// This will not compile if `AppContext` does not implement `Send`
fn assert_send<T: Send>() {}
assert_send::<AppContext>();
}
}