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

@ -4,7 +4,7 @@ use futures::{
future::BoxFuture, io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, FutureExt, future::BoxFuture, io::BufReader, stream::BoxStream, AsyncBufReadExt, AsyncReadExt, FutureExt,
Stream, StreamExt, Stream, StreamExt,
}; };
use gpui2::{AppContext, Executor}; use gpui2::{AppContext, BackgroundExecutor};
use isahc::{http::StatusCode, Request, RequestExt}; use isahc::{http::StatusCode, Request, RequestExt};
use parking_lot::RwLock; use parking_lot::RwLock;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -105,7 +105,7 @@ pub struct OpenAIResponseStreamEvent {
pub async fn stream_completion( pub async fn stream_completion(
credential: ProviderCredential, credential: ProviderCredential,
executor: Arc<Executor>, executor: Arc<BackgroundExecutor>,
request: Box<dyn CompletionRequest>, request: Box<dyn CompletionRequest>,
) -> Result<impl Stream<Item = Result<OpenAIResponseStreamEvent>>> { ) -> Result<impl Stream<Item = Result<OpenAIResponseStreamEvent>>> {
let api_key = match credential { let api_key = match credential {
@ -198,11 +198,11 @@ pub async fn stream_completion(
pub struct OpenAICompletionProvider { pub struct OpenAICompletionProvider {
model: OpenAILanguageModel, model: OpenAILanguageModel,
credential: Arc<RwLock<ProviderCredential>>, credential: Arc<RwLock<ProviderCredential>>,
executor: Arc<Executor>, executor: Arc<BackgroundExecutor>,
} }
impl OpenAICompletionProvider { impl OpenAICompletionProvider {
pub fn new(model_name: &str, executor: Arc<Executor>) -> Self { pub fn new(model_name: &str, executor: Arc<BackgroundExecutor>) -> Self {
let model = OpenAILanguageModel::load(model_name); let model = OpenAILanguageModel::load(model_name);
let credential = Arc::new(RwLock::new(ProviderCredential::NoCredentials)); let credential = Arc::new(RwLock::new(ProviderCredential::NoCredentials));
Self { Self {

View file

@ -1,7 +1,7 @@
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use async_trait::async_trait; use async_trait::async_trait;
use futures::AsyncReadExt; use futures::AsyncReadExt;
use gpui2::Executor; use gpui2::BackgroundExecutor;
use gpui2::{serde_json, AppContext}; use gpui2::{serde_json, AppContext};
use isahc::http::StatusCode; use isahc::http::StatusCode;
use isahc::prelude::Configurable; use isahc::prelude::Configurable;
@ -35,7 +35,7 @@ pub struct OpenAIEmbeddingProvider {
model: OpenAILanguageModel, model: OpenAILanguageModel,
credential: Arc<RwLock<ProviderCredential>>, credential: Arc<RwLock<ProviderCredential>>,
pub client: Arc<dyn HttpClient>, pub client: Arc<dyn HttpClient>,
pub executor: Arc<Executor>, pub executor: Arc<BackgroundExecutor>,
rate_limit_count_rx: watch::Receiver<Option<Instant>>, rate_limit_count_rx: watch::Receiver<Option<Instant>>,
rate_limit_count_tx: Arc<Mutex<watch::Sender<Option<Instant>>>>, rate_limit_count_tx: Arc<Mutex<watch::Sender<Option<Instant>>>>,
} }
@ -66,7 +66,7 @@ struct OpenAIEmbeddingUsage {
} }
impl OpenAIEmbeddingProvider { impl OpenAIEmbeddingProvider {
pub fn new(client: Arc<dyn HttpClient>, executor: Arc<Executor>) -> Self { pub fn new(client: Arc<dyn HttpClient>, executor: Arc<BackgroundExecutor>) -> Self {
let (rate_limit_count_tx, rate_limit_count_rx) = watch::channel_with(None); let (rate_limit_count_tx, rate_limit_count_rx) = watch::channel_with(None);
let rate_limit_count_tx = Arc::new(Mutex::new(rate_limit_count_tx)); let rate_limit_count_tx = Arc::new(Mutex::new(rate_limit_count_tx));

View file

@ -1,6 +1,6 @@
use assets::SoundRegistry; use assets::SoundRegistry;
use futures::{channel::mpsc, StreamExt}; use futures::{channel::mpsc, StreamExt};
use gpui2::{AppContext, AssetSource, Executor}; use gpui2::{AppContext, AssetSource, BackgroundExecutor};
use rodio::{OutputStream, OutputStreamHandle}; use rodio::{OutputStream, OutputStreamHandle};
use util::ResultExt; use util::ResultExt;
@ -34,7 +34,7 @@ impl Sound {
} }
pub struct Audio { pub struct Audio {
tx: mpsc::UnboundedSender<Box<dyn FnOnce(&mut AudioState) + Send>>, tx: mpsc::UnboundedSender<Box<dyn FnOnce(&mut AudioState)>>,
} }
struct AudioState { struct AudioState {
@ -60,8 +60,8 @@ impl AudioState {
} }
impl Audio { impl Audio {
pub fn new(executor: &Executor) -> Self { pub fn new(executor: &BackgroundExecutor) -> Self {
let (tx, mut rx) = mpsc::unbounded::<Box<dyn FnOnce(&mut AudioState) + Send>>(); let (tx, mut rx) = mpsc::unbounded::<Box<dyn FnOnce(&mut AudioState)>>();
executor executor
.spawn_on_main(|| async move { .spawn_on_main(|| async move {
let mut audio = AudioState { let mut audio = AudioState {

View file

@ -445,7 +445,8 @@ impl Room {
// Wait for client to re-establish a connection to the server. // Wait for client to re-establish a connection to the server.
{ {
let mut reconnection_timeout = cx.executor().timer(RECONNECT_TIMEOUT).fuse(); let mut reconnection_timeout =
cx.background_executor().timer(RECONNECT_TIMEOUT).fuse();
let client_reconnection = async { let client_reconnection = async {
let mut remaining_attempts = 3; let mut remaining_attempts = 3;
while remaining_attempts > 0 { while remaining_attempts > 0 {

View file

@ -505,7 +505,7 @@ impl Client {
}, },
&cx, &cx,
); );
cx.executor().timer(delay).await; cx.background_executor().timer(delay).await;
delay = delay delay = delay
.mul_f32(rng.gen_range(1.0..=2.0)) .mul_f32(rng.gen_range(1.0..=2.0))
.min(reconnect_interval); .min(reconnect_interval);
@ -763,7 +763,8 @@ impl Client {
self.set_status(Status::Reconnecting, cx); self.set_status(Status::Reconnecting, cx);
} }
let mut timeout = futures::FutureExt::fuse(cx.executor().timer(CONNECTION_TIMEOUT)); let mut timeout =
futures::FutureExt::fuse(cx.background_executor().timer(CONNECTION_TIMEOUT));
futures::select_biased! { futures::select_biased! {
connection = self.establish_connection(&credentials, cx).fuse() => { connection = self.establish_connection(&credentials, cx).fuse() => {
match connection { match connection {
@ -814,7 +815,7 @@ impl Client {
conn: Connection, conn: Connection,
cx: &AsyncAppContext, cx: &AsyncAppContext,
) -> Result<()> { ) -> Result<()> {
let executor = cx.executor(); let executor = cx.background_executor();
log::info!("add connection to peer"); log::info!("add connection to peer");
let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, { let (connection_id, handle_io, mut incoming) = self.peer.add_connection(conn, {
let executor = executor.clone(); let executor = executor.clone();
@ -978,7 +979,7 @@ impl Client {
.header("x-zed-protocol-version", rpc2::PROTOCOL_VERSION); .header("x-zed-protocol-version", rpc2::PROTOCOL_VERSION);
let http = self.http.clone(); let http = self.http.clone();
cx.executor().spawn(async move { cx.background_executor().spawn(async move {
let mut rpc_url = Self::get_rpc_url(http, use_preview_server).await?; let mut rpc_url = Self::get_rpc_url(http, use_preview_server).await?;
let rpc_host = rpc_url let rpc_host = rpc_url
.host_str() .host_str()
@ -1382,7 +1383,7 @@ mod tests {
use super::*; use super::*;
use crate::test::FakeServer; use crate::test::FakeServer;
use gpui2::{Context, Executor, TestAppContext}; use gpui2::{BackgroundExecutor, Context, TestAppContext};
use parking_lot::Mutex; use parking_lot::Mutex;
use std::future; use std::future;
use util::http::FakeHttpClient; use util::http::FakeHttpClient;
@ -1422,7 +1423,7 @@ mod tests {
} }
#[gpui2::test(iterations = 10)] #[gpui2::test(iterations = 10)]
async fn test_connection_timeout(executor: Executor, cx: &mut TestAppContext) { async fn test_connection_timeout(executor: BackgroundExecutor, cx: &mut TestAppContext) {
let user_id = 5; let user_id = 5;
let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx)); let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));
let mut status = client.status(); let mut status = client.status();
@ -1490,7 +1491,10 @@ mod tests {
} }
#[gpui2::test(iterations = 10)] #[gpui2::test(iterations = 10)]
async fn test_authenticating_more_than_once(cx: &mut TestAppContext, executor: Executor) { async fn test_authenticating_more_than_once(
cx: &mut TestAppContext,
executor: BackgroundExecutor,
) {
let auth_count = Arc::new(Mutex::new(0)); let auth_count = Arc::new(Mutex::new(0));
let dropped_auth_count = Arc::new(Mutex::new(0)); let dropped_auth_count = Arc::new(Mutex::new(0));
let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx)); let client = cx.update(|cx| Client::new(FakeHttpClient::with_404_response(), cx));

View file

@ -1,7 +1,7 @@
use crate::{Client, Connection, Credentials, EstablishConnectionError, UserStore}; use crate::{Client, Connection, Credentials, EstablishConnectionError, UserStore};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use futures::{stream::BoxStream, StreamExt}; use futures::{stream::BoxStream, StreamExt};
use gpui2::{Context, Executor, Model, TestAppContext}; use gpui2::{BackgroundExecutor, Context, Model, TestAppContext};
use parking_lot::Mutex; use parking_lot::Mutex;
use rpc2::{ use rpc2::{
proto::{self, GetPrivateUserInfo, GetPrivateUserInfoResponse}, proto::{self, GetPrivateUserInfo, GetPrivateUserInfoResponse},
@ -14,7 +14,7 @@ pub struct FakeServer {
peer: Arc<Peer>, peer: Arc<Peer>,
state: Arc<Mutex<FakeServerState>>, state: Arc<Mutex<FakeServerState>>,
user_id: u64, user_id: u64,
executor: Executor, executor: BackgroundExecutor,
} }
#[derive(Default)] #[derive(Default)]
@ -79,10 +79,10 @@ impl FakeServer {
} }
let (client_conn, server_conn, _) = let (client_conn, server_conn, _) =
Connection::in_memory(cx.executor().clone()); Connection::in_memory(cx.background_executor().clone());
let (connection_id, io, incoming) = let (connection_id, io, incoming) =
peer.add_test_connection(server_conn, cx.executor().clone()); peer.add_test_connection(server_conn, cx.background_executor().clone());
cx.executor().spawn(io).detach(); cx.background_executor().spawn(io).detach();
{ {
let mut state = state.lock(); let mut state = state.lock();
state.connection_id = Some(connection_id); state.connection_id = Some(connection_id);

View file

@ -208,7 +208,7 @@ impl RegisteredBuffer {
let new_snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot()).ok()?; let new_snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot()).ok()?;
let content_changes = cx let content_changes = cx
.executor() .background_executor()
.spawn({ .spawn({
let new_snapshot = new_snapshot.clone(); let new_snapshot = new_snapshot.clone();
async move { async move {

View file

@ -266,9 +266,9 @@ impl<'a> EditorLspTestContext<'a> {
) -> futures::channel::mpsc::UnboundedReceiver<()> ) -> futures::channel::mpsc::UnboundedReceiver<()>
where where
T: 'static + request::Request, T: 'static + request::Request,
T::Params: 'static + Send, T::Params: 'static,
F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut, F: 'static + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
Fut: 'static + Send + Future<Output = Result<T::Result>>, Fut: 'static + Future<Output = Result<T::Result>>,
{ {
let url = self.buffer_lsp_url.clone(); let url = self.buffer_lsp_url.clone();
self.lsp.handle_request::<T, _, _>(move |params, cx| { self.lsp.handle_request::<T, _, _>(move |params, cx| {

View file

@ -288,7 +288,7 @@ impl Fs for RealFs {
pub struct FakeFs { pub struct FakeFs {
// Use an unfair lock to ensure tests are deterministic. // Use an unfair lock to ensure tests are deterministic.
state: Mutex<FakeFsState>, state: Mutex<FakeFsState>,
executor: gpui2::Executor, executor: gpui2::BackgroundExecutor,
} }
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
@ -434,7 +434,7 @@ lazy_static::lazy_static! {
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
impl FakeFs { impl FakeFs {
pub fn new(executor: gpui2::Executor) -> Arc<Self> { pub fn new(executor: gpui2::BackgroundExecutor) -> Arc<Self> {
Arc::new(Self { Arc::new(Self {
executor, executor,
state: Mutex::new(FakeFsState { state: Mutex::new(FakeFsState {
@ -1222,11 +1222,11 @@ pub fn copy_recursive<'a>(
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use gpui2::Executor; use gpui2::BackgroundExecutor;
use serde_json::json; use serde_json::json;
#[gpui2::test] #[gpui2::test]
async fn test_fake_fs(executor: Executor) { async fn test_fake_fs(executor: BackgroundExecutor) {
let fs = FakeFs::new(executor.clone()); let fs = FakeFs::new(executor.clone());
fs.insert_tree( fs.insert_tree(
"/root", "/root",

View file

@ -1,4 +1,4 @@
use gpui2::Executor; use gpui2::BackgroundExecutor;
use std::{ use std::{
borrow::Cow, borrow::Cow,
cmp::{self, Ordering}, cmp::{self, Ordering},
@ -134,7 +134,7 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>(
smart_case: bool, smart_case: bool,
max_results: usize, max_results: usize,
cancel_flag: &AtomicBool, cancel_flag: &AtomicBool,
executor: Executor, executor: BackgroundExecutor,
) -> Vec<PathMatch> { ) -> Vec<PathMatch> {
let path_count: usize = candidate_sets.iter().map(|s| s.len()).sum(); let path_count: usize = candidate_sets.iter().map(|s| s.len()).sum();
if path_count == 0 { if path_count == 0 {

View file

@ -14,8 +14,8 @@ pub use test_context::*;
use crate::{ use crate::{
current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource, current_platform, image_cache::ImageCache, Action, AnyBox, AnyView, AppMetadata, AssetSource,
ClipboardItem, Context, DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId, FocusEvent, FocusHandle,
KeyBinding, Keymap, LayoutId, MainThread, MainThreadOnly, Pixels, Platform, Point, Render, FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId, Pixels, Platform, Point, Render,
SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,
TextSystem, View, Window, WindowContext, WindowHandle, WindowId, TextSystem, View, Window, WindowContext, WindowHandle, WindowId,
}; };
@ -26,17 +26,18 @@ use parking_lot::Mutex;
use slotmap::SlotMap; use slotmap::SlotMap;
use std::{ use std::{
any::{type_name, Any, TypeId}, any::{type_name, Any, TypeId},
borrow::Borrow, cell::RefCell,
marker::PhantomData, marker::PhantomData,
mem, mem,
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
path::PathBuf, path::PathBuf,
sync::{atomic::Ordering::SeqCst, Arc, Weak}, rc::{Rc, Weak},
sync::{atomic::Ordering::SeqCst, Arc},
time::Duration, time::Duration,
}; };
use util::http::{self, HttpClient}; 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 /// Represents an application before it is fully launched. Once your app is
/// configured, you'll start the app with `App::run`. /// configured, you'll start the app with `App::run`.
@ -54,13 +55,12 @@ impl App {
/// app is fully launched. /// app is fully launched.
pub fn run<F>(self, on_finish_launching: F) pub fn run<F>(self, on_finish_launching: F)
where where
F: 'static + FnOnce(&mut MainThread<AppContext>), F: 'static + FnOnce(&mut AppContext),
{ {
let this = self.0.clone(); let this = self.0.clone();
let platform = self.0.lock().platform.clone(); let platform = self.0.borrow().platform.clone();
platform.borrow_on_main_thread().run(Box::new(move || { platform.run(Box::new(move || {
let cx = &mut *this.lock(); let cx = &mut *this.borrow_mut();
let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
on_finish_launching(cx); on_finish_launching(cx);
})); }));
} }
@ -71,16 +71,12 @@ impl App {
where where
F: 'static + FnMut(Vec<String>, &mut AppContext), F: 'static + FnMut(Vec<String>, &mut AppContext),
{ {
let this = Arc::downgrade(&self.0); let this = Rc::downgrade(&self.0);
self.0 self.0.borrow().platform.on_open_urls(Box::new(move |urls| {
.lock() if let Some(app) = this.upgrade() {
.platform callback(urls, &mut *app.borrow_mut());
.borrow_on_main_thread() }
.on_open_urls(Box::new(move |urls| { }));
if let Some(app) = this.upgrade() {
callback(urls, &mut app.lock());
}
}));
self self
} }
@ -88,29 +84,25 @@ impl App {
where where
F: 'static + FnMut(&mut AppContext), F: 'static + FnMut(&mut AppContext),
{ {
let this = Arc::downgrade(&self.0); let this = Rc::downgrade(&self.0);
self.0 self.0.borrow_mut().platform.on_reopen(Box::new(move || {
.lock() if let Some(app) = this.upgrade() {
.platform callback(&mut app.borrow_mut());
.borrow_on_main_thread() }
.on_reopen(Box::new(move || { }));
if let Some(app) = this.upgrade() {
callback(&mut app.lock());
}
}));
self self
} }
pub fn metadata(&self) -> AppMetadata { pub fn metadata(&self) -> AppMetadata {
self.0.lock().app_metadata.clone() self.0.borrow().app_metadata.clone()
} }
pub fn executor(&self) -> Executor { pub fn background_executor(&self) -> BackgroundExecutor {
self.0.lock().executor.clone() self.0.borrow().background_executor.clone()
} }
pub fn text_system(&self) -> Arc<TextSystem> { 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>; type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + Send + 'static>;
pub struct AppContext { pub struct AppContext {
this: Weak<Mutex<AppContext>>, this: Weak<RefCell<AppContext>>,
pub(crate) platform: MainThreadOnly<dyn Platform>, pub(crate) platform: Rc<dyn Platform>,
app_metadata: AppMetadata, app_metadata: AppMetadata,
text_system: Arc<TextSystem>, text_system: Arc<TextSystem>,
flushing_effects: bool, flushing_effects: bool,
pending_updates: usize, pending_updates: usize,
pub(crate) active_drag: Option<AnyDrag>, pub(crate) active_drag: Option<AnyDrag>,
pub(crate) next_frame_callbacks: HashMap<DisplayId, Vec<FrameCallback>>, 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, pub(crate) svg_renderer: SvgRenderer,
asset_source: Arc<dyn AssetSource>, asset_source: Arc<dyn AssetSource>,
pub(crate) image_cache: ImageCache, pub(crate) image_cache: ImageCache,
@ -156,11 +149,12 @@ pub struct AppContext {
impl AppContext { impl AppContext {
pub(crate) fn new( pub(crate) fn new(
platform: Arc<dyn Platform>, platform: Rc<dyn Platform>,
asset_source: Arc<dyn AssetSource>, asset_source: Arc<dyn AssetSource>,
http_client: Arc<dyn HttpClient>, http_client: Arc<dyn HttpClient>,
) -> Arc<Mutex<Self>> { ) -> Rc<RefCell<Self>> {
let executor = platform.executor(); let executor = platform.background_executor();
let foreground_executor = platform.foreground_executor();
assert!( assert!(
executor.is_main_thread(), executor.is_main_thread(),
"must construct App on main thread" "must construct App on main thread"
@ -175,16 +169,17 @@ impl AppContext {
app_version: platform.app_version().ok(), app_version: platform.app_version().ok(),
}; };
Arc::new_cyclic(|this| { Rc::new_cyclic(|this| {
Mutex::new(AppContext { RefCell::new(AppContext {
this: this.clone(), this: this.clone(),
text_system, text_system,
platform: MainThreadOnly::new(platform, executor.clone()), platform,
app_metadata, app_metadata,
flushing_effects: false, flushing_effects: false,
pending_updates: 0, pending_updates: 0,
next_frame_callbacks: Default::default(), next_frame_callbacks: Default::default(),
executor, background_executor: executor,
foreground_executor,
svg_renderer: SvgRenderer::new(asset_source.clone()), svg_renderer: SvgRenderer::new(asset_source.clone()),
asset_source, asset_source,
image_cache: ImageCache::new(http_client), image_cache: ImageCache::new(http_client),
@ -225,7 +220,7 @@ impl AppContext {
let futures = futures::future::join_all(futures); let futures = futures::future::join_all(futures);
if self if self
.executor .background_executor
.block_with_timeout(Duration::from_millis(100), futures) .block_with_timeout(Duration::from_millis(100), futures)
.is_err() .is_err()
{ {
@ -244,7 +239,6 @@ impl AppContext {
pub fn refresh(&mut self) { pub fn refresh(&mut self) {
self.pending_effects.push_back(Effect::Refresh); self.pending_effects.push_back(Effect::Refresh);
} }
pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R { pub(crate) fn update<R>(&mut self, update: impl FnOnce(&mut Self) -> R) -> R {
self.pending_updates += 1; self.pending_updates += 1;
let result = update(self); let result = update(self);
@ -258,7 +252,7 @@ impl AppContext {
} }
pub(crate) fn read_window<R>( pub(crate) fn read_window<R>(
&mut self, &self,
id: WindowId, id: WindowId,
read: impl FnOnce(&WindowContext) -> R, read: impl FnOnce(&WindowContext) -> R,
) -> Result<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) { pub(crate) fn push_effect(&mut self, effect: Effect) {
match &effect { match &effect {
Effect::Notify { emitter } => { Effect::Notify { emitter } => {
@ -473,67 +529,24 @@ impl AppContext {
pub fn to_async(&self) -> AsyncAppContext { pub fn to_async(&self) -> AsyncAppContext {
AsyncAppContext { AsyncAppContext {
app: unsafe { mem::transmute(self.this.clone()) }, 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. /// Obtains a reference to the executor, which can be used to spawn futures.
pub fn executor(&self) -> &Executor { pub fn executor(&self) -> &BackgroundExecutor {
&self.executor &self.background_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)))
} }
/// Spawns the future returned by the given function on the thread pool. The closure will be invoked /// 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. /// 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 where
Fut: Future<Output = R> + Send + 'static, Fut: Future<Output = R> + 'static,
R: Send + 'static, R: 'static,
{ {
let cx = self.to_async(); self.foreground_executor.spawn(f(self.to_async()))
self.executor.spawn(async move {
let future = f(cx);
future.await
})
} }
/// Schedules the given function to be run at the end of the current effect cycle, allowing entities /// 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 /// Access the global of the given type mutably. A default value is assigned if a global of this type has not
/// yet been assigned. /// 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>(); let global_type = TypeId::of::<G>();
self.push_effect(Effect::NotifyGlobalObservers { global_type }); self.push_effect(Effect::NotifyGlobalObservers { global_type });
self.globals_by_type self.globals_by_type
@ -608,7 +621,7 @@ impl AppContext {
} }
/// Set the value of the global of the given type. /// 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>(); let global_type = TypeId::of::<G>();
self.push_effect(Effect::NotifyGlobalObservers { global_type }); self.push_effect(Effect::NotifyGlobalObservers { global_type });
self.globals_by_type.insert(global_type, Box::new(global)); 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 /// 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 /// 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. /// which can be used to access the entity in a context.
fn build_model<T: 'static + Send>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Model<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. /// These effects are processed at the end of each application update cycle.
pub(crate) enum Effect { pub(crate) enum Effect {
Notify { Notify {
@ -855,7 +767,7 @@ pub(crate) enum Effect {
}, },
Emit { Emit {
emitter: EntityId, emitter: EntityId,
event: Box<dyn Any + Send + 'static>, event: Box<dyn Any>,
}, },
FocusChanged { FocusChanged {
window_id: WindowId, window_id: WindowId,
@ -905,15 +817,3 @@ pub(crate) struct AnyDrag {
pub view: AnyView, pub view: AnyView,
pub cursor_offset: Point<Pixels>, 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>();
}
}

View file

@ -1,16 +1,16 @@
use crate::{ use crate::{
AnyWindowHandle, AppContext, Context, Executor, MainThread, Model, ModelContext, Result, Task, AnyWindowHandle, AppContext, BackgroundExecutor, Context, ForegroundExecutor, Model,
WindowContext, ModelContext, Result, Task, WindowContext,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use parking_lot::Mutex; use std::{cell::RefCell, future::Future, rc::Weak};
use std::{future::Future, sync::Weak};
#[derive(Clone)] #[derive(Clone)]
pub struct AsyncAppContext { pub struct AsyncAppContext {
pub(crate) app: Weak<Mutex<AppContext>>, pub(crate) app: Weak<RefCell<AppContext>>,
pub(crate) executor: Executor, pub(crate) background_executor: BackgroundExecutor,
pub(crate) foreground_executor: ForegroundExecutor,
} }
impl Context for AsyncAppContext { impl Context for AsyncAppContext {
@ -22,14 +22,14 @@ impl Context for AsyncAppContext {
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>> ) -> Self::Result<Model<T>>
where where
T: 'static + Send, T: 'static,
{ {
let app = self let app = self
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock(); // Need this to compile let mut app = app.borrow_mut();
Ok(lock.build_model(build_model)) Ok(app.build_model(build_model))
} }
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
@ -41,8 +41,8 @@ impl Context for AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock(); // Need this to compile let mut app = app.borrow_mut();
Ok(lock.update_model(handle, update)) Ok(app.update_model(handle, update))
} }
} }
@ -52,13 +52,17 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock(); // Need this to compile let mut lock = app.borrow_mut();
lock.refresh(); lock.refresh();
Ok(()) Ok(())
} }
pub fn executor(&self) -> &Executor { pub fn background_executor(&self) -> &BackgroundExecutor {
&self.executor &self.background_executor
}
pub fn foreground_executor(&self) -> &ForegroundExecutor {
&self.foreground_executor
} }
pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> Result<R> { pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> Result<R> {
@ -66,7 +70,7 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock(); let mut lock = app.borrow_mut();
Ok(f(&mut *lock)) Ok(f(&mut *lock))
} }
@ -79,7 +83,7 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut app_context = app.lock(); let app_context = app.borrow();
app_context.read_window(handle.id, update) app_context.read_window(handle.id, update)
} }
@ -92,44 +96,16 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut app_context = app.lock(); let mut app_context = app.borrow_mut();
app_context.update_window(handle.id, update) app_context.update_window(handle.id, update)
} }
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,
{
let this = self.clone();
self.executor.spawn(async move { f(this).await })
}
pub fn spawn_on_main<Fut, R>(
&self,
f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static,
) -> Task<R>
where where
Fut: Future<Output = R> + 'static, Fut: Future<Output = R> + 'static,
R: Send + 'static, R: 'static,
{ {
let this = self.clone(); self.foreground_executor.spawn(f(self.clone()))
self.executor.spawn_on_main(|| f(this))
}
pub fn run_on_main<R>(
&self,
f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
) -> Result<Task<R>>
where
R: Send + 'static,
{
let app = self
.app
.upgrade()
.ok_or_else(|| anyhow!("app was released"))?;
let mut app_context = app.lock();
Ok(app_context.run_on_main(f))
} }
pub fn has_global<G: 'static>(&self) -> Result<bool> { pub fn has_global<G: 'static>(&self) -> Result<bool> {
@ -137,8 +113,8 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let lock = app.lock(); // Need this to compile let app = app.borrow_mut();
Ok(lock.has_global::<G>()) Ok(app.has_global::<G>())
} }
pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> { pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> Result<R> {
@ -146,8 +122,8 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let lock = app.lock(); // Need this to compile let app = app.borrow_mut(); // Need this to compile
Ok(read(lock.global(), &lock)) Ok(read(app.global(), &app))
} }
pub fn try_read_global<G: 'static, R>( pub fn try_read_global<G: 'static, R>(
@ -155,8 +131,8 @@ impl AsyncAppContext {
read: impl FnOnce(&G, &AppContext) -> R, read: impl FnOnce(&G, &AppContext) -> R,
) -> Option<R> { ) -> Option<R> {
let app = self.app.upgrade()?; let app = self.app.upgrade()?;
let lock = app.lock(); // Need this to compile let app = app.borrow_mut();
Some(read(lock.try_global()?, &lock)) Some(read(app.try_global()?, &app))
} }
pub fn update_global<G: 'static, R>( pub fn update_global<G: 'static, R>(
@ -167,8 +143,8 @@ impl AsyncAppContext {
.app .app
.upgrade() .upgrade()
.ok_or_else(|| anyhow!("app was released"))?; .ok_or_else(|| anyhow!("app was released"))?;
let mut lock = app.lock(); // Need this to compile let mut app = app.borrow_mut();
Ok(lock.update_global(update)) Ok(app.update_global(update))
} }
} }
@ -224,7 +200,7 @@ impl Context for AsyncWindowContext {
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Result<Model<T>> ) -> Result<Model<T>>
where where
T: 'static + Send, T: 'static,
{ {
self.app self.app
.update_window(self.window, |cx| cx.build_model(build_model)) .update_window(self.window, |cx| cx.build_model(build_model))
@ -239,14 +215,3 @@ impl Context for AsyncWindowContext {
.update_window(self.window, |cx| cx.update_model(handle, update)) .update_window(self.window, |cx| cx.update_model(handle, update))
} }
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_async_app_context_send_sync() {
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<AsyncAppContext>();
}
}

View file

@ -59,7 +59,7 @@ impl EntityMap {
/// Insert an entity into a slot obtained by calling `reserve`. /// Insert an entity into a slot obtained by calling `reserve`.
pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Model<T> pub fn insert<T>(&mut self, slot: Slot<T>, entity: T) -> Model<T>
where where
T: 'static + Send, T: 'static,
{ {
let model = slot.0; let model = slot.0;
self.entities.insert(model.entity_id, Box::new(entity)); self.entities.insert(model.entity_id, Box::new(entity));

View file

@ -1,6 +1,6 @@
use crate::{ use crate::{
AppContext, AsyncAppContext, Context, Effect, Entity, EntityId, EventEmitter, MainThread, AppContext, AsyncAppContext, Context, Effect, Entity, EntityId, EventEmitter, Model, Reference,
Model, Reference, Subscription, Task, WeakModel, Subscription, Task, WeakModel,
}; };
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use futures::FutureExt; use futures::FutureExt;
@ -191,36 +191,20 @@ impl<'a, T: 'static> ModelContext<'a, T> {
result result
} }
pub fn spawn<Fut, R>( pub fn spawn<Fut, R>(&self, f: impl FnOnce(WeakModel<T>, AsyncAppContext) -> Fut) -> Task<R>
&self,
f: impl FnOnce(WeakModel<T>, AsyncAppContext) -> Fut + Send + 'static,
) -> Task<R>
where where
T: 'static, T: 'static,
Fut: Future<Output = R> + Send + 'static, Fut: Future<Output = R> + 'static,
R: Send + 'static, R: 'static,
{ {
let this = self.weak_model(); let this = self.weak_model();
self.app.spawn(|cx| f(this, cx)) self.app.spawn(|cx| f(this, cx))
} }
pub fn spawn_on_main<Fut, R>(
&self,
f: impl FnOnce(WeakModel<T>, MainThread<AsyncAppContext>) -> Fut + Send + 'static,
) -> Task<R>
where
Fut: Future<Output = R> + 'static,
R: Send + 'static,
{
let this = self.weak_model();
self.app.spawn_on_main(|cx| f(this, cx))
}
} }
impl<'a, T> ModelContext<'a, T> impl<'a, T> ModelContext<'a, T>
where where
T: EventEmitter, T: EventEmitter,
T::Event: Send,
{ {
pub fn emit(&mut self, event: T::Event) { pub fn emit(&mut self, event: T::Event) {
self.app.pending_effects.push_back(Effect::Emit { self.app.pending_effects.push_back(Effect::Emit {
@ -234,13 +218,10 @@ impl<'a, T> Context for ModelContext<'a, T> {
type ModelContext<'b, U> = ModelContext<'b, U>; type ModelContext<'b, U> = ModelContext<'b, U>;
type Result<U> = U; type Result<U> = U;
fn build_model<U>( fn build_model<U: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, U>) -> U, build_model: impl FnOnce(&mut Self::ModelContext<'_, U>) -> U,
) -> Model<U> ) -> Model<U> {
where
U: 'static + Send,
{
self.app.build_model(build_model) self.app.build_model(build_model)
} }

View file

@ -1,15 +1,16 @@
use crate::{ use crate::{
AnyWindowHandle, AppContext, AsyncAppContext, Context, EventEmitter, Executor, MainThread, AnyWindowHandle, AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter,
Model, ModelContext, Result, Task, TestDispatcher, TestPlatform, WindowContext, ForegroundExecutor, Model, ModelContext, Result, Task, TestDispatcher, TestPlatform,
WindowContext,
}; };
use futures::SinkExt; use futures::SinkExt;
use parking_lot::Mutex; use std::{cell::RefCell, future::Future, rc::Rc, sync::Arc};
use std::{future::Future, sync::Arc};
#[derive(Clone)] #[derive(Clone)]
pub struct TestAppContext { pub struct TestAppContext {
pub app: Arc<Mutex<AppContext>>, pub app: Rc<RefCell<AppContext>>,
pub executor: Executor, pub background_executor: BackgroundExecutor,
pub foreground_executor: ForegroundExecutor,
} }
impl Context for TestAppContext { impl Context for TestAppContext {
@ -21,10 +22,10 @@ impl Context for TestAppContext {
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>> ) -> Self::Result<Model<T>>
where where
T: 'static + Send, T: 'static,
{ {
let mut lock = self.app.lock(); let mut app = self.app.borrow_mut();
lock.build_model(build_model) app.build_model(build_model)
} }
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
@ -32,39 +33,45 @@ impl Context for TestAppContext {
handle: &Model<T>, handle: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R, update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
) -> Self::Result<R> { ) -> Self::Result<R> {
let mut lock = self.app.lock(); let mut app = self.app.borrow_mut();
lock.update_model(handle, update) app.update_model(handle, update)
} }
} }
impl TestAppContext { impl TestAppContext {
pub fn new(dispatcher: TestDispatcher) -> Self { pub fn new(dispatcher: TestDispatcher) -> Self {
let executor = Executor::new(Arc::new(dispatcher)); let dispatcher = Arc::new(dispatcher);
let platform = Arc::new(TestPlatform::new(executor.clone())); let background_executor = BackgroundExecutor::new(dispatcher.clone());
let foreground_executor = ForegroundExecutor::new(dispatcher);
let platform = Rc::new(TestPlatform::new(
background_executor.clone(),
foreground_executor.clone(),
));
let asset_source = Arc::new(()); let asset_source = Arc::new(());
let http_client = util::http::FakeHttpClient::with_404_response(); let http_client = util::http::FakeHttpClient::with_404_response();
Self { Self {
app: AppContext::new(platform, asset_source, http_client), app: AppContext::new(platform, asset_source, http_client),
executor, background_executor,
foreground_executor,
} }
} }
pub fn quit(&self) { pub fn quit(&self) {
self.app.lock().quit(); self.app.borrow_mut().quit();
} }
pub fn refresh(&mut self) -> Result<()> { pub fn refresh(&mut self) -> Result<()> {
let mut lock = self.app.lock(); let mut app = self.app.borrow_mut();
lock.refresh(); app.refresh();
Ok(()) Ok(())
} }
pub fn executor(&self) -> &Executor { pub fn executor(&self) -> &BackgroundExecutor {
&self.executor &self.background_executor
} }
pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R { pub fn update<R>(&self, f: impl FnOnce(&mut AppContext) -> R) -> R {
let mut cx = self.app.lock(); let mut cx = self.app.borrow_mut();
cx.update(f) cx.update(f)
} }
@ -73,7 +80,7 @@ impl TestAppContext {
handle: AnyWindowHandle, handle: AnyWindowHandle,
read: impl FnOnce(&WindowContext) -> R, read: impl FnOnce(&WindowContext) -> R,
) -> R { ) -> R {
let mut app_context = self.app.lock(); let app_context = self.app.borrow();
app_context.read_window(handle.id, read).unwrap() app_context.read_window(handle.id, read).unwrap()
} }
@ -82,57 +89,33 @@ impl TestAppContext {
handle: AnyWindowHandle, handle: AnyWindowHandle,
update: impl FnOnce(&mut WindowContext) -> R, update: impl FnOnce(&mut WindowContext) -> R,
) -> R { ) -> R {
let mut app = self.app.lock(); let mut app = self.app.borrow_mut();
app.update_window(handle.id, update).unwrap() app.update_window(handle.id, update).unwrap()
} }
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,
{
let cx = self.to_async();
self.executor.spawn(async move { f(cx).await })
}
pub fn spawn_on_main<Fut, R>(
&self,
f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static,
) -> Task<R>
where where
Fut: Future<Output = R> + 'static, Fut: Future<Output = R> + 'static,
R: Send + 'static, R: 'static,
{ {
let cx = self.to_async(); self.foreground_executor.spawn(f(self.to_async()))
self.executor.spawn_on_main(|| f(cx))
}
pub fn run_on_main<R>(
&self,
f: impl FnOnce(&mut MainThread<AppContext>) -> R + Send + 'static,
) -> Task<R>
where
R: Send + 'static,
{
let mut app_context = self.app.lock();
app_context.run_on_main(f)
} }
pub fn has_global<G: 'static>(&self) -> bool { pub fn has_global<G: 'static>(&self) -> bool {
let lock = self.app.lock(); let app = self.app.borrow();
lock.has_global::<G>() app.has_global::<G>()
} }
pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R { pub fn read_global<G: 'static, R>(&self, read: impl FnOnce(&G, &AppContext) -> R) -> R {
let lock = self.app.lock(); let app = self.app.borrow();
read(lock.global(), &lock) read(app.global(), &app)
} }
pub fn try_read_global<G: 'static, R>( pub fn try_read_global<G: 'static, R>(
&self, &self,
read: impl FnOnce(&G, &AppContext) -> R, read: impl FnOnce(&G, &AppContext) -> R,
) -> Option<R> { ) -> Option<R> {
let lock = self.app.lock(); let lock = self.app.borrow();
Some(read(lock.try_global()?, &lock)) Some(read(lock.try_global()?, &lock))
} }
@ -140,14 +123,15 @@ impl TestAppContext {
&mut self, &mut self,
update: impl FnOnce(&mut G, &mut AppContext) -> R, update: impl FnOnce(&mut G, &mut AppContext) -> R,
) -> R { ) -> R {
let mut lock = self.app.lock(); let mut lock = self.app.borrow_mut();
lock.update_global(update) lock.update_global(update)
} }
pub fn to_async(&self) -> AsyncAppContext { pub fn to_async(&self) -> AsyncAppContext {
AsyncAppContext { AsyncAppContext {
app: Arc::downgrade(&self.app), app: Rc::downgrade(&self.app),
executor: self.executor.clone(), background_executor: self.background_executor.clone(),
foreground_executor: self.foreground_executor.clone(),
} }
} }

View file

@ -8,7 +8,7 @@ use std::{
sync::atomic::{AtomicUsize, Ordering::SeqCst}, sync::atomic::{AtomicUsize, Ordering::SeqCst},
}; };
pub trait AssetSource: 'static + Send + Sync { pub trait AssetSource: 'static + Sync {
fn load(&self, path: &str) -> Result<Cow<[u8]>>; fn load(&self, path: &str) -> Result<Cow<[u8]>>;
fn list(&self, path: &str) -> Result<Vec<SharedString>>; fn list(&self, path: &str) -> Result<Vec<SharedString>>;
} }

View file

@ -4,7 +4,7 @@ pub(crate) use smallvec::SmallVec;
use std::{any::Any, mem}; use std::{any::Any, mem};
pub trait Element<V: 'static> { pub trait Element<V: 'static> {
type ElementState: 'static + Send; type ElementState: 'static;
fn id(&self) -> Option<ElementId>; fn id(&self) -> Option<ElementId>;
@ -97,7 +97,7 @@ impl<V, E: Element<V>> RenderedElement<V, E> {
impl<V, E> ElementObject<V> for RenderedElement<V, E> impl<V, E> ElementObject<V> for RenderedElement<V, E>
where where
E: Element<V>, E: Element<V>,
E::ElementState: 'static + Send, E::ElementState: 'static,
{ {
fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) { fn initialize(&mut self, view_state: &mut V, cx: &mut ViewContext<V>) {
let frame_state = if let Some(id) = self.element.id() { let frame_state = if let Some(id) = self.element.id() {
@ -170,16 +170,14 @@ where
} }
} }
pub struct AnyElement<V>(Box<dyn ElementObject<V> + Send>); pub struct AnyElement<V>(Box<dyn ElementObject<V>>);
unsafe impl<V> Send for AnyElement<V> {}
impl<V> AnyElement<V> { impl<V> AnyElement<V> {
pub fn new<E>(element: E) -> Self pub fn new<E>(element: E) -> Self
where where
V: 'static, V: 'static,
E: 'static + Element<V> + Send, E: 'static + Element<V>,
E::ElementState: Any + Send, E::ElementState: Any,
{ {
AnyElement(Box::new(RenderedElement::new(element))) AnyElement(Box::new(RenderedElement::new(element)))
} }

View file

@ -6,6 +6,7 @@ use std::{
marker::PhantomData, marker::PhantomData,
mem, mem,
pin::Pin, pin::Pin,
rc::Rc,
sync::{ sync::{
atomic::{AtomicBool, Ordering::SeqCst}, atomic::{AtomicBool, Ordering::SeqCst},
Arc, Arc,
@ -17,10 +18,16 @@ use util::TryFutureExt;
use waker_fn::waker_fn; use waker_fn::waker_fn;
#[derive(Clone)] #[derive(Clone)]
pub struct Executor { pub struct BackgroundExecutor {
dispatcher: Arc<dyn PlatformDispatcher>, dispatcher: Arc<dyn PlatformDispatcher>,
} }
#[derive(Clone)]
pub struct ForegroundExecutor {
dispatcher: Arc<dyn PlatformDispatcher>,
not_send: PhantomData<Rc<()>>,
}
#[must_use] #[must_use]
pub enum Task<T> { pub enum Task<T> {
Ready(Option<T>), Ready(Option<T>),
@ -61,7 +68,7 @@ impl<T> Future for Task<T> {
} }
} }
impl Executor { impl BackgroundExecutor {
pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self { pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
Self { dispatcher } Self { dispatcher }
} }
@ -79,63 +86,6 @@ impl Executor {
Task::Spawned(task) Task::Spawned(task)
} }
/// Enqueues the given closure to run on the application's event loop.
/// Returns the result asynchronously.
pub fn run_on_main<F, R>(&self, func: F) -> Task<R>
where
F: FnOnce() -> R + Send + 'static,
R: Send + 'static,
{
if self.dispatcher.is_main_thread() {
Task::ready(func())
} else {
self.spawn_on_main(move || async move { func() })
}
}
/// Enqueues the given closure to be run on the application's event loop. The
/// closure returns a future which will be run to completion on the main thread.
pub fn spawn_on_main<F, R>(&self, func: impl FnOnce() -> F + Send + 'static) -> Task<R>
where
F: Future<Output = R> + 'static,
R: Send + 'static,
{
let (runnable, task) = async_task::spawn(
{
let this = self.clone();
async move {
let task = this.spawn_on_main_local(func());
task.await
}
},
{
let dispatcher = self.dispatcher.clone();
move |runnable| dispatcher.dispatch_on_main_thread(runnable)
},
);
runnable.schedule();
Task::Spawned(task)
}
/// Enqueues the given closure to be run on the application's event loop. Must
/// be called on the main thread.
pub fn spawn_on_main_local<R>(&self, future: impl Future<Output = R> + 'static) -> Task<R>
where
R: 'static,
{
assert!(
self.dispatcher.is_main_thread(),
"must be called on main thread"
);
let dispatcher = self.dispatcher.clone();
let (runnable, task) = async_task::spawn_local(future, move |runnable| {
dispatcher.dispatch_on_main_thread(runnable)
});
runnable.schedule();
Task::Spawned(task)
}
pub fn block<R>(&self, future: impl Future<Output = R>) -> R { pub fn block<R>(&self, future: impl Future<Output = R>) -> R {
pin_mut!(future); pin_mut!(future);
let (parker, unparker) = parking::pair(); let (parker, unparker) = parking::pair();
@ -261,8 +211,31 @@ impl Executor {
} }
} }
impl ForegroundExecutor {
pub fn new(dispatcher: Arc<dyn PlatformDispatcher>) -> Self {
Self {
dispatcher,
not_send: PhantomData,
}
}
/// Enqueues the given closure to be run on any thread. The closure returns
/// a future which will be run to completion on any available thread.
pub fn spawn<R>(&self, future: impl Future<Output = R> + 'static) -> Task<R>
where
R: 'static,
{
let dispatcher = self.dispatcher.clone();
let (runnable, task) = async_task::spawn_local(future, move |runnable| {
dispatcher.dispatch_on_main_thread(runnable)
});
runnable.schedule();
Task::Spawned(task)
}
}
pub struct Scope<'a> { pub struct Scope<'a> {
executor: Executor, executor: BackgroundExecutor,
futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>, futures: Vec<Pin<Box<dyn Future<Output = ()> + Send + 'static>>>,
tx: Option<mpsc::Sender<()>>, tx: Option<mpsc::Sender<()>>,
rx: mpsc::Receiver<()>, rx: mpsc::Receiver<()>,
@ -270,7 +243,7 @@ pub struct Scope<'a> {
} }
impl<'a> Scope<'a> { impl<'a> Scope<'a> {
fn new(executor: Executor) -> Self { fn new(executor: BackgroundExecutor) -> Self {
let (tx, rx) = mpsc::channel(1); let (tx, rx) = mpsc::channel(1);
Self { Self {
executor, executor,

View file

@ -68,24 +68,20 @@ use derive_more::{Deref, DerefMut};
use std::{ use std::{
any::{Any, TypeId}, any::{Any, TypeId},
borrow::{Borrow, BorrowMut}, borrow::{Borrow, BorrowMut},
mem,
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
sync::Arc,
}; };
use taffy::TaffyLayoutEngine; use taffy::TaffyLayoutEngine;
type AnyBox = Box<dyn Any + Send>; type AnyBox = Box<dyn Any>;
pub trait Context { pub trait Context {
type ModelContext<'a, T>; type ModelContext<'a, T>;
type Result<T>; type Result<T>;
fn build_model<T>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>> ) -> Self::Result<Model<T>>;
where
T: 'static + Send;
fn update_model<T: 'static, R>( fn update_model<T: 'static, R>(
&mut self, &mut self,
@ -102,7 +98,7 @@ pub trait VisualContext: Context {
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V, build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
) -> Self::Result<View<V>> ) -> Self::Result<View<V>>
where where
V: 'static + Send; V: 'static;
fn update_view<V: 'static, R>( fn update_view<V: 'static, R>(
&mut self, &mut self,
@ -127,100 +123,6 @@ pub enum GlobalKey {
Type(TypeId), Type(TypeId),
} }
#[repr(transparent)]
pub struct MainThread<T>(T);
impl<T> Deref for MainThread<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl<T> DerefMut for MainThread<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<C: Context> Context for MainThread<C> {
type ModelContext<'a, T> = MainThread<C::ModelContext<'a, T>>;
type Result<T> = C::Result<T>;
fn build_model<T>(
&mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Self::Result<Model<T>>
where
T: 'static + Send,
{
self.0.build_model(|cx| {
let cx = unsafe {
mem::transmute::<
&mut C::ModelContext<'_, T>,
&mut MainThread<C::ModelContext<'_, T>>,
>(cx)
};
build_model(cx)
})
}
fn update_model<T: 'static, R>(
&mut self,
handle: &Model<T>,
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
) -> Self::Result<R> {
self.0.update_model(handle, |entity, cx| {
let cx = unsafe {
mem::transmute::<
&mut C::ModelContext<'_, T>,
&mut MainThread<C::ModelContext<'_, T>>,
>(cx)
};
update(entity, cx)
})
}
}
impl<C: VisualContext> VisualContext for MainThread<C> {
type ViewContext<'a, 'w, V> = MainThread<C::ViewContext<'a, 'w, V>>;
fn build_view<V>(
&mut self,
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
) -> Self::Result<View<V>>
where
V: 'static + Send,
{
self.0.build_view(|cx| {
let cx = unsafe {
mem::transmute::<
&mut C::ViewContext<'_, '_, V>,
&mut MainThread<C::ViewContext<'_, '_, V>>,
>(cx)
};
build_view_state(cx)
})
}
fn update_view<V: 'static, R>(
&mut self,
view: &View<V>,
update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, '_, V>) -> R,
) -> Self::Result<R> {
self.0.update_view(view, |view_state, cx| {
let cx = unsafe {
mem::transmute::<
&mut C::ViewContext<'_, '_, V>,
&mut MainThread<C::ViewContext<'_, '_, V>>,
>(cx)
};
update(view_state, cx)
})
}
}
pub trait BorrowAppContext { pub trait BorrowAppContext {
fn with_text_style<F, R>(&mut self, style: TextStyleRefinement, f: F) -> R fn with_text_style<F, R>(&mut self, style: TextStyleRefinement, f: F) -> R
where where
@ -333,32 +235,3 @@ impl<'a, T> DerefMut for Reference<'a, T> {
} }
} }
} }
pub(crate) struct MainThreadOnly<T: ?Sized> {
executor: Executor,
value: Arc<T>,
}
impl<T: ?Sized> Clone for MainThreadOnly<T> {
fn clone(&self) -> Self {
Self {
executor: self.executor.clone(),
value: self.value.clone(),
}
}
}
/// Allows a value to be accessed only on the main thread, allowing a non-`Send` type
/// to become `Send`.
impl<T: 'static + ?Sized> MainThreadOnly<T> {
pub(crate) fn new(value: Arc<T>, executor: Executor) -> Self {
Self { executor, value }
}
pub(crate) fn borrow_on_main_thread(&self) -> &T {
assert!(self.executor.is_main_thread());
&self.value
}
}
unsafe impl<T: ?Sized> Send for MainThreadOnly<T> {}

View file

@ -50,7 +50,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_mouse_down( fn on_mouse_down(
mut self, mut self,
button: MouseButton, button: MouseButton,
handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -71,7 +71,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_mouse_up( fn on_mouse_up(
mut self, mut self,
button: MouseButton, button: MouseButton,
handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -92,7 +92,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_mouse_down_out( fn on_mouse_down_out(
mut self, mut self,
button: MouseButton, button: MouseButton,
handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &MouseDownEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -113,7 +113,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_mouse_up_out( fn on_mouse_up_out(
mut self, mut self,
button: MouseButton, button: MouseButton,
handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &MouseUpEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -133,7 +133,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_mouse_move( fn on_mouse_move(
mut self, mut self,
handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &MouseMoveEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -150,7 +150,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_scroll_wheel( fn on_scroll_wheel(
mut self, mut self,
handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &ScrollWheelEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -178,7 +178,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_action<A: 'static>( fn on_action<A: 'static>(
mut self, mut self,
listener: impl Fn(&mut V, &A, DispatchPhase, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &A, DispatchPhase, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -196,7 +196,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_key_down( fn on_key_down(
mut self, mut self,
listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &KeyDownEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -214,7 +214,7 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
fn on_key_up( fn on_key_up(
mut self, mut self,
listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &KeyUpEvent, DispatchPhase, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -258,9 +258,9 @@ pub trait StatelessInteractive<V: 'static>: Element<V> {
self self
} }
fn on_drop<W: 'static + Send>( fn on_drop<W: 'static>(
mut self, mut self,
listener: impl Fn(&mut V, View<W>, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, View<W>, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -303,7 +303,7 @@ pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
fn on_click( fn on_click(
mut self, mut self,
listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + Send + 'static, listener: impl Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
@ -316,11 +316,11 @@ pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
fn on_drag<W>( fn on_drag<W>(
mut self, mut self,
listener: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + Send + 'static, listener: impl Fn(&mut V, &mut ViewContext<V>) -> View<W> + 'static,
) -> Self ) -> Self
where where
Self: Sized, Self: Sized,
W: 'static + Send + Render, W: 'static + Render,
{ {
debug_assert!( debug_assert!(
self.stateful_interaction().drag_listener.is_none(), self.stateful_interaction().drag_listener.is_none(),
@ -335,7 +335,7 @@ pub trait StatefulInteractive<V: 'static>: StatelessInteractive<V> {
} }
} }
pub trait ElementInteraction<V: 'static>: 'static + Send { pub trait ElementInteraction<V: 'static>: 'static {
fn as_stateless(&self) -> &StatelessInteraction<V>; fn as_stateless(&self) -> &StatelessInteraction<V>;
fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V>; fn as_stateless_mut(&mut self) -> &mut StatelessInteraction<V>;
fn as_stateful(&self) -> Option<&StatefulInteraction<V>>; fn as_stateful(&self) -> Option<&StatefulInteraction<V>>;
@ -672,7 +672,7 @@ impl<V> From<ElementId> for StatefulInteraction<V> {
} }
} }
type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static + Send; type DropListener<V> = dyn Fn(&mut V, AnyView, &mut ViewContext<V>) + 'static;
pub struct StatelessInteraction<V> { pub struct StatelessInteraction<V> {
pub dispatch_context: DispatchContext, pub dispatch_context: DispatchContext,
@ -1077,32 +1077,25 @@ pub struct FocusEvent {
} }
pub type MouseDownListener<V> = Box< pub type MouseDownListener<V> = Box<
dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) dyn Fn(&mut V, &MouseDownEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
+ Send
+ 'static,
>; >;
pub type MouseUpListener<V> = Box< pub type MouseUpListener<V> = Box<
dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) dyn Fn(&mut V, &MouseUpEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
+ Send
+ 'static,
>; >;
pub type MouseMoveListener<V> = Box< pub type MouseMoveListener<V> = Box<
dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) dyn Fn(&mut V, &MouseMoveEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) + 'static,
+ Send
+ 'static,
>; >;
pub type ScrollWheelListener<V> = Box< pub type ScrollWheelListener<V> = Box<
dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>) dyn Fn(&mut V, &ScrollWheelEvent, &Bounds<Pixels>, DispatchPhase, &mut ViewContext<V>)
+ Send
+ 'static, + 'static,
>; >;
pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + Send + 'static>; pub type ClickListener<V> = Box<dyn Fn(&mut V, &ClickEvent, &mut ViewContext<V>) + 'static>;
pub(crate) type DragListener<V> = pub(crate) type DragListener<V> =
Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + Send + 'static>; Box<dyn Fn(&mut V, Point<Pixels>, &mut ViewContext<V>) -> AnyDrag + 'static>;
pub type KeyListener<V> = Box< pub type KeyListener<V> = Box<
dyn Fn( dyn Fn(
@ -1112,6 +1105,5 @@ pub type KeyListener<V> = Box<
DispatchPhase, DispatchPhase,
&mut ViewContext<V>, &mut ViewContext<V>,
) -> Option<Box<dyn Action>> ) -> Option<Box<dyn Action>>
+ Send
+ 'static, + 'static,
>; >;

View file

@ -5,9 +5,9 @@ mod mac;
mod test; mod test;
use crate::{ use crate::{
AnyWindowHandle, Bounds, DevicePixels, Executor, Font, FontId, FontMetrics, FontRun, AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId, FontMetrics, FontRun,
GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point, RenderGlyphParams, ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point,
RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use async_task::Runnable; use async_task::Runnable;
@ -35,12 +35,13 @@ pub use test::*;
pub use time::UtcOffset; pub use time::UtcOffset;
#[cfg(target_os = "macos")] #[cfg(target_os = "macos")]
pub(crate) fn current_platform() -> Arc<dyn Platform> { pub(crate) fn current_platform() -> Rc<dyn Platform> {
Arc::new(MacPlatform::new()) Rc::new(MacPlatform::new())
} }
pub(crate) trait Platform: 'static { pub(crate) trait Platform: 'static {
fn executor(&self) -> Executor; fn background_executor(&self) -> BackgroundExecutor;
fn foreground_executor(&self) -> ForegroundExecutor;
fn text_system(&self) -> Arc<dyn PlatformTextSystem>; fn text_system(&self) -> Arc<dyn PlatformTextSystem>;
fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>); fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>);

View file

@ -1,9 +1,9 @@
use super::BoolExt; use super::BoolExt;
use crate::{ use crate::{
AnyWindowHandle, ClipboardItem, CursorStyle, DisplayId, Executor, InputEvent, MacDispatcher, AnyWindowHandle, BackgroundExecutor, ClipboardItem, CursorStyle, DisplayId, ForegroundExecutor,
MacDisplay, MacDisplayLinker, MacTextSystem, MacWindow, PathPromptOptions, Platform, InputEvent, MacDispatcher, MacDisplay, MacDisplayLinker, MacTextSystem, MacWindow,
PlatformDisplay, PlatformTextSystem, PlatformWindow, Result, SemanticVersion, VideoTimestamp, PathPromptOptions, Platform, PlatformDisplay, PlatformTextSystem, PlatformWindow, Result,
WindowOptions, SemanticVersion, VideoTimestamp, WindowOptions,
}; };
use anyhow::anyhow; use anyhow::anyhow;
use block::ConcreteBlock; use block::ConcreteBlock;
@ -143,7 +143,8 @@ unsafe fn build_classes() {
pub struct MacPlatform(Mutex<MacPlatformState>); pub struct MacPlatform(Mutex<MacPlatformState>);
pub struct MacPlatformState { pub struct MacPlatformState {
executor: Executor, background_executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
text_system: Arc<MacTextSystem>, text_system: Arc<MacTextSystem>,
display_linker: MacDisplayLinker, display_linker: MacDisplayLinker,
pasteboard: id, pasteboard: id,
@ -164,8 +165,10 @@ pub struct MacPlatformState {
impl MacPlatform { impl MacPlatform {
pub fn new() -> Self { pub fn new() -> Self {
let dispatcher = Arc::new(MacDispatcher);
Self(Mutex::new(MacPlatformState { Self(Mutex::new(MacPlatformState {
executor: Executor::new(Arc::new(MacDispatcher)), background_executor: BackgroundExecutor::new(dispatcher.clone()),
foreground_executor: ForegroundExecutor::new(dispatcher.clone()),
text_system: Arc::new(MacTextSystem::new()), text_system: Arc::new(MacTextSystem::new()),
display_linker: MacDisplayLinker::new(), display_linker: MacDisplayLinker::new(),
pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) }, pasteboard: unsafe { NSPasteboard::generalPasteboard(nil) },
@ -345,8 +348,12 @@ impl MacPlatform {
} }
impl Platform for MacPlatform { impl Platform for MacPlatform {
fn executor(&self) -> Executor { fn background_executor(&self) -> BackgroundExecutor {
self.0.lock().executor.clone() self.0.lock().background_executor.clone()
}
fn foreground_executor(&self) -> crate::ForegroundExecutor {
self.0.lock().foreground_executor.clone()
} }
fn text_system(&self) -> Arc<dyn PlatformTextSystem> { fn text_system(&self) -> Arc<dyn PlatformTextSystem> {
@ -457,6 +464,10 @@ impl Platform for MacPlatform {
} }
} }
// fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn platform::Window> {
// Box::new(StatusItem::add(self.fonts()))
// }
fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> { fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
MacDisplay::all() MacDisplay::all()
.into_iter() .into_iter()
@ -464,10 +475,6 @@ impl Platform for MacPlatform {
.collect() .collect()
} }
// fn add_status_item(&self, _handle: AnyWindowHandle) -> Box<dyn platform::Window> {
// Box::new(StatusItem::add(self.fonts()))
// }
fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> { fn display(&self, id: DisplayId) -> Option<Rc<dyn PlatformDisplay>> {
MacDisplay::find_by_id(id).map(|screen| Rc::new(screen) as Rc<_>) MacDisplay::find_by_id(id).map(|screen| Rc::new(screen) as Rc<_>)
} }
@ -481,7 +488,7 @@ impl Platform for MacPlatform {
handle: AnyWindowHandle, handle: AnyWindowHandle,
options: WindowOptions, options: WindowOptions,
) -> Box<dyn PlatformWindow> { ) -> Box<dyn PlatformWindow> {
Box::new(MacWindow::open(handle, options, self.executor())) Box::new(MacWindow::open(handle, options, self.foreground_executor()))
} }
fn set_display_link_output_callback( fn set_display_link_output_callback(
@ -589,8 +596,8 @@ impl Platform for MacPlatform {
let path = path.to_path_buf(); let path = path.to_path_buf();
self.0 self.0
.lock() .lock()
.executor .background_executor
.spawn_on_main_local(async move { .spawn(async move {
let full_path = ns_string(path.to_str().unwrap_or("")); let full_path = ns_string(path.to_str().unwrap_or(""));
let root_full_path = ns_string(""); let root_full_path = ns_string("");
let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace]; let workspace: id = msg_send![class!(NSWorkspace), sharedWorkspace];
@ -674,23 +681,6 @@ impl Platform for MacPlatform {
} }
} }
fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
unsafe {
let bundle: id = NSBundle::mainBundle();
if bundle.is_null() {
Err(anyhow!("app is not running inside a bundle"))
} else {
let name = ns_string(name);
let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
if url.is_null() {
Err(anyhow!("resource not found"))
} else {
ns_url_to_path(url)
}
}
}
}
// fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>) { // fn on_menu_command(&self, callback: Box<dyn FnMut(&dyn Action)>) {
// self.0.lock().menu_command = Some(callback); // self.0.lock().menu_command = Some(callback);
// } // }
@ -717,6 +707,23 @@ impl Platform for MacPlatform {
// } // }
// } // }
fn path_for_auxiliary_executable(&self, name: &str) -> Result<PathBuf> {
unsafe {
let bundle: id = NSBundle::mainBundle();
if bundle.is_null() {
Err(anyhow!("app is not running inside a bundle"))
} else {
let name = ns_string(name);
let url: id = msg_send![bundle, URLForAuxiliaryExecutable: name];
if url.is_null() {
Err(anyhow!("resource not found"))
} else {
ns_url_to_path(url)
}
}
}
}
fn set_cursor_style(&self, style: CursorStyle) { fn set_cursor_style(&self, style: CursorStyle) {
unsafe { unsafe {
let new_cursor: id = match style { let new_cursor: id = match style {

View file

@ -1,10 +1,10 @@
use super::{display_bounds_from_native, ns_string, MacDisplay, MetalRenderer, NSRange}; use super::{display_bounds_from_native, ns_string, MacDisplay, MetalRenderer, NSRange};
use crate::{ use crate::{
display_bounds_to_native, point, px, size, AnyWindowHandle, Bounds, Executor, ExternalPaths, display_bounds_to_native, point, px, size, AnyWindowHandle, Bounds, ExternalPaths,
FileDropEvent, GlobalPixels, InputEvent, KeyDownEvent, Keystroke, Modifiers, FileDropEvent, ForegroundExecutor, GlobalPixels, InputEvent, KeyDownEvent, Keystroke,
ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, Scene, Size, Pixels, PlatformAtlas, PlatformDisplay, PlatformInputHandler, PlatformWindow, Point, Scene,
Timer, WindowAppearance, WindowBounds, WindowKind, WindowOptions, WindowPromptLevel, Size, Timer, WindowAppearance, WindowBounds, WindowKind, WindowOptions, WindowPromptLevel,
}; };
use block::ConcreteBlock; use block::ConcreteBlock;
use cocoa::{ use cocoa::{
@ -315,7 +315,7 @@ struct InsertText {
struct MacWindowState { struct MacWindowState {
handle: AnyWindowHandle, handle: AnyWindowHandle,
executor: Executor, executor: ForegroundExecutor,
native_window: id, native_window: id,
renderer: MetalRenderer, renderer: MetalRenderer,
scene_to_render: Option<Scene>, scene_to_render: Option<Scene>,
@ -451,7 +451,11 @@ unsafe impl Send for MacWindowState {}
pub struct MacWindow(Arc<Mutex<MacWindowState>>); pub struct MacWindow(Arc<Mutex<MacWindowState>>);
impl MacWindow { impl MacWindow {
pub fn open(handle: AnyWindowHandle, options: WindowOptions, executor: Executor) -> Self { pub fn open(
handle: AnyWindowHandle,
options: WindowOptions,
executor: ForegroundExecutor,
) -> Self {
unsafe { unsafe {
let pool = NSAutoreleasePool::new(nil); let pool = NSAutoreleasePool::new(nil);
@ -674,13 +678,10 @@ impl MacWindow {
impl Drop for MacWindow { impl Drop for MacWindow {
fn drop(&mut self) { fn drop(&mut self) {
let this = self.0.clone(); let native_window = self.0.lock().native_window;
let executor = self.0.lock().executor.clone(); unsafe {
executor native_window.close();
.run_on_main(move || unsafe { }
this.lock().native_window.close();
})
.detach();
} }
} }
@ -807,7 +808,7 @@ impl PlatformWindow for MacWindow {
let native_window = self.0.lock().native_window; let native_window = self.0.lock().native_window;
let executor = self.0.lock().executor.clone(); let executor = self.0.lock().executor.clone();
executor executor
.spawn_on_main_local(async move { .spawn(async move {
let _: () = msg_send![ let _: () = msg_send![
alert, alert,
beginSheetModalForWindow: native_window beginSheetModalForWindow: native_window
@ -824,7 +825,7 @@ impl PlatformWindow for MacWindow {
let window = self.0.lock().native_window; let window = self.0.lock().native_window;
let executor = self.0.lock().executor.clone(); let executor = self.0.lock().executor.clone();
executor executor
.spawn_on_main_local(async move { .spawn(async move {
unsafe { unsafe {
let _: () = msg_send![window, makeKeyAndOrderFront: nil]; let _: () = msg_send![window, makeKeyAndOrderFront: nil];
} }
@ -872,25 +873,17 @@ impl PlatformWindow for MacWindow {
fn zoom(&self) { fn zoom(&self) {
let this = self.0.lock(); let this = self.0.lock();
let window = this.native_window; let window = this.native_window;
this.executor unsafe {
.spawn_on_main_local(async move { window.zoom_(nil);
unsafe { }
window.zoom_(nil);
}
})
.detach();
} }
fn toggle_full_screen(&self) { fn toggle_full_screen(&self) {
let this = self.0.lock(); let this = self.0.lock();
let window = this.native_window; let window = this.native_window;
this.executor unsafe {
.spawn_on_main_local(async move { window.toggleFullScreen_(nil);
unsafe { }
window.toggleFullScreen_(nil);
}
})
.detach();
} }
fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>) { fn on_input(&self, callback: Box<dyn FnMut(InputEvent) -> bool>) {
@ -1189,7 +1182,7 @@ extern "C" fn handle_view_event(this: &Object, _: Sel, native_event: id) {
lock.synthetic_drag_counter += 1; lock.synthetic_drag_counter += 1;
let executor = lock.executor.clone(); let executor = lock.executor.clone();
executor executor
.spawn_on_main_local(synthetic_drag( .spawn(synthetic_drag(
weak_window_state, weak_window_state,
lock.synthetic_drag_counter, lock.synthetic_drag_counter,
event.clone(), event.clone(),
@ -1317,7 +1310,7 @@ extern "C" fn window_did_change_key_status(this: &Object, selector: Sel, _: id)
let executor = lock.executor.clone(); let executor = lock.executor.clone();
drop(lock); drop(lock);
executor executor
.spawn_on_main_local(async move { .spawn(async move {
let mut lock = window_state.as_ref().lock(); let mut lock = window_state.as_ref().lock();
if let Some(mut callback) = lock.activate_callback.take() { if let Some(mut callback) = lock.activate_callback.take() {
drop(lock); drop(lock);

View file

@ -215,58 +215,3 @@ impl PlatformDispatcher for TestDispatcher {
Some(self) Some(self)
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::Executor;
use std::sync::Arc;
#[test]
fn test_dispatch() {
let dispatcher = TestDispatcher::new(StdRng::seed_from_u64(0));
let executor = Executor::new(Arc::new(dispatcher));
let result = executor.block(async { executor.run_on_main(|| 1).await });
assert_eq!(result, 1);
let result = executor.block({
let executor = executor.clone();
async move {
executor
.spawn_on_main({
let executor = executor.clone();
assert!(executor.is_main_thread());
|| async move {
assert!(executor.is_main_thread());
let result = executor
.spawn({
let executor = executor.clone();
async move {
assert!(!executor.is_main_thread());
let result = executor
.spawn_on_main({
let executor = executor.clone();
|| async move {
assert!(executor.is_main_thread());
2
}
})
.await;
assert!(!executor.is_main_thread());
result
}
})
.await;
assert!(executor.is_main_thread());
result
}
})
.await
}
});
assert_eq!(result, 2);
}
}

View file

@ -1,21 +1,29 @@
use crate::{DisplayId, Executor, Platform, PlatformTextSystem}; use crate::{BackgroundExecutor, DisplayId, ForegroundExecutor, Platform, PlatformTextSystem};
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
use std::sync::Arc; use std::sync::Arc;
pub struct TestPlatform { pub struct TestPlatform {
executor: Executor, background_executor: BackgroundExecutor,
foreground_executor: ForegroundExecutor,
} }
impl TestPlatform { impl TestPlatform {
pub fn new(executor: Executor) -> Self { pub fn new(executor: BackgroundExecutor, foreground_executor: ForegroundExecutor) -> Self {
TestPlatform { executor } TestPlatform {
background_executor: executor,
foreground_executor,
}
} }
} }
// todo!("implement out what our tests needed in GPUI 1") // todo!("implement out what our tests needed in GPUI 1")
impl Platform for TestPlatform { impl Platform for TestPlatform {
fn executor(&self) -> Executor { fn background_executor(&self) -> BackgroundExecutor {
self.executor.clone() self.background_executor.clone()
}
fn foreground_executor(&self) -> ForegroundExecutor {
self.foreground_executor.clone()
} }
fn text_system(&self) -> Arc<dyn PlatformTextSystem> { fn text_system(&self) -> Arc<dyn PlatformTextSystem> {

View file

@ -21,8 +21,8 @@ struct SubscriberSetState<EmitterKey, Callback> {
impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback> impl<EmitterKey, Callback> SubscriberSet<EmitterKey, Callback>
where where
EmitterKey: 'static + Send + Ord + Clone + Debug, EmitterKey: 'static + Ord + Clone + Debug,
Callback: 'static + Send, Callback: 'static,
{ {
pub fn new() -> Self { pub fn new() -> Self {
Self(Arc::new(Mutex::new(SubscriberSetState { Self(Arc::new(Mutex::new(SubscriberSetState {
@ -96,7 +96,7 @@ where
#[must_use] #[must_use]
pub struct Subscription { pub struct Subscription {
unsubscribe: Option<Box<dyn FnOnce() + Send + 'static>>, unsubscribe: Option<Box<dyn FnOnce() + 'static>>,
} }
impl Subscription { impl Subscription {

View file

@ -4,10 +4,13 @@ use crate::{
Size, ViewContext, VisualContext, WeakModel, WindowContext, Size, ViewContext, VisualContext, WeakModel, WindowContext,
}; };
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use std::{any::TypeId, marker::PhantomData}; use std::{
any::{Any, TypeId},
marker::PhantomData,
};
pub trait Render: 'static + Sized { pub trait Render: 'static + Sized {
type Element: Element<Self> + 'static + Send; type Element: Element<Self> + 'static;
fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element; fn render(&mut self, cx: &mut ViewContext<Self>) -> Self::Element;
} }
@ -163,7 +166,7 @@ impl<V: Render, ParentV: 'static> Component<ParentV> for EraseViewState<V, Paren
} }
impl<V: Render, ParentV: 'static> Element<ParentV> for EraseViewState<V, ParentV> { impl<V: Render, ParentV: 'static> Element<ParentV> for EraseViewState<V, ParentV> {
type ElementState = AnyBox; type ElementState = Box<dyn Any>;
fn id(&self) -> Option<crate::ElementId> { fn id(&self) -> Option<crate::ElementId> {
Element::id(&self.view) Element::id(&self.view)
@ -343,7 +346,7 @@ impl<V: Render> From<View<V>> for AnyView {
} }
impl<ParentViewState: 'static> Element<ParentViewState> for AnyView { impl<ParentViewState: 'static> Element<ParentViewState> for AnyView {
type ElementState = AnyBox; type ElementState = Box<dyn Any>;
fn id(&self) -> Option<ElementId> { fn id(&self) -> Option<ElementId> {
Some(self.model.entity_id.into()) Some(self.model.entity_id.into())

View file

@ -3,12 +3,11 @@ use crate::{
Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect, Bounds, BoxShadow, Context, Corners, DevicePixels, DispatchContext, DisplayId, Edges, Effect,
Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId, Entity, EntityId, EventEmitter, FileDropEvent, FocusEvent, FontId, GlobalElementId, GlyphId,
Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId, Hsla, ImageData, InputEvent, IsZero, KeyListener, KeyMatch, KeyMatcher, Keystroke, LayoutId,
MainThread, MainThreadOnly, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, Model, ModelContext, Modifiers, MonochromeSprite, MouseButton, MouseDownEvent, MouseMoveEvent,
MouseDownEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformWindow, Point, PolychromeSprite, Quad,
Point, PolychromeSprite, Quad, Reference, RenderGlyphParams, RenderImageParams, Reference, RenderGlyphParams, RenderImageParams, RenderSvgParams, ScaledPixels, SceneBuilder,
RenderSvgParams, ScaledPixels, SceneBuilder, Shadow, SharedString, Size, Style, Subscription, Shadow, SharedString, Size, Style, Subscription, TaffyLayoutEngine, Task, Underline,
TaffyLayoutEngine, Task, Underline, UnderlineStyle, View, VisualContext, WeakModel, WeakView, UnderlineStyle, View, VisualContext, WeakModel, WeakView, WindowOptions, SUBPIXEL_VARIANTS,
WindowOptions, SUBPIXEL_VARIANTS,
}; };
use anyhow::Result; use anyhow::Result;
use collections::HashMap; use collections::HashMap;
@ -52,7 +51,7 @@ pub enum DispatchPhase {
Capture, Capture,
} }
type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + Send + 'static>; type AnyListener = Box<dyn Fn(&dyn Any, DispatchPhase, &mut WindowContext) + 'static>;
type AnyKeyListener = Box< type AnyKeyListener = Box<
dyn Fn( dyn Fn(
&dyn Any, &dyn Any,
@ -60,10 +59,9 @@ type AnyKeyListener = Box<
DispatchPhase, DispatchPhase,
&mut WindowContext, &mut WindowContext,
) -> Option<Box<dyn Action>> ) -> Option<Box<dyn Action>>
+ Send
+ 'static, + 'static,
>; >;
type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + Send + 'static>; type AnyFocusListener = Box<dyn Fn(&FocusEvent, &mut WindowContext) + 'static>;
slotmap::new_key_type! { pub struct FocusId; } slotmap::new_key_type! { pub struct FocusId; }
@ -159,7 +157,7 @@ impl Drop for FocusHandle {
// Holds the state for a specific window. // Holds the state for a specific window.
pub struct Window { pub struct Window {
handle: AnyWindowHandle, handle: AnyWindowHandle,
platform_window: MainThreadOnly<Box<dyn PlatformWindow>>, platform_window: Box<dyn PlatformWindow>,
display_id: DisplayId, display_id: DisplayId,
sprite_atlas: Arc<dyn PlatformAtlas>, sprite_atlas: Arc<dyn PlatformAtlas>,
rem_size: Pixels, rem_size: Pixels,
@ -194,7 +192,7 @@ impl Window {
pub(crate) fn new( pub(crate) fn new(
handle: AnyWindowHandle, handle: AnyWindowHandle,
options: WindowOptions, options: WindowOptions,
cx: &mut MainThread<AppContext>, cx: &mut AppContext,
) -> Self { ) -> Self {
let platform_window = cx.platform().open_window(handle, options); let platform_window = cx.platform().open_window(handle, options);
let display_id = platform_window.display().id(); let display_id = platform_window.display().id();
@ -209,12 +207,7 @@ impl Window {
cx.window.scale_factor = scale_factor; cx.window.scale_factor = scale_factor;
cx.window.scene_builder = SceneBuilder::new(); cx.window.scene_builder = SceneBuilder::new();
cx.window.content_size = content_size; cx.window.content_size = content_size;
cx.window.display_id = cx cx.window.display_id = cx.window.platform_window.display().id();
.window
.platform_window
.borrow_on_main_thread()
.display()
.id();
cx.window.dirty = true; cx.window.dirty = true;
}) })
.log_err(); .log_err();
@ -230,8 +223,6 @@ impl Window {
}) })
}); });
let platform_window = MainThreadOnly::new(Arc::new(platform_window), cx.executor.clone());
Window { Window {
handle, handle,
platform_window, platform_window,
@ -378,26 +369,6 @@ impl<'a, 'w> WindowContext<'a, 'w> {
self.notify(); self.notify();
} }
/// Schedule the given closure to be run on the main thread. It will be invoked with
/// a `MainThread<WindowContext>`, which provides access to platform-specific functionality
/// of the window.
pub fn run_on_main<R>(
&mut self,
f: impl FnOnce(&mut MainThread<WindowContext<'_, '_>>) -> R + Send + 'static,
) -> Task<Result<R>>
where
R: Send + 'static,
{
if self.executor.is_main_thread() {
Task::ready(Ok(f(unsafe {
mem::transmute::<&mut Self, &mut MainThread<Self>>(self)
})))
} else {
let id = self.window.handle.id;
self.app.run_on_main(move |cx| cx.update_window(id, f))
}
}
/// Create an `AsyncWindowContext`, which has a static lifetime and can be held across /// Create an `AsyncWindowContext`, which has a static lifetime and can be held across
/// await points in async code. /// await points in async code.
pub fn to_async(&self) -> AsyncWindowContext { pub fn to_async(&self) -> AsyncWindowContext {
@ -408,44 +379,39 @@ impl<'a, 'w> WindowContext<'a, 'w> {
pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) { pub fn on_next_frame(&mut self, f: impl FnOnce(&mut WindowContext) + Send + 'static) {
let f = Box::new(f); let f = Box::new(f);
let display_id = self.window.display_id; let display_id = self.window.display_id;
self.run_on_main(move |cx| {
if let Some(callbacks) = cx.next_frame_callbacks.get_mut(&display_id) {
callbacks.push(f);
// If there was already a callback, it means that we already scheduled a frame.
if callbacks.len() > 1 {
return;
}
} else {
let async_cx = cx.to_async();
cx.next_frame_callbacks.insert(display_id, vec![f]);
cx.platform().set_display_link_output_callback(
display_id,
Box::new(move |_current_time, _output_time| {
let _ = async_cx.update(|cx| {
let callbacks = cx
.next_frame_callbacks
.get_mut(&display_id)
.unwrap()
.drain(..)
.collect::<Vec<_>>();
for callback in callbacks {
callback(cx);
}
cx.run_on_main(move |cx| { if let Some(callbacks) = self.next_frame_callbacks.get_mut(&display_id) {
if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() { callbacks.push(f);
cx.platform().stop_display_link(display_id); // If there was already a callback, it means that we already scheduled a frame.
} if callbacks.len() > 1 {
}) return;
.detach();
});
}),
);
} }
} else {
let async_cx = self.to_async();
self.next_frame_callbacks.insert(display_id, vec![f]);
self.platform().set_display_link_output_callback(
display_id,
Box::new(move |_current_time, _output_time| {
let _ = async_cx.update(|cx| {
let callbacks = cx
.next_frame_callbacks
.get_mut(&display_id)
.unwrap()
.drain(..)
.collect::<Vec<_>>();
for callback in callbacks {
callback(cx);
}
cx.platform().start_display_link(display_id); if cx.next_frame_callbacks.get(&display_id).unwrap().is_empty() {
}) cx.platform().stop_display_link(display_id);
.detach(); }
});
}),
);
}
self.platform().start_display_link(display_id);
} }
/// Spawn the future returned by the given closure on the application thread pool. /// Spawn the future returned by the given closure on the application thread pool.
@ -453,17 +419,16 @@ impl<'a, 'w> WindowContext<'a, 'w> {
/// use within your future. /// use within your future.
pub fn spawn<Fut, R>( pub fn spawn<Fut, R>(
&mut self, &mut self,
f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut + Send + 'static, f: impl FnOnce(AnyWindowHandle, AsyncWindowContext) -> Fut,
) -> Task<R> ) -> Task<R>
where where
R: Send + 'static, R: 'static,
Fut: Future<Output = R> + Send + 'static, Fut: Future<Output = R> + 'static,
{ {
let window = self.window.handle; let window = self.window.handle;
self.app.spawn(move |app| { self.app.spawn(move |app| {
let cx = AsyncWindowContext::new(app, window); let cx = AsyncWindowContext::new(app, window);
let future = f(window, cx); f(window, cx)
async move { future.await }
}) })
} }
@ -569,7 +534,7 @@ impl<'a, 'w> WindowContext<'a, 'w> {
/// a specific need to register a global listener. /// a specific need to register a global listener.
pub fn on_mouse_event<Event: 'static>( pub fn on_mouse_event<Event: 'static>(
&mut self, &mut self,
handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + Send + 'static, handler: impl Fn(&Event, DispatchPhase, &mut WindowContext) + 'static,
) { ) {
let order = self.window.z_index_stack.clone(); let order = self.window.z_index_stack.clone();
self.window self.window
@ -906,14 +871,8 @@ impl<'a, 'w> WindowContext<'a, 'w> {
self.window.root_view = Some(root_view); self.window.root_view = Some(root_view);
let scene = self.window.scene_builder.build(); let scene = self.window.scene_builder.build();
self.run_on_main(|cx| { self.window.platform_window.draw(scene);
cx.window self.window.dirty = false;
.platform_window
.borrow_on_main_thread()
.draw(scene);
cx.window.dirty = false;
})
.detach();
} }
fn start_frame(&mut self) { fn start_frame(&mut self) {
@ -1246,7 +1205,7 @@ impl Context for WindowContext<'_, '_> {
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Model<T> ) -> Model<T>
where where
T: 'static + Send, T: 'static,
{ {
let slot = self.app.entities.reserve(); let slot = self.app.entities.reserve();
let model = build_model(&mut ModelContext::mutable(&mut *self.app, slot.downgrade())); let model = build_model(&mut ModelContext::mutable(&mut *self.app, slot.downgrade()));
@ -1276,7 +1235,7 @@ impl VisualContext for WindowContext<'_, '_> {
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V, build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
) -> Self::Result<View<V>> ) -> Self::Result<View<V>>
where where
V: 'static + Send, V: 'static,
{ {
let slot = self.app.entities.reserve(); let slot = self.app.entities.reserve();
let view = View { let view = View {
@ -1422,7 +1381,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
f: impl FnOnce(Option<S>, &mut Self) -> (R, S), f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
) -> R ) -> R
where where
S: 'static + Send, S: 'static,
{ {
self.with_element_id(id, |global_id, cx| { self.with_element_id(id, |global_id, cx| {
if let Some(any) = cx if let Some(any) = cx
@ -1460,7 +1419,7 @@ pub trait BorrowWindow: BorrowMut<Window> + BorrowMut<AppContext> {
f: impl FnOnce(Option<S>, &mut Self) -> (R, S), f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
) -> R ) -> R
where where
S: 'static + Send, S: 'static,
{ {
if let Some(element_id) = element_id { if let Some(element_id) = element_id {
self.with_element_state(element_id, f) self.with_element_state(element_id, f)
@ -1772,30 +1731,13 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
result result
} }
pub fn run_on_main<R>(
&mut self,
view: &mut V,
f: impl FnOnce(&mut V, &mut MainThread<ViewContext<'_, '_, V>>) -> R + Send + 'static,
) -> Task<Result<R>>
where
R: Send + 'static,
{
if self.executor.is_main_thread() {
let cx = unsafe { mem::transmute::<&mut Self, &mut MainThread<Self>>(self) };
Task::ready(Ok(f(view, cx)))
} else {
let view = self.view().upgrade().unwrap();
self.window_cx.run_on_main(move |cx| view.update(cx, f))
}
}
pub fn spawn<Fut, R>( pub fn spawn<Fut, R>(
&mut self, &mut self,
f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut + Send + 'static, f: impl FnOnce(WeakView<V>, AsyncWindowContext) -> Fut,
) -> Task<R> ) -> Task<R>
where where
R: Send + 'static, R: 'static,
Fut: Future<Output = R> + Send + 'static, Fut: Future<Output = R> + 'static,
{ {
let view = self.view(); let view = self.view();
self.window_cx.spawn(move |_, cx| { self.window_cx.spawn(move |_, cx| {
@ -1833,7 +1775,7 @@ impl<'a, 'w, V: 'static> ViewContext<'a, 'w, V> {
pub fn on_mouse_event<Event: 'static>( pub fn on_mouse_event<Event: 'static>(
&mut self, &mut self,
handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + Send + 'static, handler: impl Fn(&mut V, &Event, DispatchPhase, &mut ViewContext<V>) + 'static,
) { ) {
let handle = self.view().upgrade().unwrap(); let handle = self.view().upgrade().unwrap();
self.window_cx.on_mouse_event(move |event, phase, cx| { self.window_cx.on_mouse_event(move |event, phase, cx| {
@ -1862,13 +1804,10 @@ impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
type ModelContext<'b, U> = ModelContext<'b, U>; type ModelContext<'b, U> = ModelContext<'b, U>;
type Result<U> = U; type Result<U> = U;
fn build_model<T>( fn build_model<T: 'static>(
&mut self, &mut self,
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T, build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
) -> Model<T> ) -> Model<T> {
where
T: 'static + Send,
{
self.window_cx.build_model(build_model) self.window_cx.build_model(build_model)
} }
@ -1884,7 +1823,7 @@ impl<'a, 'w, V> Context for ViewContext<'a, 'w, V> {
impl<V: 'static> VisualContext for ViewContext<'_, '_, V> { impl<V: 'static> VisualContext for ViewContext<'_, '_, V> {
type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>; type ViewContext<'a, 'w, V2> = ViewContext<'a, 'w, V2>;
fn build_view<W: 'static + Send>( fn build_view<W: 'static>(
&mut self, &mut self,
build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W, build_view: impl FnOnce(&mut Self::ViewContext<'_, '_, W>) -> W,
) -> Self::Result<View<W>> { ) -> Self::Result<View<W>> {

View file

@ -17,7 +17,7 @@ use futures::{
future::{BoxFuture, Shared}, future::{BoxFuture, Shared},
FutureExt, TryFutureExt as _, FutureExt, TryFutureExt as _,
}; };
use gpui2::{AppContext, AsyncAppContext, Executor, Task}; use gpui2::{AppContext, AsyncAppContext, BackgroundExecutor, Task};
pub use highlight_map::HighlightMap; pub use highlight_map::HighlightMap;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use lsp2::{CodeActionKind, LanguageServerBinary}; use lsp2::{CodeActionKind, LanguageServerBinary};
@ -631,7 +631,7 @@ pub struct LanguageRegistry {
lsp_binary_paths: Mutex< lsp_binary_paths: Mutex<
HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>, HashMap<LanguageServerName, Shared<Task<Result<LanguageServerBinary, Arc<anyhow::Error>>>>>,
>, >,
executor: Option<Executor>, executor: Option<BackgroundExecutor>,
lsp_binary_status_tx: LspBinaryStatusSender, lsp_binary_status_tx: LspBinaryStatusSender,
} }
@ -680,7 +680,7 @@ impl LanguageRegistry {
Self::new(Task::ready(())) Self::new(Task::ready(()))
} }
pub fn set_executor(&mut self, executor: Executor) { pub fn set_executor(&mut self, executor: BackgroundExecutor) {
self.executor = Some(executor); self.executor = Some(executor);
} }
@ -916,7 +916,7 @@ impl LanguageRegistry {
} }
let servers_tx = servers_tx.clone(); let servers_tx = servers_tx.clone();
cx.executor() cx.background_executor()
.spawn(async move { .spawn(async move {
if fake_server if fake_server
.try_receive_notification::<lsp2::notification::Initialized>() .try_receive_notification::<lsp2::notification::Initialized>()

View file

@ -5,7 +5,7 @@ pub use lsp_types::*;
use anyhow::{anyhow, Context, Result}; use anyhow::{anyhow, Context, Result};
use collections::HashMap; use collections::HashMap;
use futures::{channel::oneshot, io::BufWriter, AsyncRead, AsyncWrite, FutureExt}; use futures::{channel::oneshot, io::BufWriter, AsyncRead, AsyncWrite, FutureExt};
use gpui2::{AsyncAppContext, Executor, Task}; use gpui2::{AsyncAppContext, BackgroundExecutor, Task};
use parking_lot::Mutex; use parking_lot::Mutex;
use postage::{barrier, prelude::Stream}; use postage::{barrier, prelude::Stream};
use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde::{de::DeserializeOwned, Deserialize, Serialize};
@ -62,7 +62,7 @@ pub struct LanguageServer {
notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>, notification_handlers: Arc<Mutex<HashMap<&'static str, NotificationHandler>>>,
response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>, response_handlers: Arc<Mutex<Option<HashMap<usize, ResponseHandler>>>>,
io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>, io_handlers: Arc<Mutex<HashMap<usize, IoHandler>>>,
executor: Executor, executor: BackgroundExecutor,
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>, io_tasks: Mutex<Option<(Task<Option<()>>, Task<Option<()>>)>>,
output_done_rx: Mutex<Option<barrier::Receiver>>, output_done_rx: Mutex<Option<barrier::Receiver>>,
@ -248,7 +248,7 @@ impl LanguageServer {
let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task); let (stdout, stderr) = futures::join!(stdout_input_task, stderr_input_task);
stdout.or(stderr) stdout.or(stderr)
}); });
let output_task = cx.executor().spawn({ let output_task = cx.background_executor().spawn({
Self::handle_output( Self::handle_output(
stdin, stdin,
outbound_rx, outbound_rx,
@ -269,7 +269,7 @@ impl LanguageServer {
code_action_kinds, code_action_kinds,
next_id: Default::default(), next_id: Default::default(),
outbound_tx, outbound_tx,
executor: cx.executor().clone(), executor: cx.background_executor().clone(),
io_tasks: Mutex::new(Some((input_task, output_task))), io_tasks: Mutex::new(Some((input_task, output_task))),
output_done_rx: Mutex::new(Some(output_done_rx)), output_done_rx: Mutex::new(Some(output_done_rx)),
root_path: root_path.to_path_buf(), root_path: root_path.to_path_buf(),
@ -670,10 +670,10 @@ impl LanguageServer {
match serde_json::from_str(params) { match serde_json::from_str(params) {
Ok(params) => { Ok(params) => {
let response = f(params, cx.clone()); let response = f(params, cx.clone());
cx.executor() cx.foreground_executor()
.spawn_on_main({ .spawn({
let outbound_tx = outbound_tx.clone(); let outbound_tx = outbound_tx.clone();
move || async move { async move {
let response = match response.await { let response = match response.await {
Ok(result) => Response { Ok(result) => Response {
jsonrpc: JSON_RPC_VERSION, jsonrpc: JSON_RPC_VERSION,
@ -769,7 +769,7 @@ impl LanguageServer {
next_id: &AtomicUsize, next_id: &AtomicUsize,
response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>, response_handlers: &Mutex<Option<HashMap<usize, ResponseHandler>>>,
outbound_tx: &channel::Sender<String>, outbound_tx: &channel::Sender<String>,
executor: &Executor, executor: &BackgroundExecutor,
params: T::Params, params: T::Params,
) -> impl 'static + Future<Output = anyhow::Result<T::Result>> ) -> impl 'static + Future<Output = anyhow::Result<T::Result>>
where where
@ -1048,7 +1048,7 @@ impl FakeLanguageServer {
let result = handler(params, cx.clone()); let result = handler(params, cx.clone());
let responded_tx = responded_tx.clone(); let responded_tx = responded_tx.clone();
async move { async move {
cx.executor().simulate_random_delay().await; cx.background_executor().simulate_random_delay().await;
let result = result.await; let result = result.await;
responded_tx.unbounded_send(()).ok(); responded_tx.unbounded_send(()).ok();
result result

View file

@ -26,8 +26,8 @@ use futures::{
}; };
use globset::{Glob, GlobSet, GlobSetBuilder}; use globset::{Glob, GlobSet, GlobSetBuilder};
use gpui2::{ use gpui2::{
AnyModel, AppContext, AsyncAppContext, Context, Entity, EventEmitter, Executor, Model, AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, Context, Entity, EventEmitter,
ModelContext, Task, WeakModel, Model, ModelContext, Task, WeakModel,
}; };
use itertools::Itertools; use itertools::Itertools;
use language2::{ use language2::{
@ -207,7 +207,7 @@ impl DelayedDebounced {
let previous_task = self.task.take(); let previous_task = self.task.take();
self.task = Some(cx.spawn(move |project, mut cx| async move { self.task = Some(cx.spawn(move |project, mut cx| async move {
let mut timer = cx.executor().timer(delay).fuse(); let mut timer = cx.background_executor().timer(delay).fuse();
if let Some(previous_task) = previous_task { if let Some(previous_task) = previous_task {
previous_task.await; previous_task.await;
} }
@ -1453,7 +1453,7 @@ impl Project {
}; };
if client.send(initial_state).log_err().is_some() { if client.send(initial_state).log_err().is_some() {
let client = client.clone(); let client = client.clone();
cx.executor() cx.background_executor()
.spawn(async move { .spawn(async move {
let mut chunks = split_operations(operations).peekable(); let mut chunks = split_operations(operations).peekable();
while let Some(chunk) = chunks.next() { while let Some(chunk) = chunks.next() {
@ -2436,7 +2436,7 @@ impl Project {
Duration::from_secs(1); Duration::from_secs(1);
let task = cx.spawn(move |this, mut cx| async move { let task = cx.spawn(move |this, mut cx| async move {
cx.executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await; cx.background_executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
if let Some(this) = this.upgrade() { if let Some(this) = this.upgrade() {
this.update(&mut cx, |this, cx| { this.update(&mut cx, |this, cx| {
this.disk_based_diagnostics_finished( this.disk_based_diagnostics_finished(
@ -3477,7 +3477,7 @@ impl Project {
}); });
const PROCESS_TIMEOUT: Duration = Duration::from_secs(5); const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
let mut timeout = cx.executor().timer(PROCESS_TIMEOUT).fuse(); let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
let mut errored = false; let mut errored = false;
if let Some(mut process) = process { if let Some(mut process) = process {
@ -5741,7 +5741,7 @@ impl Project {
async fn background_search( async fn background_search(
unnamed_buffers: Vec<Model<Buffer>>, unnamed_buffers: Vec<Model<Buffer>>,
opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>, opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
executor: Executor, executor: BackgroundExecutor,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
workers: usize, workers: usize,
query: SearchQuery, query: SearchQuery,
@ -6376,7 +6376,7 @@ impl Project {
let snapshot = let snapshot =
worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?; worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
let diff_bases_by_buffer = cx let diff_bases_by_buffer = cx
.executor() .background_executor()
.spawn(async move { .spawn(async move {
future_buffers future_buffers
.into_iter() .into_iter()
@ -7983,7 +7983,7 @@ impl Project {
// Any incomplete buffers have open requests waiting. Request that the host sends // Any incomplete buffers have open requests waiting. Request that the host sends
// creates these buffers for us again to unblock any waiting futures. // creates these buffers for us again to unblock any waiting futures.
for id in incomplete_buffer_ids { for id in incomplete_buffer_ids {
cx.executor() cx.background_executor()
.spawn(client.request(proto::OpenBufferById { project_id, id })) .spawn(client.request(proto::OpenBufferById { project_id, id }))
.detach(); .detach();
} }
@ -8438,7 +8438,7 @@ impl Project {
let fs = self.fs.clone(); let fs = self.fs.clone();
cx.spawn(move |this, mut cx| async move { cx.spawn(move |this, mut cx| async move {
let prettier_dir = match cx let prettier_dir = match cx
.executor() .background_executor()
.spawn(Prettier::locate( .spawn(Prettier::locate(
worktree_path.zip(buffer_path).map( worktree_path.zip(buffer_path).map(
|(worktree_root_path, starting_path)| LocateStart { |(worktree_root_path, starting_path)| LocateStart {

View file

@ -22,7 +22,8 @@ use futures::{
use fuzzy2::CharBag; use fuzzy2::CharBag;
use git::{DOT_GIT, GITIGNORE}; use git::{DOT_GIT, GITIGNORE};
use gpui2::{ use gpui2::{
AppContext, AsyncAppContext, Context, EventEmitter, Executor, Model, ModelContext, Task, AppContext, AsyncAppContext, BackgroundExecutor, Context, EventEmitter, Model, ModelContext,
Task,
}; };
use language2::{ use language2::{
proto::{ proto::{
@ -600,7 +601,7 @@ impl LocalWorktree {
.update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))? .update(&mut cx, |t, cx| t.as_local().unwrap().load(&path, cx))?
.await?; .await?;
let text_buffer = cx let text_buffer = cx
.executor() .background_executor()
.spawn(async move { text::Buffer::new(0, id, contents) }) .spawn(async move { text::Buffer::new(0, id, contents) })
.await; .await;
cx.build_model(|_| Buffer::build(text_buffer, diff_base, Some(Arc::new(file)))) cx.build_model(|_| Buffer::build(text_buffer, diff_base, Some(Arc::new(file))))
@ -888,7 +889,7 @@ impl LocalWorktree {
if let Some(repo) = snapshot.git_repositories.get(&*repo.work_directory) { if let Some(repo) = snapshot.git_repositories.get(&*repo.work_directory) {
let repo = repo.repo_ptr.clone(); let repo = repo.repo_ptr.clone();
index_task = Some( index_task = Some(
cx.executor() cx.background_executor()
.spawn(async move { repo.lock().load_index_text(&repo_path) }), .spawn(async move { repo.lock().load_index_text(&repo_path) }),
); );
} }
@ -3012,7 +3013,7 @@ struct BackgroundScanner {
state: Mutex<BackgroundScannerState>, state: Mutex<BackgroundScannerState>,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
status_updates_tx: UnboundedSender<ScanState>, status_updates_tx: UnboundedSender<ScanState>,
executor: Executor, executor: BackgroundExecutor,
scan_requests_rx: channel::Receiver<ScanRequest>, scan_requests_rx: channel::Receiver<ScanRequest>,
path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>, path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
next_entry_id: Arc<AtomicUsize>, next_entry_id: Arc<AtomicUsize>,
@ -3032,7 +3033,7 @@ impl BackgroundScanner {
next_entry_id: Arc<AtomicUsize>, next_entry_id: Arc<AtomicUsize>,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
status_updates_tx: UnboundedSender<ScanState>, status_updates_tx: UnboundedSender<ScanState>,
executor: Executor, executor: BackgroundExecutor,
scan_requests_rx: channel::Receiver<ScanRequest>, scan_requests_rx: channel::Receiver<ScanRequest>,
path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>, path_prefixes_to_scan_rx: channel::Receiver<Arc<Path>>,
) -> Self { ) -> Self {

View file

@ -34,7 +34,7 @@ impl Connection {
#[cfg(any(test, feature = "test-support"))] #[cfg(any(test, feature = "test-support"))]
pub fn in_memory( pub fn in_memory(
executor: gpui2::Executor, executor: gpui2::BackgroundExecutor,
) -> (Self, Self, std::sync::Arc<std::sync::atomic::AtomicBool>) { ) -> (Self, Self, std::sync::Arc<std::sync::atomic::AtomicBool>) {
use std::sync::{ use std::sync::{
atomic::{AtomicBool, Ordering::SeqCst}, atomic::{AtomicBool, Ordering::SeqCst},
@ -53,7 +53,7 @@ impl Connection {
#[allow(clippy::type_complexity)] #[allow(clippy::type_complexity)]
fn channel( fn channel(
killed: Arc<AtomicBool>, killed: Arc<AtomicBool>,
executor: gpui2::Executor, executor: gpui2::BackgroundExecutor,
) -> ( ) -> (
Box<dyn Send + Unpin + futures::Sink<WebSocketMessage, Error = anyhow::Error>>, Box<dyn Send + Unpin + futures::Sink<WebSocketMessage, Error = anyhow::Error>>,
Box<dyn Send + Unpin + futures::Stream<Item = Result<WebSocketMessage, anyhow::Error>>>, Box<dyn Send + Unpin + futures::Stream<Item = Result<WebSocketMessage, anyhow::Error>>>,

View file

@ -342,7 +342,7 @@ impl Peer {
pub fn add_test_connection( pub fn add_test_connection(
self: &Arc<Self>, self: &Arc<Self>,
connection: Connection, connection: Connection,
executor: gpui2::Executor, executor: gpui2::BackgroundExecutor,
) -> ( ) -> (
ConnectionId, ConnectionId,
impl Future<Output = anyhow::Result<()>> + Send, impl Future<Output = anyhow::Result<()>> + Send,

View file

@ -2,7 +2,7 @@ use crate::{settings_store::SettingsStore, Settings};
use anyhow::Result; use anyhow::Result;
use fs2::Fs; use fs2::Fs;
use futures::{channel::mpsc, StreamExt}; use futures::{channel::mpsc, StreamExt};
use gpui2::{AppContext, Executor}; use gpui2::{AppContext, BackgroundExecutor};
use std::{io::ErrorKind, path::PathBuf, str, sync::Arc, time::Duration}; use std::{io::ErrorKind, path::PathBuf, str, sync::Arc, time::Duration};
use util::{paths, ResultExt}; use util::{paths, ResultExt};
@ -28,7 +28,7 @@ pub fn test_settings() -> String {
} }
pub fn watch_config_file( pub fn watch_config_file(
executor: &Executor, executor: &BackgroundExecutor,
fs: Arc<dyn Fs>, fs: Arc<dyn Fs>,
path: PathBuf, path: PathBuf,
) -> mpsc::UnboundedReceiver<String> { ) -> mpsc::UnboundedReceiver<String> {

View file

@ -336,13 +336,13 @@ mod test {
FOREIGN KEY(dock_pane) REFERENCES panes(pane_id), FOREIGN KEY(dock_pane) REFERENCES panes(pane_id),
FOREIGN KEY(active_pane) REFERENCES panes(pane_id) FOREIGN KEY(active_pane) REFERENCES panes(pane_id)
) STRICT; ) STRICT;
CREATE TABLE panes( CREATE TABLE panes(
pane_id INTEGER PRIMARY KEY, pane_id INTEGER PRIMARY KEY,
workspace_id INTEGER NOT NULL, workspace_id INTEGER NOT NULL,
active INTEGER NOT NULL, -- Boolean active INTEGER NOT NULL, -- Boolean
FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id) FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
ON DELETE CASCADE ON DELETE CASCADE
ON UPDATE CASCADE ON UPDATE CASCADE
) STRICT; ) STRICT;
"] "]

View file

@ -133,9 +133,9 @@ impl<'a> VimTestContext<'a> {
) -> futures::channel::mpsc::UnboundedReceiver<()> ) -> futures::channel::mpsc::UnboundedReceiver<()>
where where
T: 'static + request::Request, T: 'static + request::Request,
T::Params: 'static + Send, T::Params: 'static,
F: 'static + Send + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut, F: 'static + FnMut(lsp::Url, T::Params, gpui::AsyncAppContext) -> Fut,
Fut: 'static + Send + Future<Output = Result<T::Result>>, Fut: 'static + Future<Output = Result<T::Result>>,
{ {
self.cx.handle_request::<T, F, Fut>(handler) self.cx.handle_request::<T, F, Fut>(handler)
} }

View file

@ -62,20 +62,26 @@ fn main() {
log::info!("========== starting zed =========="); log::info!("========== starting zed ==========");
let app = App::production(Arc::new(Assets)); let app = App::production(Arc::new(Assets));
let installation_id = app.executor().block(installation_id()).ok(); let installation_id = app.background_executor().block(installation_id()).ok();
let session_id = Uuid::new_v4().to_string(); let session_id = Uuid::new_v4().to_string();
init_panic_hook(&app, installation_id.clone(), session_id.clone()); init_panic_hook(&app, installation_id.clone(), session_id.clone());
let fs = Arc::new(RealFs); let fs = Arc::new(RealFs);
let user_settings_file_rx = let user_settings_file_rx = watch_config_file(
watch_config_file(&app.executor(), fs.clone(), paths::SETTINGS.clone()); &app.background_executor(),
let _user_keymap_file_rx = fs.clone(),
watch_config_file(&app.executor(), fs.clone(), paths::KEYMAP.clone()); paths::SETTINGS.clone(),
);
let _user_keymap_file_rx = watch_config_file(
&app.background_executor(),
fs.clone(),
paths::KEYMAP.clone(),
);
let login_shell_env_loaded = if stdout_is_a_pty() { let login_shell_env_loaded = if stdout_is_a_pty() {
Task::ready(()) Task::ready(())
} else { } else {
app.executor().spawn(async { app.background_executor().spawn(async {
load_login_shell_environment().await.log_err(); load_login_shell_environment().await.log_err();
}) })
}; };