Start removing the Send impl for App

Co-authored-by: Antonio <antonio@zed.dev>
Co-authored-by: Nathan <nathan@zed.dev>
This commit is contained in:
Max Brunsfeld 2023-11-01 11:31:23 -07:00 committed by Nathan Sobo
parent ea7fdef417
commit 57ffa8201e
38 changed files with 506 additions and 932 deletions

View file

@ -14,8 +14,8 @@ pub use test_context::*;
use crate::{
current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource,
ClipboardItem, Context, DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId,
KeyBinding, Keymap, LayoutId, MainThread, MainThreadOnly, Pixels, Platform, Point, Render,
BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId, FocusEvent, FocusHandle,
FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId, Pixels, Platform, Point, Render,
SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,
TextSystem, View, Window, WindowContext, WindowHandle, WindowId,
};
@ -26,17 +26,18 @@ use parking_lot::Mutex;
use slotmap::SlotMap;
use std::{
any::{type_name, Any, TypeId},
borrow::Borrow,
cell::RefCell,
marker::PhantomData,
mem,
ops::{Deref, DerefMut},
path::PathBuf,
sync::{atomic::Ordering::SeqCst, Arc, Weak},
rc::{Rc, Weak},
sync::{atomic::Ordering::SeqCst, Arc},
time::Duration,
};
use util::http::{self, HttpClient};
pub struct App(Arc<Mutex<AppContext>>);
pub struct App(Rc<RefCell<AppContext>>);
/// Represents an application before it is fully launched. Once your app is
/// configured, you'll start the app with `App::run`.
@ -54,13 +55,12 @@ impl App {
/// app is fully launched.
pub fn run<F>(self, on_finish_launching: F)
where
F: 'static + FnOnce(&mut MainThread<AppContext>),
F: 'static + FnOnce(&mut AppContext),
{
let this = self.0.clone();
let platform = self.0.lock().platform.clone();
platform.borrow_on_main_thread().run(Box::new(move || {
let cx = &mut *this.lock();
let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
let platform = self.0.borrow().platform.clone();
platform.run(Box::new(move || {
let cx = &mut *this.borrow_mut();
on_finish_launching(cx);
}));
}
@ -71,16 +71,12 @@ impl App {
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());
}
}));
let this = Rc::downgrade(&self.0);
self.0.borrow().platform.on_open_urls(Box::new(move |urls| {
if let Some(app) = this.upgrade() {
callback(urls, &mut *app.borrow_mut());
}
}));
self
}
@ -88,29 +84,25 @@ impl App {
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());
}
}));
let this = Rc::downgrade(&self.0);
self.0.borrow_mut().platform.on_reopen(Box::new(move || {
if let Some(app) = this.upgrade() {
callback(&mut app.borrow_mut());
}
}));
self
}
pub fn metadata(&self) -> AppMetadata {
self.0.lock().app_metadata.clone()
self.0.borrow().app_metadata.clone()
}
pub fn executor(&self) -> Executor {
self.0.lock().executor.clone()
pub fn background_executor(&self) -> BackgroundExecutor {
self.0.borrow().background_executor.clone()
}
pub fn text_system(&self) -> Arc<TextSystem> {
self.0.lock().text_system.clone()
self.0.borrow().text_system.clone()
}
}
@ -122,15 +114,16 @@ type QuitHandler = Box<dyn FnMut(&mut AppContext) -> BoxFuture<'static, ()> + Se
type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + Send + 'static>;
pub struct AppContext {
this: Weak<Mutex<AppContext>>,
pub(crate) platform: MainThreadOnly<dyn Platform>,
this: Weak<RefCell<AppContext>>,
pub(crate) platform: Rc<dyn Platform>,
app_metadata: AppMetadata,
text_system: Arc<TextSystem>,
flushing_effects: bool,
pending_updates: usize,
pub(crate) active_drag: Option<AnyDrag>,
pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>,
pub(crate) executor: Executor,
pub(crate) background_executor: BackgroundExecutor,
pub(crate) foreground_executor: ForegroundExecutor,
pub(crate) svg_renderer: SvgRenderer,
asset_source: Arc<dyn AssetSource>,
pub(crate) image_cache: ImageCache,
@ -156,11 +149,12 @@ pub struct AppContext {
impl AppContext {
pub(crate) fn new(
platform: Arc<dyn Platform>,
platform: Rc<dyn Platform>,
asset_source: Arc<dyn AssetSource>,
http_client: Arc<dyn HttpClient>,
) -> Arc<Mutex<Self>> {
let executor = platform.executor();
) -> Rc<RefCell<Self>> {
let executor = platform.background_executor();
let foreground_executor = platform.foreground_executor();
assert!(
executor.is_main_thread(),
"must construct App on main thread"
@ -175,16 +169,17 @@ impl AppContext {
app_version: platform.app_version().ok(),
};
Arc::new_cyclic(|this| {
Mutex::new(AppContext {
Rc::new_cyclic(|this| {
RefCell::new(AppContext {
this: this.clone(),
text_system,
platform: MainThreadOnly::new(platform, executor.clone()),
platform,
app_metadata,
flushing_effects: false,
pending_updates: 0,
next_frame_callbacks: Default::default(),
executor,
background_executor: executor,
foreground_executor,
svg_renderer: SvgRenderer::new(asset_source.clone()),
asset_source,
image_cache: ImageCache::new(http_client),
@ -225,7 +220,7 @@ impl AppContext {
let futures = futures::future::join_all(futures);
if self
.executor
.background_executor
.block_with_timeout(Duration::from_millis(100), futures)
.is_err()
{
@ -244,7 +239,6 @@ impl AppContext {
pub fn refresh(&mut self) {
self.pending_effects.push_back(Effect::Refresh);
}
pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
self.pending_updates += 1;
let result = update(self);
@ -258,7 +252,7 @@ impl AppContext {
}
pub(crate) fn read_window<R>(
&mut self,
&self,
id: WindowId,
read: impl FnOnce(&WindowContext) -> R,
) -> Result<R> {
@ -295,6 +289,68 @@ impl AppContext {
})
}
/// Opens a new window with the given option and the root view returned by the given function.
/// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
/// functionality.
pub fn open_window<V: Render>(
&mut self,
options: crate::WindowOptions,
build_root_view: impl FnOnce(&mut WindowContext) -> View<V> + Send + 'static,
) -> WindowHandle<V> {
self.update(|cx| {
let id = cx.windows.insert(None);
let handle = WindowHandle::new(id);
let mut window = Window::new(handle.into(), options, cx);
let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
window.root_view.replace(root_view.into());
cx.windows.get_mut(id).unwrap().replace(window);
handle
})
}
pub(crate) fn platform(&self) -> &Rc<dyn Platform> {
&self.platform
}
/// Instructs the platform to activate the application by bringing it to the foreground.
pub fn activate(&self, ignoring_other_apps: bool) {
self.platform().activate(ignoring_other_apps);
}
/// Writes data to the platform clipboard.
pub fn write_to_clipboard(&self, item: ClipboardItem) {
self.platform().write_to_clipboard(item)
}
/// Reads data from the platform clipboard.
pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
self.platform().read_from_clipboard()
}
/// Writes credentials to the platform keychain.
pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
self.platform().write_credentials(url, username, password)
}
/// Reads credentials from the platform keychain.
pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
self.platform().read_credentials(url)
}
/// Deletes credentials from the platform keychain.
pub fn delete_credentials(&self, url: &str) -> Result<()> {
self.platform().delete_credentials(url)
}
/// Directs the platform's default browser to open the given URL.
pub fn open_url(&self, url: &str) {
self.platform().open_url(url);
}
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
self.platform().path_for_auxiliary_executable(name)
}
pub(crate) fn push_effect(&mut self, effect: Effect) {
match &effect {
Effect::Notify { emitter } => {
@ -473,67 +529,24 @@ impl AppContext {
pub fn to_async(&self) -> AsyncAppContext {
AsyncAppContext {
app: unsafe { mem::transmute(self.this.clone()) },
executor: self.executor.clone(),
background_executor: self.background_executor.clone(),
foreground_executor: self.foreground_executor.clone(),
}
}
/// Obtains a reference to the executor, which can be used to spawn futures.
pub fn executor(&self) -> &Executor {
&self.executor
}
/// Runs the given closure on the main thread, where interaction with the platform
/// is possible. The given closure will be invoked with a `MainThread<AppContext>`, which
/// has platform-specific methods that aren't present on `AppContext`.
pub fn run_on_main<R>(
&mut self,
f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
) -> Task<R>
where
R: Send + 'static,
{
if self.executor.is_main_thread() {
Task::ready(f(unsafe {
mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(self)
}))
} else {
let this = self.this.upgrade().unwrap();
self.executor.run_on_main(move || {
let cx = &mut *this.lock();
cx.update(|cx| f(unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(cx) }))
})
}
}
/// Spawns the future returned by the given function on the main thread, where interaction with
/// the platform is possible. The given closure will be invoked with a `MainThread<AsyncAppContext>`,
/// which has platform-specific methods that aren't present on `AsyncAppContext`. The future will be
/// polled exclusively on the main thread.
// todo!("I think we need somehow to prevent the MainThread<AsyncAppContext> from implementing Send")
pub fn spawn_on_main<F, R>(
&self,
f: impl FnOnce(MainThread<AsyncAppContext>) -> F + Send + 'static,
) -> Task<R>
where
F: Future<Output = R> + 'static,
R: Send + 'static,
{
let cx = self.to_async();
self.executor.spawn_on_main(move || f(MainThread(cx)))
pub fn executor(&self) -> &BackgroundExecutor {
&self.background_executor
}
/// Spawns the future returned by the given function on the thread pool. The closure will be invoked
/// with AsyncAppContext, which allows the application state to be accessed across await points.
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
where
Fut: Future<Output = R> + Send + 'static,
R: Send + 'static,
Fut: Future<Output = R> + 'static,
R: 'static,
{
let cx = self.to_async();
self.executor.spawn(async move {
let future = f(cx);
future.await
})
self.foreground_executor.spawn(f(self.to_async()))
}
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities
@ -597,7 +610,7 @@ impl AppContext {
/// Access the global of the given type mutably. A default value is assigned if a global of this type has not
/// yet been assigned.
pub fn default_global<G: 'static + Default + Send>(&mut self) -> &mut G {
pub fn default_global<G: 'static + Default>(&mut self) -> &mut G {
let global_type = TypeId::of::<G>();
self.push_effect(Effect::NotifyGlobalObservers { global_type });
self.globals_by_type
@ -608,7 +621,7 @@ impl AppContext {
}
/// Set the value of the global of the given type.
pub fn set_global<G: Any + Send>(&mut self, global: G) {
pub fn set_global<G: Any>(&mut self, global: G) {
let global_type = TypeId::of::<G>();
self.push_effect(Effect::NotifyGlobalObservers { global_type });
self.globals_by_type.insert(global_type, Box::new(global));
@ -717,7 +730,7 @@ impl Context for AppContext {
/// Build an entity that is owned by the application. The given function will be invoked with
/// a `ModelContext` and must return an object representing the entity. A `Model` will be returned
/// which can be used to access the entity in a context.
fn build_model<T: 'static + Send>(
fn build_model<T: 'static>(
&mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Model<T> {
@ -747,107 +760,6 @@ impl Context for AppContext {
}
}
impl<C> MainThread<C>
where
C: Borrow<AppContext>,
{
pub(crate) fn platform(&self) -> &dyn Platform {
self.0.borrow().platform.borrow_on_main_thread()
}
/// Instructs the platform to activate the application by bringing it to the foreground.
pub fn activate(&self, ignoring_other_apps: bool) {
self.platform().activate(ignoring_other_apps);
}
/// Writes data to the platform clipboard.
pub fn write_to_clipboard(&self, item: ClipboardItem) {
self.platform().write_to_clipboard(item)
}
/// Reads data from the platform clipboard.
pub fn read_from_clipboard(&self) -> Option<ClipboardItem> {
self.platform().read_from_clipboard()
}
/// Writes credentials to the platform keychain.
pub fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Result<()> {
self.platform().write_credentials(url, username, password)
}
/// Reads credentials from the platform keychain.
pub fn read_credentials(&self, url: &str) -> Result<Option<(String, Vec<u8>)>> {
self.platform().read_credentials(url)
}
/// Deletes credentials from the platform keychain.
pub fn delete_credentials(&self, url: &str) -> Result<()> {
self.platform().delete_credentials(url)
}
/// Directs the platform's default browser to open the given URL.
pub fn open_url(&self, url: &str) {
self.platform().open_url(url);
}
pub fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
self.platform().path_for_auxiliary_executable(name)
}
}
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)
})
})
}
pub(crate) fn update_window<R>(
&mut self,
id: WindowId,
update: impl FnOnce(&mut MainThread<WindowContext>) -> R,
) -> Result<R> {
self.0.update_window(id, |cx| {
update(unsafe {
std::mem::transmute::<&mut WindowContext, &mut MainThread<WindowContext>>(cx)
})
})
}
/// Opens a new window with the given option and the root view returned by the given function.
/// The function is invoked with a `WindowContext`, which can be used to interact with window-specific
/// functionality.
pub fn open_window<V: Render>(
&mut self,
options: crate::WindowOptions,
build_root_view: impl FnOnce(&mut WindowContext) -> View<V> + Send + 'static,
) -> WindowHandle<V> {
self.update(|cx| {
let id = cx.windows.insert(None);
let handle = WindowHandle::new(id);
let mut window = Window::new(handle.into(), options, cx);
let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
window.root_view.replace(root_view.into());
cx.windows.get_mut(id).unwrap().replace(window);
handle
})
}
/// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
/// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.
pub fn update_global<G: 'static + Send, 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)
})
}
}
/// These effects are processed at the end of each application update cycle.
pub(crate) enum Effect {
Notify {
@ -855,7 +767,7 @@ pub(crate) enum Effect {
},
Emit {
emitter: EntityId,
event: Box<dyn Any + Send + 'static>,
event: Box<dyn Any>,
},
FocusChanged {
window_id: WindowId,
@ -905,15 +817,3 @@ pub(crate) struct AnyDrag {
pub view: AnyView,
pub cursor_offset: Point<Pixels>,
}
#[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>();
}
}