Merge branch 'main' into n/t2
This commit is contained in:
commit
3b91a76159
71 changed files with 2217 additions and 2376 deletions
45
.github/workflows/release_actions.yml
vendored
45
.github/workflows/release_actions.yml
vendored
|
@ -6,26 +6,27 @@ jobs:
|
||||||
discord_release:
|
discord_release:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Get release URL
|
- name: Get release URL
|
||||||
id: get-release-url
|
id: get-release-url
|
||||||
run: |
|
run: |
|
||||||
if [ "${{ github.event.release.prerelease }}" == "true" ]; then
|
if [ "${{ github.event.release.prerelease }}" == "true" ]; then
|
||||||
URL="https://zed.dev/releases/preview/latest"
|
URL="https://zed.dev/releases/preview/latest"
|
||||||
else
|
else
|
||||||
URL="https://zed.dev/releases/stable/latest"
|
URL="https://zed.dev/releases/stable/latest"
|
||||||
fi
|
fi
|
||||||
echo "::set-output name=URL::$URL"
|
echo "::set-output name=URL::$URL"
|
||||||
- name: Get content
|
- name: Get content
|
||||||
uses: 2428392/gh-truncate-string-action@v1.2.0
|
uses: 2428392/gh-truncate-string-action@v1.3.0
|
||||||
id: get-content
|
id: get-content
|
||||||
with:
|
with:
|
||||||
stringToTruncate: |
|
stringToTruncate: |
|
||||||
📣 Zed [${{ github.event.release.tag_name }}](${{ steps.get-release-url.outputs.URL }}) was just released!
|
📣 Zed [${{ github.event.release.tag_name }}](${{ steps.get-release-url.outputs.URL }}) was just released!
|
||||||
|
|
||||||
${{ github.event.release.body }}
|
${{ github.event.release.body }}
|
||||||
maxLength: 2000
|
maxLength: 2000
|
||||||
- name: Discord Webhook Action
|
truncationSymbol: "..."
|
||||||
uses: tsickert/discord-webhook@v5.3.0
|
- name: Discord Webhook Action
|
||||||
with:
|
uses: tsickert/discord-webhook@v5.3.0
|
||||||
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
with:
|
||||||
content: ${{ steps.get-content.outputs.string }}
|
webhook-url: ${{ secrets.DISCORD_WEBHOOK_URL }}
|
||||||
|
content: ${{ steps.get-content.outputs.string }}
|
||||||
|
|
2
Cargo.lock
generated
2
Cargo.lock
generated
|
@ -1603,7 +1603,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "collab"
|
name = "collab"
|
||||||
version = "0.27.0"
|
version = "0.28.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"async-trait",
|
"async-trait",
|
||||||
|
|
|
@ -153,10 +153,17 @@ impl FakeCompletionProvider {
|
||||||
|
|
||||||
pub fn send_completion(&self, completion: impl Into<String>) {
|
pub fn send_completion(&self, completion: impl Into<String>) {
|
||||||
let mut tx = self.last_completion_tx.lock();
|
let mut tx = self.last_completion_tx.lock();
|
||||||
tx.as_mut().unwrap().try_send(completion.into()).unwrap();
|
|
||||||
|
println!("COMPLETION TX: {:?}", &tx);
|
||||||
|
|
||||||
|
let a = tx.as_mut().unwrap();
|
||||||
|
a.try_send(completion.into()).unwrap();
|
||||||
|
|
||||||
|
// tx.as_mut().unwrap().try_send(completion.into()).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn finish_completion(&self) {
|
pub fn finish_completion(&self) {
|
||||||
|
println!("FINISHING COMPLETION");
|
||||||
self.last_completion_tx.lock().take().unwrap();
|
self.last_completion_tx.lock().take().unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -181,8 +188,10 @@ impl CompletionProvider for FakeCompletionProvider {
|
||||||
&self,
|
&self,
|
||||||
_prompt: Box<dyn CompletionRequest>,
|
_prompt: Box<dyn CompletionRequest>,
|
||||||
) -> BoxFuture<'static, anyhow::Result<BoxStream<'static, anyhow::Result<String>>>> {
|
) -> BoxFuture<'static, anyhow::Result<BoxStream<'static, anyhow::Result<String>>>> {
|
||||||
|
println!("COMPLETING");
|
||||||
let (tx, rx) = mpsc::channel(1);
|
let (tx, rx) = mpsc::channel(1);
|
||||||
*self.last_completion_tx.lock() = Some(tx);
|
*self.last_completion_tx.lock() = Some(tx);
|
||||||
|
println!("TX: {:?}", *self.last_completion_tx.lock());
|
||||||
async move { Ok(rx.map(|rx| Ok(rx)).boxed()) }.boxed()
|
async move { Ok(rx.map(|rx| Ok(rx)).boxed()) }.boxed()
|
||||||
}
|
}
|
||||||
fn box_clone(&self) -> Box<dyn CompletionProvider> {
|
fn box_clone(&self) -> Box<dyn CompletionProvider> {
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
use async_trait::async_trait;
|
|
||||||
use gpui2::AppContext;
|
use gpui2::AppContext;
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
|
@ -8,10 +7,9 @@ pub enum ProviderCredential {
|
||||||
NotNeeded,
|
NotNeeded,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
pub trait CredentialProvider {
|
||||||
pub trait CredentialProvider: Send + Sync {
|
|
||||||
fn has_credentials(&self) -> bool;
|
fn has_credentials(&self) -> bool;
|
||||||
async fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential;
|
fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential;
|
||||||
async fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential);
|
fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential);
|
||||||
async fn delete_credentials(&self, cx: &mut AppContext);
|
fn delete_credentials(&self, cx: &mut AppContext);
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,10 +1,9 @@
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use async_trait::async_trait;
|
|
||||||
use futures::{
|
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 +104,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 +197,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 {
|
||||||
|
@ -213,7 +212,6 @@ impl OpenAICompletionProvider {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl CredentialProvider for OpenAICompletionProvider {
|
impl CredentialProvider for OpenAICompletionProvider {
|
||||||
fn has_credentials(&self) -> bool {
|
fn has_credentials(&self) -> bool {
|
||||||
match *self.credential.read() {
|
match *self.credential.read() {
|
||||||
|
@ -221,52 +219,45 @@ impl CredentialProvider for OpenAICompletionProvider {
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential {
|
|
||||||
|
fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential {
|
||||||
let existing_credential = self.credential.read().clone();
|
let existing_credential = self.credential.read().clone();
|
||||||
|
let retrieved_credential = match existing_credential {
|
||||||
let retrieved_credential = cx
|
ProviderCredential::Credentials { .. } => existing_credential.clone(),
|
||||||
.run_on_main(move |cx| match existing_credential {
|
_ => {
|
||||||
ProviderCredential::Credentials { .. } => {
|
if let Some(api_key) = env::var("OPENAI_API_KEY").log_err() {
|
||||||
return existing_credential.clone();
|
ProviderCredential::Credentials { api_key }
|
||||||
}
|
} else if let Some(Some((_, api_key))) =
|
||||||
_ => {
|
cx.read_credentials(OPENAI_API_URL).log_err()
|
||||||
if let Some(api_key) = env::var("OPENAI_API_KEY").log_err() {
|
{
|
||||||
return ProviderCredential::Credentials { api_key };
|
if let Some(api_key) = String::from_utf8(api_key).log_err() {
|
||||||
}
|
ProviderCredential::Credentials { api_key }
|
||||||
|
|
||||||
if let Some(Some((_, api_key))) = cx.read_credentials(OPENAI_API_URL).log_err()
|
|
||||||
{
|
|
||||||
if let Some(api_key) = String::from_utf8(api_key).log_err() {
|
|
||||||
return ProviderCredential::Credentials { api_key };
|
|
||||||
} else {
|
|
||||||
return ProviderCredential::NoCredentials;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
return ProviderCredential::NoCredentials;
|
ProviderCredential::NoCredentials
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
ProviderCredential::NoCredentials
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
.await;
|
};
|
||||||
|
|
||||||
*self.credential.write() = retrieved_credential.clone();
|
*self.credential.write() = retrieved_credential.clone();
|
||||||
retrieved_credential
|
retrieved_credential
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential) {
|
fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential) {
|
||||||
*self.credential.write() = credential.clone();
|
*self.credential.write() = credential.clone();
|
||||||
let credential = credential.clone();
|
let credential = credential.clone();
|
||||||
cx.run_on_main(move |cx| match credential {
|
match credential {
|
||||||
ProviderCredential::Credentials { api_key } => {
|
ProviderCredential::Credentials { api_key } => {
|
||||||
cx.write_credentials(OPENAI_API_URL, "Bearer", api_key.as_bytes())
|
cx.write_credentials(OPENAI_API_URL, "Bearer", api_key.as_bytes())
|
||||||
.log_err();
|
.log_err();
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
})
|
}
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
async fn delete_credentials(&self, cx: &mut AppContext) {
|
|
||||||
cx.run_on_main(move |cx| cx.delete_credentials(OPENAI_API_URL).log_err())
|
fn delete_credentials(&self, cx: &mut AppContext) {
|
||||||
.await;
|
cx.delete_credentials(OPENAI_API_URL).log_err();
|
||||||
*self.credential.write() = ProviderCredential::NoCredentials;
|
*self.credential.write() = ProviderCredential::NoCredentials;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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));
|
||||||
|
|
||||||
|
@ -146,7 +146,6 @@ impl OpenAIEmbeddingProvider {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl CredentialProvider for OpenAIEmbeddingProvider {
|
impl CredentialProvider for OpenAIEmbeddingProvider {
|
||||||
fn has_credentials(&self) -> bool {
|
fn has_credentials(&self) -> bool {
|
||||||
match *self.credential.read() {
|
match *self.credential.read() {
|
||||||
|
@ -154,52 +153,45 @@ impl CredentialProvider for OpenAIEmbeddingProvider {
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential {
|
fn retrieve_credentials(&self, cx: &mut AppContext) -> ProviderCredential {
|
||||||
let existing_credential = self.credential.read().clone();
|
let existing_credential = self.credential.read().clone();
|
||||||
|
|
||||||
let retrieved_credential = cx
|
let retrieved_credential = match existing_credential {
|
||||||
.run_on_main(move |cx| match existing_credential {
|
ProviderCredential::Credentials { .. } => existing_credential.clone(),
|
||||||
ProviderCredential::Credentials { .. } => {
|
_ => {
|
||||||
return existing_credential.clone();
|
if let Some(api_key) = env::var("OPENAI_API_KEY").log_err() {
|
||||||
}
|
ProviderCredential::Credentials { api_key }
|
||||||
_ => {
|
} else if let Some(Some((_, api_key))) =
|
||||||
if let Some(api_key) = env::var("OPENAI_API_KEY").log_err() {
|
cx.read_credentials(OPENAI_API_URL).log_err()
|
||||||
return ProviderCredential::Credentials { api_key };
|
{
|
||||||
}
|
if let Some(api_key) = String::from_utf8(api_key).log_err() {
|
||||||
|
ProviderCredential::Credentials { api_key }
|
||||||
if let Some(Some((_, api_key))) = cx.read_credentials(OPENAI_API_URL).log_err()
|
|
||||||
{
|
|
||||||
if let Some(api_key) = String::from_utf8(api_key).log_err() {
|
|
||||||
return ProviderCredential::Credentials { api_key };
|
|
||||||
} else {
|
|
||||||
return ProviderCredential::NoCredentials;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
return ProviderCredential::NoCredentials;
|
ProviderCredential::NoCredentials
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
ProviderCredential::NoCredentials
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
.await;
|
};
|
||||||
|
|
||||||
*self.credential.write() = retrieved_credential.clone();
|
*self.credential.write() = retrieved_credential.clone();
|
||||||
retrieved_credential
|
retrieved_credential
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential) {
|
fn save_credentials(&self, cx: &mut AppContext, credential: ProviderCredential) {
|
||||||
*self.credential.write() = credential.clone();
|
*self.credential.write() = credential.clone();
|
||||||
let credential = credential.clone();
|
match credential {
|
||||||
cx.run_on_main(move |cx| match credential {
|
|
||||||
ProviderCredential::Credentials { api_key } => {
|
ProviderCredential::Credentials { api_key } => {
|
||||||
cx.write_credentials(OPENAI_API_URL, "Bearer", api_key.as_bytes())
|
cx.write_credentials(OPENAI_API_URL, "Bearer", api_key.as_bytes())
|
||||||
.log_err();
|
.log_err();
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
})
|
}
|
||||||
.await;
|
|
||||||
}
|
}
|
||||||
async fn delete_credentials(&self, cx: &mut AppContext) {
|
|
||||||
cx.run_on_main(move |cx| cx.delete_credentials(OPENAI_API_URL).log_err())
|
fn delete_credentials(&self, cx: &mut AppContext) {
|
||||||
.await;
|
cx.delete_credentials(OPENAI_API_URL).log_err();
|
||||||
*self.credential.write() = ProviderCredential::NoCredentials;
|
*self.credential.write() = ProviderCredential::NoCredentials;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -100,16 +100,15 @@ impl FakeEmbeddingProvider {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl CredentialProvider for FakeEmbeddingProvider {
|
impl CredentialProvider for FakeEmbeddingProvider {
|
||||||
fn has_credentials(&self) -> bool {
|
fn has_credentials(&self) -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
async fn retrieve_credentials(&self, _cx: &mut AppContext) -> ProviderCredential {
|
fn retrieve_credentials(&self, _cx: &mut AppContext) -> ProviderCredential {
|
||||||
ProviderCredential::NotNeeded
|
ProviderCredential::NotNeeded
|
||||||
}
|
}
|
||||||
async fn save_credentials(&self, _cx: &mut AppContext, _credential: ProviderCredential) {}
|
fn save_credentials(&self, _cx: &mut AppContext, _credential: ProviderCredential) {}
|
||||||
async fn delete_credentials(&self, _cx: &mut AppContext) {}
|
fn delete_credentials(&self, _cx: &mut AppContext) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait]
|
||||||
|
@ -162,16 +161,15 @@ impl FakeCompletionProvider {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
|
||||||
impl CredentialProvider for FakeCompletionProvider {
|
impl CredentialProvider for FakeCompletionProvider {
|
||||||
fn has_credentials(&self) -> bool {
|
fn has_credentials(&self) -> bool {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
async fn retrieve_credentials(&self, _cx: &mut AppContext) -> ProviderCredential {
|
fn retrieve_credentials(&self, _cx: &mut AppContext) -> ProviderCredential {
|
||||||
ProviderCredential::NotNeeded
|
ProviderCredential::NotNeeded
|
||||||
}
|
}
|
||||||
async fn save_credentials(&self, _cx: &mut AppContext, _credential: ProviderCredential) {}
|
fn save_credentials(&self, _cx: &mut AppContext, _credential: ProviderCredential) {}
|
||||||
async fn delete_credentials(&self, _cx: &mut AppContext) {}
|
fn delete_credentials(&self, _cx: &mut AppContext) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CompletionProvider for FakeCompletionProvider {
|
impl CompletionProvider for FakeCompletionProvider {
|
||||||
|
|
|
@ -142,7 +142,7 @@ pub struct AssistantPanel {
|
||||||
zoomed: bool,
|
zoomed: bool,
|
||||||
has_focus: bool,
|
has_focus: bool,
|
||||||
toolbar: ViewHandle<Toolbar>,
|
toolbar: ViewHandle<Toolbar>,
|
||||||
completion_provider: Box<dyn CompletionProvider>,
|
completion_provider: Arc<dyn CompletionProvider>,
|
||||||
api_key_editor: Option<ViewHandle<Editor>>,
|
api_key_editor: Option<ViewHandle<Editor>>,
|
||||||
languages: Arc<LanguageRegistry>,
|
languages: Arc<LanguageRegistry>,
|
||||||
fs: Arc<dyn Fs>,
|
fs: Arc<dyn Fs>,
|
||||||
|
@ -204,7 +204,7 @@ impl AssistantPanel {
|
||||||
|
|
||||||
let semantic_index = SemanticIndex::global(cx);
|
let semantic_index = SemanticIndex::global(cx);
|
||||||
// Defaulting currently to GPT4, allow for this to be set via config.
|
// Defaulting currently to GPT4, allow for this to be set via config.
|
||||||
let completion_provider = Box::new(OpenAICompletionProvider::new(
|
let completion_provider = Arc::new(OpenAICompletionProvider::new(
|
||||||
"gpt-4",
|
"gpt-4",
|
||||||
cx.background().clone(),
|
cx.background().clone(),
|
||||||
));
|
));
|
||||||
|
@ -259,7 +259,13 @@ impl AssistantPanel {
|
||||||
cx: &mut ViewContext<Workspace>,
|
cx: &mut ViewContext<Workspace>,
|
||||||
) {
|
) {
|
||||||
let this = if let Some(this) = workspace.panel::<AssistantPanel>(cx) {
|
let this = if let Some(this) = workspace.panel::<AssistantPanel>(cx) {
|
||||||
if this.update(cx, |assistant, _| assistant.has_credentials()) {
|
if this.update(cx, |assistant, cx| {
|
||||||
|
if !assistant.has_credentials() {
|
||||||
|
assistant.load_credentials(cx);
|
||||||
|
};
|
||||||
|
|
||||||
|
assistant.has_credentials()
|
||||||
|
}) {
|
||||||
this
|
this
|
||||||
} else {
|
} else {
|
||||||
workspace.focus_panel::<AssistantPanel>(cx);
|
workspace.focus_panel::<AssistantPanel>(cx);
|
||||||
|
@ -320,13 +326,10 @@ impl AssistantPanel {
|
||||||
};
|
};
|
||||||
|
|
||||||
let inline_assist_id = post_inc(&mut self.next_inline_assist_id);
|
let inline_assist_id = post_inc(&mut self.next_inline_assist_id);
|
||||||
let provider = Arc::new(OpenAICompletionProvider::new(
|
let provider = self.completion_provider.clone();
|
||||||
"gpt-4",
|
|
||||||
cx.background().clone(),
|
|
||||||
));
|
|
||||||
|
|
||||||
// Retrieve Credentials Authenticates the Provider
|
// Retrieve Credentials Authenticates the Provider
|
||||||
// provider.retrieve_credentials(cx);
|
provider.retrieve_credentials(cx);
|
||||||
|
|
||||||
let codegen = cx.add_model(|cx| {
|
let codegen = cx.add_model(|cx| {
|
||||||
Codegen::new(editor.read(cx).buffer().clone(), codegen_kind, provider, cx)
|
Codegen::new(editor.read(cx).buffer().clone(), codegen_kind, provider, cx)
|
||||||
|
@ -1439,7 +1442,7 @@ struct Conversation {
|
||||||
pending_save: Task<Result<()>>,
|
pending_save: Task<Result<()>>,
|
||||||
path: Option<PathBuf>,
|
path: Option<PathBuf>,
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
completion_provider: Box<dyn CompletionProvider>,
|
completion_provider: Arc<dyn CompletionProvider>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Entity for Conversation {
|
impl Entity for Conversation {
|
||||||
|
@ -1450,7 +1453,7 @@ impl Conversation {
|
||||||
fn new(
|
fn new(
|
||||||
language_registry: Arc<LanguageRegistry>,
|
language_registry: Arc<LanguageRegistry>,
|
||||||
cx: &mut ModelContext<Self>,
|
cx: &mut ModelContext<Self>,
|
||||||
completion_provider: Box<dyn CompletionProvider>,
|
completion_provider: Arc<dyn CompletionProvider>,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let markdown = language_registry.language_for_name("Markdown");
|
let markdown = language_registry.language_for_name("Markdown");
|
||||||
let buffer = cx.add_model(|cx| {
|
let buffer = cx.add_model(|cx| {
|
||||||
|
@ -1544,7 +1547,7 @@ impl Conversation {
|
||||||
None => Some(Uuid::new_v4().to_string()),
|
None => Some(Uuid::new_v4().to_string()),
|
||||||
};
|
};
|
||||||
let model = saved_conversation.model;
|
let model = saved_conversation.model;
|
||||||
let completion_provider: Box<dyn CompletionProvider> = Box::new(
|
let completion_provider: Arc<dyn CompletionProvider> = Arc::new(
|
||||||
OpenAICompletionProvider::new(model.full_name(), cx.background().clone()),
|
OpenAICompletionProvider::new(model.full_name(), cx.background().clone()),
|
||||||
);
|
);
|
||||||
completion_provider.retrieve_credentials(cx);
|
completion_provider.retrieve_credentials(cx);
|
||||||
|
@ -2201,7 +2204,7 @@ struct ConversationEditor {
|
||||||
|
|
||||||
impl ConversationEditor {
|
impl ConversationEditor {
|
||||||
fn new(
|
fn new(
|
||||||
completion_provider: Box<dyn CompletionProvider>,
|
completion_provider: Arc<dyn CompletionProvider>,
|
||||||
language_registry: Arc<LanguageRegistry>,
|
language_registry: Arc<LanguageRegistry>,
|
||||||
fs: Arc<dyn Fs>,
|
fs: Arc<dyn Fs>,
|
||||||
workspace: WeakViewHandle<Workspace>,
|
workspace: WeakViewHandle<Workspace>,
|
||||||
|
@ -3406,7 +3409,7 @@ mod tests {
|
||||||
init(cx);
|
init(cx);
|
||||||
let registry = Arc::new(LanguageRegistry::test());
|
let registry = Arc::new(LanguageRegistry::test());
|
||||||
|
|
||||||
let completion_provider = Box::new(FakeCompletionProvider::new());
|
let completion_provider = Arc::new(FakeCompletionProvider::new());
|
||||||
let conversation = cx.add_model(|cx| Conversation::new(registry, cx, completion_provider));
|
let conversation = cx.add_model(|cx| Conversation::new(registry, cx, completion_provider));
|
||||||
let buffer = conversation.read(cx).buffer.clone();
|
let buffer = conversation.read(cx).buffer.clone();
|
||||||
|
|
||||||
|
@ -3535,7 +3538,7 @@ mod tests {
|
||||||
cx.set_global(SettingsStore::test(cx));
|
cx.set_global(SettingsStore::test(cx));
|
||||||
init(cx);
|
init(cx);
|
||||||
let registry = Arc::new(LanguageRegistry::test());
|
let registry = Arc::new(LanguageRegistry::test());
|
||||||
let completion_provider = Box::new(FakeCompletionProvider::new());
|
let completion_provider = Arc::new(FakeCompletionProvider::new());
|
||||||
|
|
||||||
let conversation = cx.add_model(|cx| Conversation::new(registry, cx, completion_provider));
|
let conversation = cx.add_model(|cx| Conversation::new(registry, cx, completion_provider));
|
||||||
let buffer = conversation.read(cx).buffer.clone();
|
let buffer = conversation.read(cx).buffer.clone();
|
||||||
|
@ -3633,7 +3636,7 @@ mod tests {
|
||||||
cx.set_global(SettingsStore::test(cx));
|
cx.set_global(SettingsStore::test(cx));
|
||||||
init(cx);
|
init(cx);
|
||||||
let registry = Arc::new(LanguageRegistry::test());
|
let registry = Arc::new(LanguageRegistry::test());
|
||||||
let completion_provider = Box::new(FakeCompletionProvider::new());
|
let completion_provider = Arc::new(FakeCompletionProvider::new());
|
||||||
let conversation = cx.add_model(|cx| Conversation::new(registry, cx, completion_provider));
|
let conversation = cx.add_model(|cx| Conversation::new(registry, cx, completion_provider));
|
||||||
let buffer = conversation.read(cx).buffer.clone();
|
let buffer = conversation.read(cx).buffer.clone();
|
||||||
|
|
||||||
|
@ -3716,7 +3719,7 @@ mod tests {
|
||||||
cx.set_global(SettingsStore::test(cx));
|
cx.set_global(SettingsStore::test(cx));
|
||||||
init(cx);
|
init(cx);
|
||||||
let registry = Arc::new(LanguageRegistry::test());
|
let registry = Arc::new(LanguageRegistry::test());
|
||||||
let completion_provider = Box::new(FakeCompletionProvider::new());
|
let completion_provider = Arc::new(FakeCompletionProvider::new());
|
||||||
let conversation =
|
let conversation =
|
||||||
cx.add_model(|cx| Conversation::new(registry.clone(), cx, completion_provider));
|
cx.add_model(|cx| Conversation::new(registry.clone(), cx, completion_provider));
|
||||||
let buffer = conversation.read(cx).buffer.clone();
|
let buffer = conversation.read(cx).buffer.clone();
|
||||||
|
|
|
@ -367,6 +367,8 @@ fn strip_invalid_spans_from_codeblock(
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use ai::test::FakeCompletionProvider;
|
use ai::test::FakeCompletionProvider;
|
||||||
use futures::stream::{self};
|
use futures::stream::{self};
|
||||||
|
@ -437,6 +439,7 @@ mod tests {
|
||||||
let max_len = cmp::min(new_text.len(), 10);
|
let max_len = cmp::min(new_text.len(), 10);
|
||||||
let len = rng.gen_range(1..=max_len);
|
let len = rng.gen_range(1..=max_len);
|
||||||
let (chunk, suffix) = new_text.split_at(len);
|
let (chunk, suffix) = new_text.split_at(len);
|
||||||
|
println!("CHUNK: {:?}", &chunk);
|
||||||
provider.send_completion(chunk);
|
provider.send_completion(chunk);
|
||||||
new_text = suffix;
|
new_text = suffix;
|
||||||
deterministic.run_until_parked();
|
deterministic.run_until_parked();
|
||||||
|
@ -569,6 +572,7 @@ mod tests {
|
||||||
let max_len = cmp::min(new_text.len(), 10);
|
let max_len = cmp::min(new_text.len(), 10);
|
||||||
let len = rng.gen_range(1..=max_len);
|
let len = rng.gen_range(1..=max_len);
|
||||||
let (chunk, suffix) = new_text.split_at(len);
|
let (chunk, suffix) = new_text.split_at(len);
|
||||||
|
println!("{:?}", &chunk);
|
||||||
provider.send_completion(chunk);
|
provider.send_completion(chunk);
|
||||||
new_text = suffix;
|
new_text = suffix;
|
||||||
deterministic.run_until_parked();
|
deterministic.run_until_parked();
|
||||||
|
|
|
@ -1,14 +1,13 @@
|
||||||
use assets::SoundRegistry;
|
use assets::SoundRegistry;
|
||||||
use futures::{channel::mpsc, StreamExt};
|
use gpui2::{AppContext, AssetSource};
|
||||||
use gpui2::{AppContext, AssetSource, Executor};
|
|
||||||
use rodio::{OutputStream, OutputStreamHandle};
|
use rodio::{OutputStream, OutputStreamHandle};
|
||||||
use util::ResultExt;
|
use util::ResultExt;
|
||||||
|
|
||||||
mod assets;
|
mod assets;
|
||||||
|
|
||||||
pub fn init(source: impl AssetSource, cx: &mut AppContext) {
|
pub fn init(source: impl AssetSource, cx: &mut AppContext) {
|
||||||
cx.set_global(Audio::new(cx.executor()));
|
|
||||||
cx.set_global(SoundRegistry::new(source));
|
cx.set_global(SoundRegistry::new(source));
|
||||||
|
cx.set_global(Audio::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Sound {
|
pub enum Sound {
|
||||||
|
@ -34,15 +33,18 @@ impl Sound {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Audio {
|
pub struct Audio {
|
||||||
tx: mpsc::UnboundedSender<Box<dyn FnOnce(&mut AudioState) + Send>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct AudioState {
|
|
||||||
_output_stream: Option<OutputStream>,
|
_output_stream: Option<OutputStream>,
|
||||||
output_handle: Option<OutputStreamHandle>,
|
output_handle: Option<OutputStreamHandle>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AudioState {
|
impl Audio {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
_output_stream: None,
|
||||||
|
output_handle: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn ensure_output_exists(&mut self) -> Option<&OutputStreamHandle> {
|
fn ensure_output_exists(&mut self) -> Option<&OutputStreamHandle> {
|
||||||
if self.output_handle.is_none() {
|
if self.output_handle.is_none() {
|
||||||
let (_output_stream, output_handle) = OutputStream::try_default().log_err().unzip();
|
let (_output_stream, output_handle) = OutputStream::try_default().log_err().unzip();
|
||||||
|
@ -53,59 +55,27 @@ impl AudioState {
|
||||||
self.output_handle.as_ref()
|
self.output_handle.as_ref()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn take(&mut self) {
|
|
||||||
self._output_stream.take();
|
|
||||||
self.output_handle.take();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Audio {
|
|
||||||
pub fn new(executor: &Executor) -> Self {
|
|
||||||
let (tx, mut rx) = mpsc::unbounded::<Box<dyn FnOnce(&mut AudioState) + Send>>();
|
|
||||||
executor
|
|
||||||
.spawn_on_main(|| async move {
|
|
||||||
let mut audio = AudioState {
|
|
||||||
_output_stream: None,
|
|
||||||
output_handle: None,
|
|
||||||
};
|
|
||||||
|
|
||||||
while let Some(f) = rx.next().await {
|
|
||||||
(f)(&mut audio);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.detach();
|
|
||||||
|
|
||||||
Self { tx }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn play_sound(sound: Sound, cx: &mut AppContext) {
|
pub fn play_sound(sound: Sound, cx: &mut AppContext) {
|
||||||
if !cx.has_global::<Self>() {
|
if !cx.has_global::<Self>() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(source) = SoundRegistry::global(cx).get(sound.file()).log_err() else {
|
cx.update_global::<Self, _>(|this, cx| {
|
||||||
return;
|
let output_handle = this.ensure_output_exists()?;
|
||||||
};
|
let source = SoundRegistry::global(cx).get(sound.file()).log_err()?;
|
||||||
|
output_handle.play_raw(source).log_err()?;
|
||||||
let this = cx.global::<Self>();
|
Some(())
|
||||||
this.tx
|
});
|
||||||
.unbounded_send(Box::new(move |state| {
|
|
||||||
if let Some(output_handle) = state.ensure_output_exists() {
|
|
||||||
output_handle.play_raw(source).log_err();
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn end_call(cx: &AppContext) {
|
pub fn end_call(cx: &mut AppContext) {
|
||||||
if !cx.has_global::<Self>() {
|
if !cx.has_global::<Self>() {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let this = cx.global::<Self>();
|
cx.update_global::<Self, _>(|this, _| {
|
||||||
|
this._output_stream.take();
|
||||||
this.tx
|
this.output_handle.take();
|
||||||
.unbounded_send(Box::new(move |state| state.take()))
|
});
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -196,7 +196,7 @@ impl ActiveCall {
|
||||||
})
|
})
|
||||||
.shared();
|
.shared();
|
||||||
self.pending_room_creation = Some(room.clone());
|
self.pending_room_creation = Some(room.clone());
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
room.await.map_err(|err| anyhow!("{:?}", err))?;
|
room.await.map_err(|err| anyhow!("{:?}", err))?;
|
||||||
anyhow::Ok(())
|
anyhow::Ok(())
|
||||||
})
|
})
|
||||||
|
@ -230,7 +230,7 @@ impl ActiveCall {
|
||||||
};
|
};
|
||||||
|
|
||||||
let client = self.client.clone();
|
let client = self.client.clone();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
client
|
client
|
||||||
.request(proto::CancelCall {
|
.request(proto::CancelCall {
|
||||||
room_id,
|
room_id,
|
||||||
|
|
|
@ -134,7 +134,7 @@ impl Room {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let _maintain_video_tracks = cx.spawn_on_main({
|
let _maintain_video_tracks = cx.spawn({
|
||||||
let room = room.clone();
|
let room = room.clone();
|
||||||
move |this, mut cx| async move {
|
move |this, mut cx| async move {
|
||||||
let mut track_video_changes = room.remote_video_track_updates();
|
let mut track_video_changes = room.remote_video_track_updates();
|
||||||
|
@ -153,7 +153,7 @@ impl Room {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
let _maintain_audio_tracks = cx.spawn_on_main({
|
let _maintain_audio_tracks = cx.spawn({
|
||||||
let room = room.clone();
|
let room = room.clone();
|
||||||
|this, mut cx| async move {
|
|this, mut cx| async move {
|
||||||
let mut track_audio_changes = room.remote_audio_track_updates();
|
let mut track_audio_changes = room.remote_audio_track_updates();
|
||||||
|
@ -326,7 +326,7 @@ impl Room {
|
||||||
fn app_will_quit(&mut self, cx: &mut ModelContext<Self>) -> impl Future<Output = ()> {
|
fn app_will_quit(&mut self, cx: &mut ModelContext<Self>) -> impl Future<Output = ()> {
|
||||||
let task = if self.status.is_online() {
|
let task = if self.status.is_online() {
|
||||||
let leave = self.leave_internal(cx);
|
let leave = self.leave_internal(cx);
|
||||||
Some(cx.executor().spawn(async move {
|
Some(cx.background_executor().spawn(async move {
|
||||||
leave.await.log_err();
|
leave.await.log_err();
|
||||||
}))
|
}))
|
||||||
} else {
|
} else {
|
||||||
|
@ -394,7 +394,7 @@ impl Room {
|
||||||
self.clear_state(cx);
|
self.clear_state(cx);
|
||||||
|
|
||||||
let leave_room = self.client.request(proto::LeaveRoom {});
|
let leave_room = self.client.request(proto::LeaveRoom {});
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
leave_room.await?;
|
leave_room.await?;
|
||||||
anyhow::Ok(())
|
anyhow::Ok(())
|
||||||
})
|
})
|
||||||
|
@ -449,7 +449,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 {
|
||||||
|
@ -1195,7 +1196,7 @@ impl Room {
|
||||||
};
|
};
|
||||||
|
|
||||||
cx.notify();
|
cx.notify();
|
||||||
cx.executor().spawn_on_main(move || async move {
|
cx.background_executor().spawn(async move {
|
||||||
client
|
client
|
||||||
.request(proto::UpdateParticipantLocation {
|
.request(proto::UpdateParticipantLocation {
|
||||||
room_id,
|
room_id,
|
||||||
|
@ -1300,7 +1301,9 @@ impl Room {
|
||||||
live_kit.room.unpublish_track(publication);
|
live_kit.room.unpublish_track(publication);
|
||||||
} else {
|
} else {
|
||||||
if muted {
|
if muted {
|
||||||
cx.executor().spawn(publication.set_mute(muted)).detach();
|
cx.background_executor()
|
||||||
|
.spawn(publication.set_mute(muted))
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
live_kit.microphone_track = LocalTrack::Published {
|
live_kit.microphone_track = LocalTrack::Published {
|
||||||
track_publication: publication,
|
track_publication: publication,
|
||||||
|
@ -1343,7 +1346,7 @@ impl Room {
|
||||||
return Task::ready(Err(anyhow!("live-kit was not initialized")));
|
return Task::ready(Err(anyhow!("live-kit was not initialized")));
|
||||||
};
|
};
|
||||||
|
|
||||||
cx.spawn_on_main(move |this, mut cx| async move {
|
cx.spawn(move |this, mut cx| async move {
|
||||||
let publish_track = async {
|
let publish_track = async {
|
||||||
let displays = displays.await?;
|
let displays = displays.await?;
|
||||||
let display = displays
|
let display = displays
|
||||||
|
@ -1386,7 +1389,9 @@ impl Room {
|
||||||
live_kit.room.unpublish_track(publication);
|
live_kit.room.unpublish_track(publication);
|
||||||
} else {
|
} else {
|
||||||
if muted {
|
if muted {
|
||||||
cx.executor().spawn(publication.set_mute(muted)).detach();
|
cx.background_executor()
|
||||||
|
.spawn(publication.set_mute(muted))
|
||||||
|
.detach();
|
||||||
}
|
}
|
||||||
live_kit.screen_track = LocalTrack::Published {
|
live_kit.screen_track = LocalTrack::Published {
|
||||||
track_publication: publication,
|
track_publication: publication,
|
||||||
|
@ -1453,14 +1458,11 @@ impl Room {
|
||||||
.remote_audio_track_publications(&participant.user.id.to_string())
|
.remote_audio_track_publications(&participant.user.id.to_string())
|
||||||
{
|
{
|
||||||
let deafened = live_kit.deafened;
|
let deafened = live_kit.deafened;
|
||||||
tasks.push(
|
tasks.push(cx.foreground_executor().spawn(track.set_enabled(!deafened)));
|
||||||
cx.executor()
|
|
||||||
.spawn_on_main(move || track.set_enabled(!deafened)),
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(cx.executor().spawn_on_main(|| async {
|
Ok(cx.foreground_executor().spawn(async move {
|
||||||
if let Some(mute_task) = mute_task {
|
if let Some(mute_task) = mute_task {
|
||||||
mute_task.await?;
|
mute_task.await?;
|
||||||
}
|
}
|
||||||
|
@ -1551,7 +1553,8 @@ impl LiveKitRoom {
|
||||||
*muted = should_mute;
|
*muted = should_mute;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
Ok((
|
Ok((
|
||||||
cx.executor().spawn(track_publication.set_mute(*muted)),
|
cx.background_executor()
|
||||||
|
.spawn(track_publication.set_mute(*muted)),
|
||||||
old_muted,
|
old_muted,
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
|
|
|
@ -11,7 +11,8 @@ use async_tungstenite::tungstenite::{
|
||||||
http::{Request, StatusCode},
|
http::{Request, StatusCode},
|
||||||
};
|
};
|
||||||
use futures::{
|
use futures::{
|
||||||
future::BoxFuture, AsyncReadExt, FutureExt, SinkExt, StreamExt, TryFutureExt as _, TryStreamExt,
|
future::LocalBoxFuture, AsyncReadExt, FutureExt, SinkExt, StreamExt, TryFutureExt as _,
|
||||||
|
TryStreamExt,
|
||||||
};
|
};
|
||||||
use gpui2::{
|
use gpui2::{
|
||||||
serde_json, AnyModel, AnyWeakModel, AppContext, AsyncAppContext, Model, SemanticVersion, Task,
|
serde_json, AnyModel, AnyWeakModel, AppContext, AsyncAppContext, Model, SemanticVersion, Task,
|
||||||
|
@ -240,7 +241,7 @@ struct ClientState {
|
||||||
Box<dyn AnyTypedEnvelope>,
|
Box<dyn AnyTypedEnvelope>,
|
||||||
&Arc<Client>,
|
&Arc<Client>,
|
||||||
AsyncAppContext,
|
AsyncAppContext,
|
||||||
) -> BoxFuture<'static, Result<()>>,
|
) -> LocalBoxFuture<'static, Result<()>>,
|
||||||
>,
|
>,
|
||||||
>,
|
>,
|
||||||
}
|
}
|
||||||
|
@ -310,10 +311,7 @@ pub struct PendingEntitySubscription<T: 'static> {
|
||||||
consumed: bool,
|
consumed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> PendingEntitySubscription<T>
|
impl<T: 'static> PendingEntitySubscription<T> {
|
||||||
where
|
|
||||||
T: 'static + Send,
|
|
||||||
{
|
|
||||||
pub fn set_model(mut self, model: &Model<T>, cx: &mut AsyncAppContext) -> Subscription {
|
pub fn set_model(mut self, model: &Model<T>, cx: &mut AsyncAppContext) -> Subscription {
|
||||||
self.consumed = true;
|
self.consumed = true;
|
||||||
let mut state = self.client.state.write();
|
let mut state = self.client.state.write();
|
||||||
|
@ -341,10 +339,7 @@ where
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Drop for PendingEntitySubscription<T>
|
impl<T: 'static> Drop for PendingEntitySubscription<T> {
|
||||||
where
|
|
||||||
T: 'static,
|
|
||||||
{
|
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if !self.consumed {
|
if !self.consumed {
|
||||||
let mut state = self.client.state.write();
|
let mut state = self.client.state.write();
|
||||||
|
@ -505,7 +500,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);
|
||||||
|
@ -529,7 +524,7 @@ impl Client {
|
||||||
remote_id: u64,
|
remote_id: u64,
|
||||||
) -> Result<PendingEntitySubscription<T>>
|
) -> Result<PendingEntitySubscription<T>>
|
||||||
where
|
where
|
||||||
T: 'static + Send,
|
T: 'static,
|
||||||
{
|
{
|
||||||
let id = (TypeId::of::<T>(), remote_id);
|
let id = (TypeId::of::<T>(), remote_id);
|
||||||
|
|
||||||
|
@ -557,9 +552,13 @@ impl Client {
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
M: EnvelopedMessage,
|
M: EnvelopedMessage,
|
||||||
E: 'static + Send,
|
E: 'static,
|
||||||
H: 'static + Send + Sync + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
|
H: 'static
|
||||||
F: 'static + Future<Output = Result<()>> + Send,
|
+ Sync
|
||||||
|
+ Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
|
||||||
|
+ Send
|
||||||
|
+ Sync,
|
||||||
|
F: 'static + Future<Output = Result<()>>,
|
||||||
{
|
{
|
||||||
let message_type_id = TypeId::of::<M>();
|
let message_type_id = TypeId::of::<M>();
|
||||||
|
|
||||||
|
@ -573,7 +572,7 @@ impl Client {
|
||||||
Arc::new(move |subscriber, envelope, client, cx| {
|
Arc::new(move |subscriber, envelope, client, cx| {
|
||||||
let subscriber = subscriber.downcast::<E>().unwrap();
|
let subscriber = subscriber.downcast::<E>().unwrap();
|
||||||
let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
|
let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
|
||||||
handler(subscriber, *envelope, client.clone(), cx).boxed()
|
handler(subscriber, *envelope, client.clone(), cx).boxed_local()
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
if prev_handler.is_some() {
|
if prev_handler.is_some() {
|
||||||
|
@ -599,9 +598,13 @@ impl Client {
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
M: RequestMessage,
|
M: RequestMessage,
|
||||||
E: 'static + Send,
|
E: 'static,
|
||||||
H: 'static + Send + Sync + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
|
H: 'static
|
||||||
F: 'static + Future<Output = Result<M::Response>> + Send,
|
+ Sync
|
||||||
|
+ Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F
|
||||||
|
+ Send
|
||||||
|
+ Sync,
|
||||||
|
F: 'static + Future<Output = Result<M::Response>>,
|
||||||
{
|
{
|
||||||
self.add_message_handler(model, move |handle, envelope, this, cx| {
|
self.add_message_handler(model, move |handle, envelope, this, cx| {
|
||||||
Self::respond_to_request(
|
Self::respond_to_request(
|
||||||
|
@ -615,9 +618,9 @@ impl Client {
|
||||||
pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
|
pub fn add_model_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
|
||||||
where
|
where
|
||||||
M: EntityMessage,
|
M: EntityMessage,
|
||||||
E: 'static + Send,
|
E: 'static,
|
||||||
H: 'static + Send + Sync + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
|
H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
|
||||||
F: 'static + Future<Output = Result<()>> + Send,
|
F: 'static + Future<Output = Result<()>>,
|
||||||
{
|
{
|
||||||
self.add_entity_message_handler::<M, E, _, _>(move |subscriber, message, client, cx| {
|
self.add_entity_message_handler::<M, E, _, _>(move |subscriber, message, client, cx| {
|
||||||
handler(subscriber.downcast::<E>().unwrap(), message, client, cx)
|
handler(subscriber.downcast::<E>().unwrap(), message, client, cx)
|
||||||
|
@ -627,9 +630,9 @@ impl Client {
|
||||||
fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
|
fn add_entity_message_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
|
||||||
where
|
where
|
||||||
M: EntityMessage,
|
M: EntityMessage,
|
||||||
E: 'static + Send,
|
E: 'static,
|
||||||
H: 'static + Send + Sync + Fn(AnyModel, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
|
H: 'static + Fn(AnyModel, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
|
||||||
F: 'static + Future<Output = Result<()>> + Send,
|
F: 'static + Future<Output = Result<()>>,
|
||||||
{
|
{
|
||||||
let model_type_id = TypeId::of::<E>();
|
let model_type_id = TypeId::of::<E>();
|
||||||
let message_type_id = TypeId::of::<M>();
|
let message_type_id = TypeId::of::<M>();
|
||||||
|
@ -655,7 +658,7 @@ impl Client {
|
||||||
message_type_id,
|
message_type_id,
|
||||||
Arc::new(move |handle, envelope, client, cx| {
|
Arc::new(move |handle, envelope, client, cx| {
|
||||||
let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
|
let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
|
||||||
handler(handle, *envelope, client.clone(), cx).boxed()
|
handler(handle, *envelope, client.clone(), cx).boxed_local()
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
if prev_handler.is_some() {
|
if prev_handler.is_some() {
|
||||||
|
@ -666,9 +669,9 @@ impl Client {
|
||||||
pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
|
pub fn add_model_request_handler<M, E, H, F>(self: &Arc<Self>, handler: H)
|
||||||
where
|
where
|
||||||
M: EntityMessage + RequestMessage,
|
M: EntityMessage + RequestMessage,
|
||||||
E: 'static + Send,
|
E: 'static,
|
||||||
H: 'static + Send + Sync + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F,
|
H: 'static + Fn(Model<E>, TypedEnvelope<M>, Arc<Self>, AsyncAppContext) -> F + Send + Sync,
|
||||||
F: 'static + Future<Output = Result<M::Response>> + Send,
|
F: 'static + Future<Output = Result<M::Response>>,
|
||||||
{
|
{
|
||||||
self.add_model_message_handler(move |entity, envelope, client, cx| {
|
self.add_model_message_handler(move |entity, envelope, client, cx| {
|
||||||
Self::respond_to_request::<M, _>(
|
Self::respond_to_request::<M, _>(
|
||||||
|
@ -705,7 +708,7 @@ impl Client {
|
||||||
read_credentials_from_keychain(cx).await.is_some()
|
read_credentials_from_keychain(cx).await.is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_recursion]
|
#[async_recursion(?Send)]
|
||||||
pub async fn authenticate_and_connect(
|
pub async fn authenticate_and_connect(
|
||||||
self: &Arc<Self>,
|
self: &Arc<Self>,
|
||||||
try_keychain: bool,
|
try_keychain: bool,
|
||||||
|
@ -763,7 +766,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 +818,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 +982,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()
|
||||||
|
@ -1049,7 +1053,7 @@ impl Client {
|
||||||
write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
|
write!(&mut url, "&impersonate={}", impersonate_login).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
cx.run_on_main(move |cx| cx.open_url(&url))?.await;
|
cx.update(|cx| cx.open_url(&url))?;
|
||||||
|
|
||||||
// Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
|
// Receive the HTTP request from the user's browser. Retrieve the user id and encrypted
|
||||||
// access token from the query params.
|
// access token from the query params.
|
||||||
|
@ -1100,7 +1104,7 @@ impl Client {
|
||||||
let access_token = private_key
|
let access_token = private_key
|
||||||
.decrypt_string(&access_token)
|
.decrypt_string(&access_token)
|
||||||
.context("failed to decrypt access token")?;
|
.context("failed to decrypt access token")?;
|
||||||
cx.run_on_main(|cx| cx.activate(true))?.await;
|
cx.update(|cx| cx.activate(true))?;
|
||||||
|
|
||||||
Ok(Credentials {
|
Ok(Credentials {
|
||||||
user_id: user_id.parse()?,
|
user_id: user_id.parse()?,
|
||||||
|
@ -1292,7 +1296,7 @@ impl Client {
|
||||||
sender_id,
|
sender_id,
|
||||||
type_name
|
type_name
|
||||||
);
|
);
|
||||||
cx.spawn_on_main(move |_| async move {
|
cx.spawn(move |_| async move {
|
||||||
match future.await {
|
match future.await {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
log::debug!(
|
log::debug!(
|
||||||
|
@ -1331,9 +1335,8 @@ async fn read_credentials_from_keychain(cx: &AsyncAppContext) -> Option<Credenti
|
||||||
}
|
}
|
||||||
|
|
||||||
let (user_id, access_token) = cx
|
let (user_id, access_token) = cx
|
||||||
.run_on_main(|cx| cx.read_credentials(&ZED_SERVER_URL).log_err().flatten())
|
.update(|cx| cx.read_credentials(&ZED_SERVER_URL).log_err().flatten())
|
||||||
.ok()?
|
.ok()??;
|
||||||
.await?;
|
|
||||||
|
|
||||||
Some(Credentials {
|
Some(Credentials {
|
||||||
user_id: user_id.parse().ok()?,
|
user_id: user_id.parse().ok()?,
|
||||||
|
@ -1345,19 +1348,17 @@ async fn write_credentials_to_keychain(
|
||||||
credentials: Credentials,
|
credentials: Credentials,
|
||||||
cx: &AsyncAppContext,
|
cx: &AsyncAppContext,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
cx.run_on_main(move |cx| {
|
cx.update(move |cx| {
|
||||||
cx.write_credentials(
|
cx.write_credentials(
|
||||||
&ZED_SERVER_URL,
|
&ZED_SERVER_URL,
|
||||||
&credentials.user_id.to_string(),
|
&credentials.user_id.to_string(),
|
||||||
credentials.access_token.as_bytes(),
|
credentials.access_token.as_bytes(),
|
||||||
)
|
)
|
||||||
})?
|
})?
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete_credentials_from_keychain(cx: &AsyncAppContext) -> Result<()> {
|
async fn delete_credentials_from_keychain(cx: &AsyncAppContext) -> Result<()> {
|
||||||
cx.run_on_main(move |cx| cx.delete_credentials(&ZED_SERVER_URL))?
|
cx.update(move |cx| cx.delete_credentials(&ZED_SERVER_URL))?
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
|
const WORKTREE_URL_PREFIX: &str = "zed://worktrees/";
|
||||||
|
@ -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,14 +1423,14 @@ 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();
|
||||||
|
|
||||||
// Time out when client tries to connect.
|
// Time out when client tries to connect.
|
||||||
client.override_authenticate(move |cx| {
|
client.override_authenticate(move |cx| {
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
Ok(Credentials {
|
Ok(Credentials {
|
||||||
user_id,
|
user_id,
|
||||||
access_token: "token".into(),
|
access_token: "token".into(),
|
||||||
|
@ -1437,7 +1438,7 @@ mod tests {
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
client.override_establish_connection(|_, cx| {
|
client.override_establish_connection(|_, cx| {
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
future::pending::<()>().await;
|
future::pending::<()>().await;
|
||||||
unreachable!()
|
unreachable!()
|
||||||
})
|
})
|
||||||
|
@ -1471,7 +1472,7 @@ mod tests {
|
||||||
// Time out when re-establishing the connection.
|
// Time out when re-establishing the connection.
|
||||||
server.allow_connections();
|
server.allow_connections();
|
||||||
client.override_establish_connection(|_, cx| {
|
client.override_establish_connection(|_, cx| {
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
future::pending::<()>().await;
|
future::pending::<()>().await;
|
||||||
unreachable!()
|
unreachable!()
|
||||||
})
|
})
|
||||||
|
@ -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));
|
||||||
|
@ -1500,7 +1504,7 @@ mod tests {
|
||||||
move |cx| {
|
move |cx| {
|
||||||
let auth_count = auth_count.clone();
|
let auth_count = auth_count.clone();
|
||||||
let dropped_auth_count = dropped_auth_count.clone();
|
let dropped_auth_count = dropped_auth_count.clone();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
*auth_count.lock() += 1;
|
*auth_count.lock() += 1;
|
||||||
let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
|
let _drop = util::defer(move || *dropped_auth_count.lock() += 1);
|
||||||
future::pending::<()>().await;
|
future::pending::<()>().await;
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
|
use crate::{TelemetrySettings, ZED_SECRET_CLIENT_TOKEN, ZED_SERVER_URL};
|
||||||
use gpui2::{serde_json, AppContext, AppMetadata, Executor, Task};
|
use gpui2::{serde_json, AppContext, AppMetadata, BackgroundExecutor, Task};
|
||||||
use lazy_static::lazy_static;
|
use lazy_static::lazy_static;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
@ -14,7 +14,7 @@ use util::{channel::ReleaseChannel, TryFutureExt};
|
||||||
|
|
||||||
pub struct Telemetry {
|
pub struct Telemetry {
|
||||||
http_client: Arc<dyn HttpClient>,
|
http_client: Arc<dyn HttpClient>,
|
||||||
executor: Executor,
|
executor: BackgroundExecutor,
|
||||||
state: Mutex<TelemetryState>,
|
state: Mutex<TelemetryState>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -123,7 +123,7 @@ impl Telemetry {
|
||||||
// TODO: Replace all hardware stuff with nested SystemSpecs json
|
// TODO: Replace all hardware stuff with nested SystemSpecs json
|
||||||
let this = Arc::new(Self {
|
let this = Arc::new(Self {
|
||||||
http_client: client,
|
http_client: client,
|
||||||
executor: cx.executor().clone(),
|
executor: cx.background_executor().clone(),
|
||||||
state: Mutex::new(TelemetryState {
|
state: Mutex::new(TelemetryState {
|
||||||
app_metadata: cx.app_metadata(),
|
app_metadata: cx.app_metadata(),
|
||||||
architecture: env::consts::ARCH,
|
architecture: env::consts::ARCH,
|
||||||
|
|
|
@ -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);
|
||||||
|
|
|
@ -3,7 +3,7 @@ authors = ["Nathan Sobo <nathan@zed.dev>"]
|
||||||
default-run = "collab"
|
default-run = "collab"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
name = "collab"
|
name = "collab"
|
||||||
version = "0.27.0"
|
version = "0.28.0"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[[bin]]
|
[[bin]]
|
||||||
|
|
|
@ -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 {
|
||||||
|
@ -535,7 +535,7 @@ impl Copilot {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(task.map_err(|err| anyhow!("{:?}", err)))
|
.spawn(task.map_err(|err| anyhow!("{:?}", err)))
|
||||||
} else {
|
} else {
|
||||||
// If we're downloading, wait until download is finished
|
// If we're downloading, wait until download is finished
|
||||||
|
@ -549,7 +549,7 @@ impl Copilot {
|
||||||
self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
|
self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
|
||||||
if let CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) = &self.server {
|
if let CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) = &self.server {
|
||||||
let server = server.clone();
|
let server = server.clone();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
server
|
server
|
||||||
.request::<request::SignOut>(request::SignOutParams {})
|
.request::<request::SignOut>(request::SignOutParams {})
|
||||||
.await?;
|
.await?;
|
||||||
|
@ -579,7 +579,7 @@ impl Copilot {
|
||||||
|
|
||||||
cx.notify();
|
cx.notify();
|
||||||
|
|
||||||
cx.executor().spawn(start_task)
|
cx.background_executor().spawn(start_task)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn language_server(&self) -> Option<(&LanguageServerName, &Arc<LanguageServer>)> {
|
pub fn language_server(&self) -> Option<(&LanguageServerName, &Arc<LanguageServer>)> {
|
||||||
|
@ -760,7 +760,7 @@ impl Copilot {
|
||||||
.request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
|
.request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
|
||||||
uuid: completion.uuid.clone(),
|
uuid: completion.uuid.clone(),
|
||||||
});
|
});
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
request.await?;
|
request.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -784,7 +784,7 @@ impl Copilot {
|
||||||
.map(|completion| completion.uuid.clone())
|
.map(|completion| completion.uuid.clone())
|
||||||
.collect(),
|
.collect(),
|
||||||
});
|
});
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
request.await?;
|
request.await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
})
|
})
|
||||||
|
@ -827,7 +827,7 @@ impl Copilot {
|
||||||
.map(|file| file.path().to_path_buf())
|
.map(|file| file.path().to_path_buf())
|
||||||
.unwrap_or_default();
|
.unwrap_or_default();
|
||||||
|
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
let (version, snapshot) = snapshot.await?;
|
let (version, snapshot) = snapshot.await?;
|
||||||
let result = lsp
|
let result = lsp
|
||||||
.request::<R>(request::GetCompletionsParams {
|
.request::<R>(request::GetCompletionsParams {
|
||||||
|
|
|
@ -185,7 +185,7 @@ pub fn write_and_log<F>(cx: &mut AppContext, db_write: impl FnOnce() -> F + Send
|
||||||
where
|
where
|
||||||
F: Future<Output = anyhow::Result<()>> + Send,
|
F: Future<Output = anyhow::Result<()>> + Send,
|
||||||
{
|
{
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(async move { db_write().await.log_err() })
|
.spawn(async move { db_write().await.log_err() })
|
||||||
.detach()
|
.detach()
|
||||||
}
|
}
|
||||||
|
|
|
@ -28,7 +28,7 @@ pub trait FeatureFlagViewExt<V: 'static> {
|
||||||
F: Fn(bool, &mut V, &mut ViewContext<V>) + Send + Sync + 'static;
|
F: Fn(bool, &mut V, &mut ViewContext<V>) + Send + Sync + 'static;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V> FeatureFlagViewExt<V> for ViewContext<'_, '_, V>
|
impl<V> FeatureFlagViewExt<V> for ViewContext<'_, V>
|
||||||
where
|
where
|
||||||
V: 'static + Send + Sync,
|
V: 'static + Send + Sync,
|
||||||
{
|
{
|
||||||
|
|
|
@ -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",
|
||||||
|
|
|
@ -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 {
|
||||||
|
|
|
@ -2,7 +2,7 @@ use crate::{
|
||||||
matcher::{Match, MatchCandidate, Matcher},
|
matcher::{Match, MatchCandidate, Matcher},
|
||||||
CharBag,
|
CharBag,
|
||||||
};
|
};
|
||||||
use gpui2::Executor;
|
use gpui2::BackgroundExecutor;
|
||||||
use std::{
|
use std::{
|
||||||
borrow::Cow,
|
borrow::Cow,
|
||||||
cmp::{self, Ordering},
|
cmp::{self, Ordering},
|
||||||
|
@ -83,7 +83,7 @@ pub async fn match_strings(
|
||||||
smart_case: bool,
|
smart_case: bool,
|
||||||
max_results: usize,
|
max_results: usize,
|
||||||
cancel_flag: &AtomicBool,
|
cancel_flag: &AtomicBool,
|
||||||
executor: Executor,
|
executor: BackgroundExecutor,
|
||||||
) -> Vec<StringMatch> {
|
) -> Vec<StringMatch> {
|
||||||
if candidates.is_empty() || max_results == 0 {
|
if candidates.is_empty() || max_results == 0 {
|
||||||
return Default::default();
|
return Default::default();
|
||||||
|
|
|
@ -4,7 +4,7 @@ use collections::{HashMap, HashSet};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::any::{type_name, Any};
|
use std::any::{type_name, Any};
|
||||||
|
|
||||||
pub trait Action: Any + Send {
|
pub trait Action: 'static {
|
||||||
fn qualified_name() -> SharedString
|
fn qualified_name() -> SharedString
|
||||||
where
|
where
|
||||||
Self: Sized;
|
Self: Sized;
|
||||||
|
@ -19,7 +19,7 @@ pub trait Action: Any + Send {
|
||||||
|
|
||||||
impl<A> Action for A
|
impl<A> Action for A
|
||||||
where
|
where
|
||||||
A: for<'a> Deserialize<'a> + PartialEq + Any + Send + Clone + Default,
|
A: for<'a> Deserialize<'a> + PartialEq + Clone + Default + 'static,
|
||||||
{
|
{
|
||||||
fn qualified_name() -> SharedString {
|
fn qualified_name() -> SharedString {
|
||||||
type_name::<A>().into()
|
type_name::<A>().into()
|
||||||
|
|
|
@ -13,30 +13,32 @@ use smallvec::SmallVec;
|
||||||
pub use test_context::*;
|
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, AnyWindowHandle,
|
||||||
ClipboardItem, Context, DispatchPhase, DisplayId, Executor, FocusEvent, FocusHandle, FocusId,
|
AppMetadata, AssetSource, BackgroundExecutor, ClipboardItem, Context, DispatchPhase, DisplayId,
|
||||||
KeyBinding, Keymap, LayoutId, MainThread, MainThreadOnly, Pixels, Platform, Point, Render,
|
Entity, FocusEvent, FocusHandle, FocusId, ForegroundExecutor, KeyBinding, Keymap, LayoutId,
|
||||||
SharedString, SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement,
|
PathPromptOptions, Pixels, Platform, PlatformDisplay, Point, Render, SharedString,
|
||||||
TextSystem, View, Window, WindowContext, WindowHandle, WindowId,
|
SubscriberSet, Subscription, SvgRenderer, Task, TextStyle, TextStyleRefinement, TextSystem,
|
||||||
|
View, Window, WindowContext, WindowHandle, WindowId,
|
||||||
};
|
};
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use collections::{HashMap, HashSet, VecDeque};
|
use collections::{HashMap, HashSet, VecDeque};
|
||||||
use futures::{future::BoxFuture, Future};
|
use futures::{channel::oneshot, future::LocalBoxFuture, Future};
|
||||||
use parking_lot::Mutex;
|
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::{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 +56,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 +72,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,49 +85,50 @@ 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 foreground_executor(&self) -> ForegroundExecutor {
|
||||||
|
self.0.borrow().foreground_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()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
|
type ActionBuilder = fn(json: Option<serde_json::Value>) -> anyhow::Result<Box<dyn Action>>;
|
||||||
type FrameCallback = Box<dyn FnOnce(&mut WindowContext) + Send>;
|
type FrameCallback = Box<dyn FnOnce(&mut WindowContext)>;
|
||||||
type Handler = Box<dyn FnMut(&mut AppContext) -> bool + Send + 'static>;
|
type Handler = Box<dyn FnMut(&mut AppContext) -> bool + 'static>;
|
||||||
type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + Send + 'static>;
|
type Listener = Box<dyn FnMut(&dyn Any, &mut AppContext) -> bool + 'static>;
|
||||||
type QuitHandler = Box<dyn FnMut(&mut AppContext) -> BoxFuture<'static, ()> + Send + 'static>;
|
type QuitHandler = Box<dyn FnOnce(&mut AppContext) -> LocalBoxFuture<'static, ()> + 'static>;
|
||||||
type ReleaseListener = Box<dyn FnMut(&mut dyn Any, &mut AppContext) + Send + 'static>;
|
type ReleaseListener = Box<dyn FnOnce(&mut dyn Any, &mut AppContext) + '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,
|
||||||
|
@ -140,7 +138,7 @@ pub struct AppContext {
|
||||||
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
|
pub(crate) windows: SlotMap<WindowId, Option<Window>>,
|
||||||
pub(crate) keymap: Arc<Mutex<Keymap>>,
|
pub(crate) keymap: Arc<Mutex<Keymap>>,
|
||||||
pub(crate) global_action_listeners:
|
pub(crate) global_action_listeners:
|
||||||
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self) + Send>>>,
|
HashMap<TypeId, Vec<Box<dyn Fn(&dyn Action, DispatchPhase, &mut Self)>>>,
|
||||||
action_builders: HashMap<SharedString, ActionBuilder>,
|
action_builders: HashMap<SharedString, ActionBuilder>,
|
||||||
pending_effects: VecDeque<Effect>,
|
pending_effects: VecDeque<Effect>,
|
||||||
pub(crate) pending_notifications: HashSet<EntityId>,
|
pub(crate) pending_notifications: HashSet<EntityId>,
|
||||||
|
@ -156,11 +154,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 +174,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),
|
||||||
|
@ -215,17 +215,16 @@ impl AppContext {
|
||||||
pub fn quit(&mut self) {
|
pub fn quit(&mut self) {
|
||||||
let mut futures = Vec::new();
|
let mut futures = Vec::new();
|
||||||
|
|
||||||
self.quit_observers.clone().retain(&(), |observer| {
|
for observer in self.quit_observers.remove(&()) {
|
||||||
futures.push(observer(self));
|
futures.push(observer(self));
|
||||||
true
|
}
|
||||||
});
|
|
||||||
|
|
||||||
self.windows.clear();
|
self.windows.clear();
|
||||||
self.flush_effects();
|
self.flush_effects();
|
||||||
|
|
||||||
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 +243,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);
|
||||||
|
@ -257,44 +255,91 @@ impl AppContext {
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn read_window<R>(
|
pub fn windows(&self) -> Vec<AnyWindowHandle> {
|
||||||
&mut self,
|
self.windows
|
||||||
id: WindowId,
|
.values()
|
||||||
read: impl FnOnce(&WindowContext) -> R,
|
.filter_map(|window| Some(window.as_ref()?.handle.clone()))
|
||||||
) -> Result<R> {
|
.collect()
|
||||||
let window = self
|
|
||||||
.windows
|
|
||||||
.get(id)
|
|
||||||
.ok_or_else(|| anyhow!("window not found"))?
|
|
||||||
.as_ref()
|
|
||||||
.unwrap();
|
|
||||||
Ok(read(&WindowContext::immutable(self, &window)))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn update_window<R>(
|
/// 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,
|
&mut self,
|
||||||
id: WindowId,
|
options: crate::WindowOptions,
|
||||||
update: impl FnOnce(&mut WindowContext) -> R,
|
build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
|
||||||
) -> Result<R> {
|
) -> WindowHandle<V> {
|
||||||
self.update(|cx| {
|
self.update(|cx| {
|
||||||
let mut window = cx
|
let id = cx.windows.insert(None);
|
||||||
.windows
|
let handle = WindowHandle::new(id);
|
||||||
.get_mut(id)
|
let mut window = Window::new(handle.into(), options, cx);
|
||||||
.ok_or_else(|| anyhow!("window not found"))?
|
let root_view = build_root_view(&mut WindowContext::new(cx, &mut window));
|
||||||
.take()
|
window.root_view.replace(root_view.into());
|
||||||
.unwrap();
|
cx.windows.get_mut(id).unwrap().replace(window);
|
||||||
|
handle
|
||||||
let result = update(&mut WindowContext::mutable(cx, &mut window));
|
|
||||||
|
|
||||||
cx.windows
|
|
||||||
.get_mut(id)
|
|
||||||
.ok_or_else(|| anyhow!("window not found"))?
|
|
||||||
.replace(window);
|
|
||||||
|
|
||||||
Ok(result)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns the list of currently active displays.
|
||||||
|
pub fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {
|
||||||
|
self.platform.displays()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 fn prompt_for_paths(
|
||||||
|
&self,
|
||||||
|
options: PathPromptOptions,
|
||||||
|
) -> oneshot::Receiver<Option<Vec<PathBuf>>> {
|
||||||
|
self.platform.prompt_for_paths(options)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prompt_for_new_path(&self, directory: &Path) -> oneshot::Receiver<Option<PathBuf>> {
|
||||||
|
self.platform.prompt_for_new_path(directory)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reveal_path(&self, path: &Path) {
|
||||||
|
self.platform.reveal_path(path)
|
||||||
|
}
|
||||||
|
|
||||||
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 } => {
|
||||||
|
@ -326,8 +371,11 @@ impl AppContext {
|
||||||
self.apply_notify_effect(emitter);
|
self.apply_notify_effect(emitter);
|
||||||
}
|
}
|
||||||
Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
|
Effect::Emit { emitter, event } => self.apply_emit_effect(emitter, event),
|
||||||
Effect::FocusChanged { window_id, focused } => {
|
Effect::FocusChanged {
|
||||||
self.apply_focus_changed_effect(window_id, focused);
|
window_handle,
|
||||||
|
focused,
|
||||||
|
} => {
|
||||||
|
self.apply_focus_changed_effect(window_handle, focused);
|
||||||
}
|
}
|
||||||
Effect::Refresh => {
|
Effect::Refresh => {
|
||||||
self.apply_refresh_effect();
|
self.apply_refresh_effect();
|
||||||
|
@ -347,18 +395,18 @@ impl AppContext {
|
||||||
let dirty_window_ids = self
|
let dirty_window_ids = self
|
||||||
.windows
|
.windows
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|(window_id, window)| {
|
.filter_map(|(_, window)| {
|
||||||
let window = window.as_ref().unwrap();
|
let window = window.as_ref().unwrap();
|
||||||
if window.dirty {
|
if window.dirty {
|
||||||
Some(window_id)
|
Some(window.handle.clone())
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect::<SmallVec<[_; 8]>>();
|
.collect::<SmallVec<[_; 8]>>();
|
||||||
|
|
||||||
for dirty_window_id in dirty_window_ids {
|
for dirty_window_handle in dirty_window_ids {
|
||||||
self.update_window(dirty_window_id, |cx| cx.draw()).unwrap();
|
dirty_window_handle.update(self, |_, cx| cx.draw()).unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -375,7 +423,7 @@ impl AppContext {
|
||||||
for (entity_id, mut entity) in dropped {
|
for (entity_id, mut entity) in dropped {
|
||||||
self.observers.remove(&entity_id);
|
self.observers.remove(&entity_id);
|
||||||
self.event_listeners.remove(&entity_id);
|
self.event_listeners.remove(&entity_id);
|
||||||
for mut release_callback in self.release_listeners.remove(&entity_id) {
|
for release_callback in self.release_listeners.remove(&entity_id) {
|
||||||
release_callback(entity.as_mut(), self);
|
release_callback(entity.as_mut(), self);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -386,27 +434,27 @@ impl AppContext {
|
||||||
/// For now, we simply blur the window if this happens, but we may want to support invoking
|
/// For now, we simply blur the window if this happens, but we may want to support invoking
|
||||||
/// a window blur handler to restore focus to some logical element.
|
/// a window blur handler to restore focus to some logical element.
|
||||||
fn release_dropped_focus_handles(&mut self) {
|
fn release_dropped_focus_handles(&mut self) {
|
||||||
let window_ids = self.windows.keys().collect::<SmallVec<[_; 8]>>();
|
for window_handle in self.windows() {
|
||||||
for window_id in window_ids {
|
window_handle
|
||||||
self.update_window(window_id, |cx| {
|
.update(self, |_, cx| {
|
||||||
let mut blur_window = false;
|
let mut blur_window = false;
|
||||||
let focus = cx.window.focus;
|
let focus = cx.window.focus;
|
||||||
cx.window.focus_handles.write().retain(|handle_id, count| {
|
cx.window.focus_handles.write().retain(|handle_id, count| {
|
||||||
if count.load(SeqCst) == 0 {
|
if count.load(SeqCst) == 0 {
|
||||||
if focus == Some(handle_id) {
|
if focus == Some(handle_id) {
|
||||||
blur_window = true;
|
blur_window = true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
false
|
});
|
||||||
} else {
|
|
||||||
true
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
if blur_window {
|
if blur_window {
|
||||||
cx.blur();
|
cx.blur();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -423,30 +471,35 @@ impl AppContext {
|
||||||
.retain(&emitter, |handler| handler(event.as_ref(), self));
|
.retain(&emitter, |handler| handler(event.as_ref(), self));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_focus_changed_effect(&mut self, window_id: WindowId, focused: Option<FocusId>) {
|
fn apply_focus_changed_effect(
|
||||||
self.update_window(window_id, |cx| {
|
&mut self,
|
||||||
if cx.window.focus == focused {
|
window_handle: AnyWindowHandle,
|
||||||
let mut listeners = mem::take(&mut cx.window.focus_listeners);
|
focused: Option<FocusId>,
|
||||||
let focused =
|
) {
|
||||||
focused.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
|
window_handle
|
||||||
let blurred = cx
|
.update(self, |_, cx| {
|
||||||
.window
|
if cx.window.focus == focused {
|
||||||
.last_blur
|
let mut listeners = mem::take(&mut cx.window.focus_listeners);
|
||||||
.take()
|
let focused = focused
|
||||||
.unwrap()
|
.map(|id| FocusHandle::for_id(id, &cx.window.focus_handles).unwrap());
|
||||||
.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
|
let blurred = cx
|
||||||
if focused.is_some() || blurred.is_some() {
|
.window
|
||||||
let event = FocusEvent { focused, blurred };
|
.last_blur
|
||||||
for listener in &listeners {
|
.take()
|
||||||
listener(&event, cx);
|
.unwrap()
|
||||||
|
.and_then(|id| FocusHandle::for_id(id, &cx.window.focus_handles));
|
||||||
|
if focused.is_some() || blurred.is_some() {
|
||||||
|
let event = FocusEvent { focused, blurred };
|
||||||
|
for listener in &listeners {
|
||||||
|
listener(&event, cx);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
listeners.extend(cx.window.focus_listeners.drain(..));
|
listeners.extend(cx.window.focus_listeners.drain(..));
|
||||||
cx.window.focus_listeners = listeners;
|
cx.window.focus_listeners = listeners;
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.ok();
|
.ok();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_refresh_effect(&mut self) {
|
fn apply_refresh_effect(&mut self) {
|
||||||
|
@ -464,7 +517,7 @@ impl AppContext {
|
||||||
.retain(&type_id, |observer| observer(self));
|
.retain(&type_id, |observer| observer(self));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + Send + 'static>) {
|
fn apply_defer_effect(&mut self, callback: Box<dyn FnOnce(&mut Self) + 'static>) {
|
||||||
callback(self);
|
callback(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -473,72 +526,34 @@ 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 background_executor(&self) -> &BackgroundExecutor {
|
||||||
&self.executor
|
&self.background_executor
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Runs the given closure on the main thread, where interaction with the platform
|
/// Obtains a reference to the executor, which can be used to spawn futures.
|
||||||
/// is possible. The given closure will be invoked with a `MainThread<AppContext>`, which
|
pub fn foreground_executor(&self) -> &ForegroundExecutor {
|
||||||
/// has platform-specific methods that aren't present on `AppContext`.
|
&self.foreground_executor
|
||||||
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
|
||||||
/// that are currently on the stack to be returned to the app.
|
/// that are currently on the stack to be returned to the app.
|
||||||
pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static + Send) {
|
pub fn defer(&mut self, f: impl FnOnce(&mut AppContext) + 'static) {
|
||||||
self.push_effect(Effect::Defer {
|
self.push_effect(Effect::Defer {
|
||||||
callback: Box::new(f),
|
callback: Box::new(f),
|
||||||
});
|
});
|
||||||
|
@ -597,7 +612,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 +623,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));
|
||||||
|
@ -626,7 +641,7 @@ impl AppContext {
|
||||||
/// Register a callback to be invoked when a global of the given type is updated.
|
/// Register a callback to be invoked when a global of the given type is updated.
|
||||||
pub fn observe_global<G: 'static>(
|
pub fn observe_global<G: 'static>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut f: impl FnMut(&mut Self) + Send + 'static,
|
mut f: impl FnMut(&mut Self) + 'static,
|
||||||
) -> Subscription {
|
) -> Subscription {
|
||||||
self.global_observers.insert(
|
self.global_observers.insert(
|
||||||
TypeId::of::<G>(),
|
TypeId::of::<G>(),
|
||||||
|
@ -658,6 +673,24 @@ impl AppContext {
|
||||||
self.globals_by_type.insert(global_type, lease.global);
|
self.globals_by_type.insert(global_type, lease.global);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn observe_release<E, T>(
|
||||||
|
&mut self,
|
||||||
|
handle: &E,
|
||||||
|
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
||||||
|
) -> Subscription
|
||||||
|
where
|
||||||
|
E: Entity<T>,
|
||||||
|
T: 'static,
|
||||||
|
{
|
||||||
|
self.release_listeners.insert(
|
||||||
|
handle.entity_id(),
|
||||||
|
Box::new(move |entity, cx| {
|
||||||
|
let entity = entity.downcast_mut().expect("invalid entity type");
|
||||||
|
on_release(entity, cx)
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
|
pub(crate) fn push_text_style(&mut self, text_style: TextStyleRefinement) {
|
||||||
self.text_style_stack.push(text_style);
|
self.text_style_stack.push(text_style);
|
||||||
}
|
}
|
||||||
|
@ -673,7 +706,7 @@ impl AppContext {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Register a global listener for actions invoked via the keyboard.
|
/// Register a global listener for actions invoked via the keyboard.
|
||||||
pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + Send + 'static) {
|
pub fn on_action<A: Action>(&mut self, listener: impl Fn(&A, &mut Self) + 'static) {
|
||||||
self.global_action_listeners
|
self.global_action_listeners
|
||||||
.entry(TypeId::of::<A>())
|
.entry(TypeId::of::<A>())
|
||||||
.or_default()
|
.or_default()
|
||||||
|
@ -711,19 +744,18 @@ impl AppContext {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Context for AppContext {
|
impl Context for AppContext {
|
||||||
type ModelContext<'a, T> = ModelContext<'a, T>;
|
|
||||||
type Result<T> = T;
|
type Result<T> = T;
|
||||||
|
|
||||||
/// 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 ModelContext<'_, T>) -> T,
|
||||||
) -> Model<T> {
|
) -> Model<T> {
|
||||||
self.update(|cx| {
|
self.update(|cx| {
|
||||||
let slot = cx.entities.reserve();
|
let slot = cx.entities.reserve();
|
||||||
let entity = build_model(&mut ModelContext::mutable(cx, slot.downgrade()));
|
let entity = build_model(&mut ModelContext::new(cx, slot.downgrade()));
|
||||||
cx.entities.insert(slot, entity)
|
cx.entities.insert(slot, entity)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -733,117 +765,36 @@ impl Context for AppContext {
|
||||||
fn update_model<T: 'static, R>(
|
fn update_model<T: 'static, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
model: &Model<T>,
|
model: &Model<T>,
|
||||||
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||||
) -> R {
|
) -> R {
|
||||||
self.update(|cx| {
|
self.update(|cx| {
|
||||||
let mut entity = cx.entities.lease(model);
|
let mut entity = cx.entities.lease(model);
|
||||||
let result = update(
|
let result = update(&mut entity, &mut ModelContext::new(cx, model.downgrade()));
|
||||||
&mut entity,
|
|
||||||
&mut ModelContext::mutable(cx, model.downgrade()),
|
|
||||||
);
|
|
||||||
cx.entities.end_lease(entity);
|
cx.entities.end_lease(entity);
|
||||||
result
|
result
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
impl<C> MainThread<C>
|
fn update_window<T, F>(&mut self, handle: AnyWindowHandle, update: F) -> Result<T>
|
||||||
where
|
where
|
||||||
C: Borrow<AppContext>,
|
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
|
||||||
{
|
{
|
||||||
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| {
|
self.update(|cx| {
|
||||||
let id = cx.windows.insert(None);
|
let mut window = cx
|
||||||
let handle = WindowHandle::new(id);
|
.windows
|
||||||
let mut window = Window::new(handle.into(), options, cx);
|
.get_mut(handle.id)
|
||||||
let root_view = build_root_view(&mut WindowContext::mutable(cx, &mut window));
|
.ok_or_else(|| anyhow!("window not found"))?
|
||||||
window.root_view.replace(root_view.into());
|
.take()
|
||||||
cx.windows.get_mut(id).unwrap().replace(window);
|
.unwrap();
|
||||||
handle
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Update the global of the given type with a closure. Unlike `global_mut`, this method provides
|
let root_view = window.root_view.clone().unwrap();
|
||||||
/// your closure with mutable access to the `MainThread<AppContext>` and the global simultaneously.
|
let result = update(root_view, &mut WindowContext::new(cx, &mut window));
|
||||||
pub fn update_global<G: 'static + Send, R>(
|
cx.windows
|
||||||
&mut self,
|
.get_mut(handle.id)
|
||||||
update: impl FnOnce(&mut G, &mut MainThread<AppContext>) -> R,
|
.ok_or_else(|| anyhow!("window not found"))?
|
||||||
) -> R {
|
.replace(window);
|
||||||
self.0.update_global(|global, cx| {
|
|
||||||
let cx = unsafe { mem::transmute::<&mut AppContext, &mut MainThread<AppContext>>(cx) };
|
Ok(result)
|
||||||
update(global, cx)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -855,10 +806,10 @@ 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_handle: AnyWindowHandle,
|
||||||
focused: Option<FocusId>,
|
focused: Option<FocusId>,
|
||||||
},
|
},
|
||||||
Refresh,
|
Refresh,
|
||||||
|
@ -866,7 +817,7 @@ pub(crate) enum Effect {
|
||||||
global_type: TypeId,
|
global_type: TypeId,
|
||||||
},
|
},
|
||||||
Defer {
|
Defer {
|
||||||
callback: Box<dyn FnOnce(&mut AppContext) + Send + 'static>,
|
callback: Box<dyn FnOnce(&mut AppContext) + 'static>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -905,15 +856,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>();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -1,48 +1,57 @@
|
||||||
use crate::{
|
use crate::{
|
||||||
AnyWindowHandle, AppContext, Context, Executor, MainThread, Model, ModelContext, Result, Task,
|
AnyView, AnyWindowHandle, AppContext, BackgroundExecutor, Context, ForegroundExecutor, Model,
|
||||||
WindowContext,
|
ModelContext, Render, Result, Task, View, ViewContext, VisualContext, WindowContext,
|
||||||
|
WindowHandle,
|
||||||
};
|
};
|
||||||
use anyhow::anyhow;
|
use anyhow::{anyhow, Context as _};
|
||||||
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 {
|
||||||
type ModelContext<'a, T> = ModelContext<'a, T>;
|
|
||||||
type Result<T> = Result<T>;
|
type Result<T> = Result<T>;
|
||||||
|
|
||||||
fn build_model<T: 'static>(
|
fn build_model<T: 'static>(
|
||||||
&mut self,
|
&mut self,
|
||||||
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
|
build_model: impl FnOnce(&mut 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>(
|
||||||
&mut self,
|
&mut self,
|
||||||
handle: &Model<T>,
|
handle: &Model<T>,
|
||||||
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||||
) -> Self::Result<R> {
|
) -> Self::Result<R> {
|
||||||
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.update_model(handle, update))
|
Ok(app.update_model(handle, update))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||||
|
where
|
||||||
|
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
|
||||||
|
{
|
||||||
|
let app = self.app.upgrade().context("app was released")?;
|
||||||
|
let mut lock = app.borrow_mut();
|
||||||
|
lock.update_window(window, f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -52,13 +61,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,70 +79,32 @@ 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))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_window<R>(
|
pub fn open_window<V>(
|
||||||
&self,
|
&self,
|
||||||
handle: AnyWindowHandle,
|
options: crate::WindowOptions,
|
||||||
update: impl FnOnce(&WindowContext) -> R,
|
build_root_view: impl FnOnce(&mut WindowContext) -> View<V>,
|
||||||
) -> Result<R> {
|
) -> Result<WindowHandle<V>>
|
||||||
let app = self
|
|
||||||
.app
|
|
||||||
.upgrade()
|
|
||||||
.ok_or_else(|| anyhow!("app was released"))?;
|
|
||||||
let mut app_context = app.lock();
|
|
||||||
app_context.read_window(handle.id, update)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_window<R>(
|
|
||||||
&self,
|
|
||||||
handle: AnyWindowHandle,
|
|
||||||
update: impl FnOnce(&mut WindowContext) -> R,
|
|
||||||
) -> Result<R> {
|
|
||||||
let app = self
|
|
||||||
.app
|
|
||||||
.upgrade()
|
|
||||||
.ok_or_else(|| anyhow!("app was released"))?;
|
|
||||||
let mut app_context = app.lock();
|
|
||||||
app_context.update_window(handle.id, update)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> Task<R>
|
|
||||||
where
|
where
|
||||||
Fut: Future<Output = R> + Send + 'static,
|
V: Render,
|
||||||
R: Send + 'static,
|
|
||||||
{
|
{
|
||||||
let this = self.clone();
|
let app = self
|
||||||
self.executor.spawn(async move { f(this).await })
|
.app
|
||||||
|
.upgrade()
|
||||||
|
.ok_or_else(|| anyhow!("app was released"))?;
|
||||||
|
let mut lock = app.borrow_mut();
|
||||||
|
Ok(lock.open_window(options, build_root_view))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn spawn_on_main<Fut, R>(
|
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<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 +112,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 +121,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 +130,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 +142,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))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -185,22 +160,22 @@ impl AsyncWindowContext {
|
||||||
Self { app, window }
|
Self { app, window }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update<R>(&self, update: impl FnOnce(&mut WindowContext) -> R) -> Result<R> {
|
pub fn update<R>(
|
||||||
|
&mut self,
|
||||||
|
update: impl FnOnce(AnyView, &mut WindowContext) -> R,
|
||||||
|
) -> Result<R> {
|
||||||
self.app.update_window(self.window, update)
|
self.app.update_window(self.window, update)
|
||||||
}
|
}
|
||||||
|
|
||||||
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) + 'static) {
|
||||||
self.app
|
self.window.update(self, |_, cx| cx.on_next_frame(f)).ok();
|
||||||
.update_window(self.window, |cx| cx.on_next_frame(f))
|
|
||||||
.ok();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_global<G: 'static, R>(
|
pub fn read_global<G: 'static, R>(
|
||||||
&self,
|
&mut self,
|
||||||
read: impl FnOnce(&G, &WindowContext) -> R,
|
read: impl FnOnce(&G, &WindowContext) -> R,
|
||||||
) -> Result<R> {
|
) -> Result<R> {
|
||||||
self.app
|
self.window.update(self, |_, cx| read(cx.global(), cx))
|
||||||
.read_window(self.window, |cx| read(cx.global(), cx))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_global<G, R>(
|
pub fn update_global<G, R>(
|
||||||
|
@ -210,43 +185,78 @@ impl AsyncWindowContext {
|
||||||
where
|
where
|
||||||
G: 'static,
|
G: 'static,
|
||||||
{
|
{
|
||||||
self.app
|
self.window.update(self, |_, cx| cx.update_global(update))
|
||||||
.update_window(self.window, |cx| cx.update_global(update))
|
}
|
||||||
|
|
||||||
|
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncWindowContext) -> Fut) -> Task<R>
|
||||||
|
where
|
||||||
|
Fut: Future<Output = R> + 'static,
|
||||||
|
R: 'static,
|
||||||
|
{
|
||||||
|
self.foreground_executor.spawn(f(self.clone()))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Context for AsyncWindowContext {
|
impl Context for AsyncWindowContext {
|
||||||
type ModelContext<'a, T> = ModelContext<'a, T>;
|
|
||||||
type Result<T> = Result<T>;
|
type Result<T> = Result<T>;
|
||||||
|
|
||||||
fn build_model<T>(
|
fn build_model<T>(
|
||||||
&mut self,
|
&mut self,
|
||||||
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
|
build_model: impl FnOnce(&mut ModelContext<'_, T>) -> T,
|
||||||
) -> Result<Model<T>>
|
) -> Result<Model<T>>
|
||||||
where
|
where
|
||||||
T: 'static + Send,
|
T: 'static,
|
||||||
{
|
{
|
||||||
self.app
|
self.window
|
||||||
.update_window(self.window, |cx| cx.build_model(build_model))
|
.update(self, |_, cx| cx.build_model(build_model))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_model<T: 'static, R>(
|
fn update_model<T: 'static, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
handle: &Model<T>,
|
handle: &Model<T>,
|
||||||
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||||
) -> Result<R> {
|
) -> Result<R> {
|
||||||
self.app
|
self.window
|
||||||
.update_window(self.window, |cx| cx.update_model(handle, update))
|
.update(self, |_, cx| cx.update_model(handle, update))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_window<T, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<T>
|
||||||
|
where
|
||||||
|
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
|
||||||
|
{
|
||||||
|
self.app.update_window(window, update)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
impl VisualContext for AsyncWindowContext {
|
||||||
mod tests {
|
fn build_view<V>(
|
||||||
use super::*;
|
&mut self,
|
||||||
|
build_view_state: impl FnOnce(&mut ViewContext<'_, V>) -> V,
|
||||||
|
) -> Self::Result<View<V>>
|
||||||
|
where
|
||||||
|
V: 'static,
|
||||||
|
{
|
||||||
|
self.window
|
||||||
|
.update(self, |_, cx| cx.build_view(build_view_state))
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
fn update_view<V: 'static, R>(
|
||||||
fn test_async_app_context_send_sync() {
|
&mut self,
|
||||||
fn assert_send_sync<T: Send + Sync>() {}
|
view: &View<V>,
|
||||||
assert_send_sync::<AsyncAppContext>();
|
update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
|
||||||
|
) -> Self::Result<R> {
|
||||||
|
self.window
|
||||||
|
.update(self, |_, cx| cx.update_view(view, update))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn replace_root_view<V>(
|
||||||
|
&mut self,
|
||||||
|
build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
|
||||||
|
) -> Self::Result<View<V>>
|
||||||
|
where
|
||||||
|
V: Render,
|
||||||
|
{
|
||||||
|
self.window
|
||||||
|
.update(self, |_, cx| cx.replace_root_view(build_view))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
use crate::{private::Sealed, AnyBox, AppContext, Context, Entity};
|
use crate::{private::Sealed, AnyBox, AppContext, Context, Entity, ModelContext};
|
||||||
use anyhow::{anyhow, Result};
|
use anyhow::{anyhow, Result};
|
||||||
use derive_more::{Deref, DerefMut};
|
use derive_more::{Deref, DerefMut};
|
||||||
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
|
use parking_lot::{RwLock, RwLockUpgradableReadGuard};
|
||||||
|
@ -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));
|
||||||
|
@ -169,6 +169,10 @@ impl AnyModel {
|
||||||
self.entity_id
|
self.entity_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn entity_type(&self) -> TypeId {
|
||||||
|
self.entity_type
|
||||||
|
}
|
||||||
|
|
||||||
pub fn downgrade(&self) -> AnyWeakModel {
|
pub fn downgrade(&self) -> AnyWeakModel {
|
||||||
AnyWeakModel {
|
AnyWeakModel {
|
||||||
entity_id: self.entity_id,
|
entity_id: self.entity_id,
|
||||||
|
@ -329,7 +333,7 @@ impl<T: 'static> Model<T> {
|
||||||
pub fn update<C, R>(
|
pub fn update<C, R>(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut C,
|
cx: &mut C,
|
||||||
update: impl FnOnce(&mut T, &mut C::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||||
) -> C::Result<R>
|
) -> C::Result<R>
|
||||||
where
|
where
|
||||||
C: Context,
|
C: Context,
|
||||||
|
@ -475,7 +479,7 @@ impl<T: 'static> WeakModel<T> {
|
||||||
pub fn update<C, R>(
|
pub fn update<C, R>(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut C,
|
cx: &mut C,
|
||||||
update: impl FnOnce(&mut T, &mut C::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||||
) -> Result<R>
|
) -> Result<R>
|
||||||
where
|
where
|
||||||
C: Context,
|
C: Context,
|
||||||
|
|
|
@ -1,7 +1,8 @@
|
||||||
use crate::{
|
use crate::{
|
||||||
AppContext, AsyncAppContext, Context, Effect, Entity, EntityId, EventEmitter, MainThread,
|
AnyView, AnyWindowHandle, AppContext, AsyncAppContext, Context, Effect, Entity, EntityId,
|
||||||
Model, Reference, Subscription, Task, WeakModel,
|
EventEmitter, Model, Subscription, Task, WeakModel, WindowContext,
|
||||||
};
|
};
|
||||||
|
use anyhow::Result;
|
||||||
use derive_more::{Deref, DerefMut};
|
use derive_more::{Deref, DerefMut};
|
||||||
use futures::FutureExt;
|
use futures::FutureExt;
|
||||||
use std::{
|
use std::{
|
||||||
|
@ -14,16 +15,13 @@ use std::{
|
||||||
pub struct ModelContext<'a, T> {
|
pub struct ModelContext<'a, T> {
|
||||||
#[deref]
|
#[deref]
|
||||||
#[deref_mut]
|
#[deref_mut]
|
||||||
app: Reference<'a, AppContext>,
|
app: &'a mut AppContext,
|
||||||
model_state: WeakModel<T>,
|
model_state: WeakModel<T>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T: 'static> ModelContext<'a, T> {
|
impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
pub(crate) fn mutable(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self {
|
pub(crate) fn new(app: &'a mut AppContext, model_state: WeakModel<T>) -> Self {
|
||||||
Self {
|
Self { app, model_state }
|
||||||
app: Reference::Mutable(app),
|
|
||||||
model_state,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn entity_id(&self) -> EntityId {
|
pub fn entity_id(&self) -> EntityId {
|
||||||
|
@ -40,15 +38,15 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
self.model_state.clone()
|
self.model_state.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn observe<T2, E>(
|
pub fn observe<W, E>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &E,
|
entity: &E,
|
||||||
mut on_notify: impl FnMut(&mut T, E, &mut ModelContext<'_, T>) + Send + 'static,
|
mut on_notify: impl FnMut(&mut T, E, &mut ModelContext<'_, T>) + 'static,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
T: 'static + Send,
|
T: 'static,
|
||||||
T2: 'static,
|
W: 'static,
|
||||||
E: Entity<T2>,
|
E: Entity<W>,
|
||||||
{
|
{
|
||||||
let this = self.weak_model();
|
let this = self.weak_model();
|
||||||
let entity_id = entity.entity_id();
|
let entity_id = entity.entity_id();
|
||||||
|
@ -69,10 +67,10 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
pub fn subscribe<T2, E>(
|
pub fn subscribe<T2, E>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &E,
|
entity: &E,
|
||||||
mut on_event: impl FnMut(&mut T, E, &T2::Event, &mut ModelContext<'_, T>) + Send + 'static,
|
mut on_event: impl FnMut(&mut T, E, &T2::Event, &mut ModelContext<'_, T>) + 'static,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
T: 'static + Send,
|
T: 'static,
|
||||||
T2: 'static + EventEmitter,
|
T2: 'static + EventEmitter,
|
||||||
E: Entity<T2>,
|
E: Entity<T2>,
|
||||||
{
|
{
|
||||||
|
@ -95,7 +93,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
|
|
||||||
pub fn on_release(
|
pub fn on_release(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut on_release: impl FnMut(&mut T, &mut AppContext) + Send + 'static,
|
on_release: impl FnOnce(&mut T, &mut AppContext) + 'static,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
T: 'static,
|
T: 'static,
|
||||||
|
@ -112,10 +110,10 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
pub fn observe_release<T2, E>(
|
pub fn observe_release<T2, E>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &E,
|
entity: &E,
|
||||||
mut on_release: impl FnMut(&mut T, &mut T2, &mut ModelContext<'_, T>) + Send + 'static,
|
on_release: impl FnOnce(&mut T, &mut T2, &mut ModelContext<'_, T>) + 'static,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
T: Any + Send,
|
T: Any,
|
||||||
T2: 'static,
|
T2: 'static,
|
||||||
E: Entity<T2>,
|
E: Entity<T2>,
|
||||||
{
|
{
|
||||||
|
@ -134,10 +132,10 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
|
|
||||||
pub fn observe_global<G: 'static>(
|
pub fn observe_global<G: 'static>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + Send + 'static,
|
mut f: impl FnMut(&mut T, &mut ModelContext<'_, T>) + 'static,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
T: 'static + Send,
|
T: 'static,
|
||||||
{
|
{
|
||||||
let handle = self.weak_model();
|
let handle = self.weak_model();
|
||||||
self.global_observers.insert(
|
self.global_observers.insert(
|
||||||
|
@ -148,11 +146,11 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
|
|
||||||
pub fn on_app_quit<Fut>(
|
pub fn on_app_quit<Fut>(
|
||||||
&mut self,
|
&mut self,
|
||||||
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + Send + 'static,
|
mut on_quit: impl FnMut(&mut T, &mut ModelContext<T>) -> Fut + 'static,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
Fut: 'static + Future<Output = ()> + Send,
|
Fut: 'static + Future<Output = ()>,
|
||||||
T: 'static + Send,
|
T: 'static,
|
||||||
{
|
{
|
||||||
let handle = self.weak_model();
|
let handle = self.weak_model();
|
||||||
self.app.quit_observers.insert(
|
self.app.quit_observers.insert(
|
||||||
|
@ -164,7 +162,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
future.await;
|
future.await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.boxed()
|
.boxed_local()
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
@ -183,7 +181,7 @@ impl<'a, T: 'static> ModelContext<'a, T> {
|
||||||
|
|
||||||
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
pub fn update_global<G, R>(&mut self, f: impl FnOnce(&mut G, &mut Self) -> R) -> R
|
||||||
where
|
where
|
||||||
G: 'static + Send,
|
G: 'static,
|
||||||
{
|
{
|
||||||
let mut global = self.app.lease_global::<G>();
|
let mut global = self.app.lease_global::<G>();
|
||||||
let result = f(&mut global, self);
|
let result = f(&mut global, self);
|
||||||
|
@ -191,36 +189,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 {
|
||||||
|
@ -231,26 +213,29 @@ where
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, T> Context for ModelContext<'a, T> {
|
impl<'a, T> Context for ModelContext<'a, T> {
|
||||||
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 ModelContext<'_, U>) -> U,
|
||||||
) -> Model<U>
|
) -> Model<U> {
|
||||||
where
|
|
||||||
U: 'static + Send,
|
|
||||||
{
|
|
||||||
self.app.build_model(build_model)
|
self.app.build_model(build_model)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_model<U: 'static, R>(
|
fn update_model<U: 'static, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
handle: &Model<U>,
|
handle: &Model<U>,
|
||||||
update: impl FnOnce(&mut U, &mut Self::ModelContext<'_, U>) -> R,
|
update: impl FnOnce(&mut U, &mut ModelContext<'_, U>) -> R,
|
||||||
) -> R {
|
) -> R {
|
||||||
self.app.update_model(handle, update)
|
self.app.update_model(handle, update)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn update_window<R, F>(&mut self, window: AnyWindowHandle, update: F) -> Result<R>
|
||||||
|
where
|
||||||
|
F: FnOnce(AnyView, &mut WindowContext<'_>) -> R,
|
||||||
|
{
|
||||||
|
self.app.update_window(window, update)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> Borrow<AppContext> for ModelContext<'_, T> {
|
impl<T> Borrow<AppContext> for ModelContext<'_, T> {
|
||||||
|
|
|
@ -1,138 +1,115 @@
|
||||||
use crate::{
|
use crate::{
|
||||||
AnyWindowHandle, AppContext, AsyncAppContext, Context, EventEmitter, Executor, MainThread,
|
AnyView, AnyWindowHandle, AppContext, AsyncAppContext, BackgroundExecutor, Context,
|
||||||
Model, ModelContext, Result, Task, TestDispatcher, TestPlatform, WindowContext,
|
EventEmitter, ForegroundExecutor, Model, ModelContext, Result, Task, TestDispatcher,
|
||||||
|
TestPlatform, WindowContext,
|
||||||
};
|
};
|
||||||
use futures::SinkExt;
|
use anyhow::{anyhow, bail};
|
||||||
use parking_lot::Mutex;
|
use futures::{Stream, StreamExt};
|
||||||
use std::{future::Future, sync::Arc};
|
use std::{cell::RefCell, future::Future, rc::Rc, sync::Arc, time::Duration};
|
||||||
|
|
||||||
#[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 {
|
||||||
type ModelContext<'a, T> = ModelContext<'a, T>;
|
|
||||||
type Result<T> = T;
|
type Result<T> = T;
|
||||||
|
|
||||||
fn build_model<T: 'static>(
|
fn build_model<T: 'static>(
|
||||||
&mut self,
|
&mut self,
|
||||||
build_model: impl FnOnce(&mut Self::ModelContext<'_, T>) -> T,
|
build_model: impl FnOnce(&mut 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>(
|
||||||
&mut self,
|
&mut self,
|
||||||
handle: &Model<T>,
|
handle: &Model<T>,
|
||||||
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||||
|
where
|
||||||
|
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T,
|
||||||
|
{
|
||||||
|
let mut lock = self.app.borrow_mut();
|
||||||
|
lock.update_window(window, f)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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 foreground_executor(&self) -> &ForegroundExecutor {
|
||||||
|
&self.foreground_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)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn read_window<R>(
|
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut) -> Task<R>
|
||||||
&self,
|
|
||||||
handle: AnyWindowHandle,
|
|
||||||
read: impl FnOnce(&WindowContext) -> R,
|
|
||||||
) -> R {
|
|
||||||
let mut app_context = self.app.lock();
|
|
||||||
app_context.read_window(handle.id, read).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn update_window<R>(
|
|
||||||
&self,
|
|
||||||
handle: AnyWindowHandle,
|
|
||||||
update: impl FnOnce(&mut WindowContext) -> R,
|
|
||||||
) -> R {
|
|
||||||
let mut app = self.app.lock();
|
|
||||||
app.update_window(handle.id, update).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn spawn<Fut, R>(&self, f: impl FnOnce(AsyncAppContext) -> Fut + Send + 'static) -> 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,32 +117,75 @@ 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(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn subscribe<T: 'static + EventEmitter + Send>(
|
pub fn notifications<T: 'static>(&mut self, entity: &Model<T>) -> impl Stream<Item = ()> {
|
||||||
|
let (tx, rx) = futures::channel::mpsc::unbounded();
|
||||||
|
|
||||||
|
entity.update(self, move |_, cx: &mut ModelContext<T>| {
|
||||||
|
cx.observe(entity, {
|
||||||
|
let tx = tx.clone();
|
||||||
|
move |_, _, _| {
|
||||||
|
let _ = tx.unbounded_send(());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
|
||||||
|
cx.on_release(move |_, _| tx.close_channel()).detach();
|
||||||
|
});
|
||||||
|
|
||||||
|
rx
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn events<T: 'static + EventEmitter>(
|
||||||
&mut self,
|
&mut self,
|
||||||
entity: &Model<T>,
|
entity: &Model<T>,
|
||||||
) -> futures::channel::mpsc::UnboundedReceiver<T::Event>
|
) -> futures::channel::mpsc::UnboundedReceiver<T::Event>
|
||||||
where
|
where
|
||||||
T::Event: 'static + Send + Clone,
|
T::Event: 'static + Clone,
|
||||||
{
|
{
|
||||||
let (mut tx, rx) = futures::channel::mpsc::unbounded();
|
let (tx, rx) = futures::channel::mpsc::unbounded();
|
||||||
entity
|
entity
|
||||||
.update(self, |_, cx: &mut ModelContext<T>| {
|
.update(self, |_, cx: &mut ModelContext<T>| {
|
||||||
cx.subscribe(entity, move |_, _, event, cx| {
|
cx.subscribe(entity, move |_model, _handle, event, _cx| {
|
||||||
cx.executor().block(tx.send(event.clone())).unwrap();
|
let _ = tx.unbounded_send(event.clone());
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
.detach();
|
.detach();
|
||||||
rx
|
rx
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn condition<T: 'static>(
|
||||||
|
&mut self,
|
||||||
|
model: &Model<T>,
|
||||||
|
mut predicate: impl FnMut(&mut T, &mut ModelContext<T>) -> bool,
|
||||||
|
) {
|
||||||
|
let timer = self.executor().timer(Duration::from_secs(3));
|
||||||
|
let mut notifications = self.notifications(model);
|
||||||
|
|
||||||
|
use futures::FutureExt as _;
|
||||||
|
use smol::future::FutureExt as _;
|
||||||
|
|
||||||
|
async {
|
||||||
|
while notifications.next().await.is_some() {
|
||||||
|
if model.update(self, &mut predicate) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
bail!("model dropped")
|
||||||
|
}
|
||||||
|
.race(timer.map(|_| Err(anyhow!("condition timed out"))))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -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)))
|
||||||
}
|
}
|
||||||
|
@ -220,8 +218,8 @@ impl<V> Component<V> for AnyElement<V> {
|
||||||
impl<V, E, F> Element<V> for Option<F>
|
impl<V, E, F> Element<V> for Option<F>
|
||||||
where
|
where
|
||||||
V: 'static,
|
V: 'static,
|
||||||
E: 'static + Component<V> + Send,
|
E: 'static + Component<V>,
|
||||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
|
||||||
{
|
{
|
||||||
type ElementState = AnyElement<V>;
|
type ElementState = AnyElement<V>;
|
||||||
|
|
||||||
|
@ -264,8 +262,8 @@ where
|
||||||
impl<V, E, F> Component<V> for Option<F>
|
impl<V, E, F> Component<V> for Option<F>
|
||||||
where
|
where
|
||||||
V: 'static,
|
V: 'static,
|
||||||
E: 'static + Component<V> + Send,
|
E: 'static + Component<V>,
|
||||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
|
||||||
{
|
{
|
||||||
fn render(self) -> AnyElement<V> {
|
fn render(self) -> AnyElement<V> {
|
||||||
AnyElement::new(self)
|
AnyElement::new(self)
|
||||||
|
@ -275,8 +273,8 @@ where
|
||||||
impl<V, E, F> Component<V> for F
|
impl<V, E, F> Component<V> for F
|
||||||
where
|
where
|
||||||
V: 'static,
|
V: 'static,
|
||||||
E: 'static + Component<V> + Send,
|
E: 'static + Component<V>,
|
||||||
F: FnOnce(&mut V, &mut ViewContext<'_, '_, V>) -> E + Send + 'static,
|
F: FnOnce(&mut V, &mut ViewContext<'_, V>) -> E + 'static,
|
||||||
{
|
{
|
||||||
fn render(self) -> AnyElement<V> {
|
fn render(self) -> AnyElement<V> {
|
||||||
AnyElement::new(Some(self))
|
AnyElement::new(Some(self))
|
||||||
|
|
|
@ -305,7 +305,6 @@ where
|
||||||
|
|
||||||
impl<V, I, F> Component<V> for Div<V, I, F>
|
impl<V, I, F> Component<V> for Div<V, I, F>
|
||||||
where
|
where
|
||||||
// V: Any + Send + Sync,
|
|
||||||
I: ElementInteraction<V>,
|
I: ElementInteraction<V>,
|
||||||
F: ElementFocus<V>,
|
F: ElementFocus<V>,
|
||||||
{
|
{
|
||||||
|
|
|
@ -44,9 +44,6 @@ pub struct Text<V> {
|
||||||
state_type: PhantomData<V>,
|
state_type: PhantomData<V>,
|
||||||
}
|
}
|
||||||
|
|
||||||
unsafe impl<V> Send for Text<V> {}
|
|
||||||
unsafe impl<V> Sync for Text<V> {}
|
|
||||||
|
|
||||||
impl<V: 'static> Component<V> for Text<V> {
|
impl<V: 'static> Component<V> for Text<V> {
|
||||||
fn render(self) -> AnyElement<V> {
|
fn render(self) -> AnyElement<V> {
|
||||||
AnyElement::new(self)
|
AnyElement::new(self)
|
||||||
|
|
|
@ -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>),
|
||||||
|
@ -46,7 +53,7 @@ where
|
||||||
E: 'static + Send + Debug,
|
E: 'static + Send + Debug,
|
||||||
{
|
{
|
||||||
pub fn detach_and_log_err(self, cx: &mut AppContext) {
|
pub fn detach_and_log_err(self, cx: &mut AppContext) {
|
||||||
cx.executor().spawn(self.log_err()).detach();
|
cx.background_executor().spawn(self.log_err()).detach();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -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,72 +86,30 @@ impl Executor {
|
||||||
Task::Spawned(task)
|
Task::Spawned(task)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Enqueues the given closure to run on the application's event loop.
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
/// Returns the result asynchronously.
|
pub fn block_test<R>(&self, future: impl Future<Output = R>) -> R {
|
||||||
pub fn run_on_main<F, R>(&self, func: F) -> Task<R>
|
self.block_internal(false, future)
|
||||||
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);
|
self.block_internal(true, future)
|
||||||
let (parker, unparker) = parking::pair();
|
}
|
||||||
let awoken = Arc::new(AtomicBool::new(false));
|
|
||||||
let awoken2 = awoken.clone();
|
|
||||||
|
|
||||||
let waker = waker_fn(move || {
|
pub(crate) fn block_internal<R>(
|
||||||
awoken2.store(true, SeqCst);
|
&self,
|
||||||
unparker.unpark();
|
background_only: bool,
|
||||||
|
future: impl Future<Output = R>,
|
||||||
|
) -> R {
|
||||||
|
pin_mut!(future);
|
||||||
|
let unparker = self.dispatcher.unparker();
|
||||||
|
let awoken = Arc::new(AtomicBool::new(false));
|
||||||
|
|
||||||
|
let waker = waker_fn({
|
||||||
|
let awoken = awoken.clone();
|
||||||
|
move || {
|
||||||
|
awoken.store(true, SeqCst);
|
||||||
|
unparker.unpark();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
let mut cx = std::task::Context::from_waker(&waker);
|
let mut cx = std::task::Context::from_waker(&waker);
|
||||||
|
|
||||||
|
@ -152,7 +117,7 @@ impl Executor {
|
||||||
match future.as_mut().poll(&mut cx) {
|
match future.as_mut().poll(&mut cx) {
|
||||||
Poll::Ready(result) => return result,
|
Poll::Ready(result) => return result,
|
||||||
Poll::Pending => {
|
Poll::Pending => {
|
||||||
if !self.dispatcher.poll() {
|
if !self.dispatcher.poll(background_only) {
|
||||||
if awoken.swap(false, SeqCst) {
|
if awoken.swap(false, SeqCst) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
@ -168,7 +133,8 @@ impl Executor {
|
||||||
panic!("parked with nothing left to run\n{:?}", backtrace_message)
|
panic!("parked with nothing left to run\n{:?}", backtrace_message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
parker.park();
|
|
||||||
|
self.dispatcher.park();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -234,7 +200,7 @@ impl Executor {
|
||||||
|
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
pub fn simulate_random_delay(&self) -> impl Future<Output = ()> {
|
pub fn simulate_random_delay(&self) -> impl Future<Output = ()> {
|
||||||
self.spawn(self.dispatcher.as_test().unwrap().simulate_random_delay())
|
self.dispatcher.as_test().unwrap().simulate_random_delay()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
|
@ -261,8 +227,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 +259,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,
|
||||||
|
|
|
@ -8,7 +8,7 @@ use smallvec::SmallVec;
|
||||||
pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;
|
pub type FocusListeners<V> = SmallVec<[FocusListener<V>; 2]>;
|
||||||
|
|
||||||
pub type FocusListener<V> =
|
pub type FocusListener<V> =
|
||||||
Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + Send + 'static>;
|
Box<dyn Fn(&mut V, &FocusHandle, &FocusEvent, &mut ViewContext<V>) + 'static>;
|
||||||
|
|
||||||
pub trait Focusable<V: 'static>: Element<V> {
|
pub trait Focusable<V: 'static>: Element<V> {
|
||||||
fn focus_listeners(&mut self) -> &mut FocusListeners<V>;
|
fn focus_listeners(&mut self) -> &mut FocusListeners<V>;
|
||||||
|
@ -42,7 +42,7 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||||
|
|
||||||
fn on_focus(
|
fn on_focus(
|
||||||
mut self,
|
mut self,
|
||||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
|
||||||
) -> Self
|
) -> Self
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
|
@ -58,7 +58,7 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||||
|
|
||||||
fn on_blur(
|
fn on_blur(
|
||||||
mut self,
|
mut self,
|
||||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
|
||||||
) -> Self
|
) -> Self
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
|
@ -74,7 +74,7 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||||
|
|
||||||
fn on_focus_in(
|
fn on_focus_in(
|
||||||
mut self,
|
mut self,
|
||||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
|
||||||
) -> Self
|
) -> Self
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
|
@ -99,7 +99,7 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||||
|
|
||||||
fn on_focus_out(
|
fn on_focus_out(
|
||||||
mut self,
|
mut self,
|
||||||
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + Send + 'static,
|
listener: impl Fn(&mut V, &FocusEvent, &mut ViewContext<V>) + 'static,
|
||||||
) -> Self
|
) -> Self
|
||||||
where
|
where
|
||||||
Self: Sized,
|
Self: Sized,
|
||||||
|
@ -122,7 +122,7 @@ pub trait Focusable<V: 'static>: Element<V> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait ElementFocus<V: 'static>: 'static + Send {
|
pub trait ElementFocus<V: 'static>: 'static {
|
||||||
fn as_focusable(&self) -> Option<&FocusEnabled<V>>;
|
fn as_focusable(&self) -> Option<&FocusEnabled<V>>;
|
||||||
fn as_focusable_mut(&mut self) -> Option<&mut FocusEnabled<V>>;
|
fn as_focusable_mut(&mut self) -> Option<&mut FocusEnabled<V>>;
|
||||||
|
|
||||||
|
|
|
@ -931,6 +931,18 @@ impl From<f64> for GlobalPixels {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl sqlez::bindable::StaticColumnCount for GlobalPixels {}
|
||||||
|
|
||||||
|
impl sqlez::bindable::Bind for GlobalPixels {
|
||||||
|
fn bind(
|
||||||
|
&self,
|
||||||
|
statement: &sqlez::statement::Statement,
|
||||||
|
start_index: i32,
|
||||||
|
) -> anyhow::Result<i32> {
|
||||||
|
self.0.bind(statement, start_index)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Copy, Default, Add, Sub, Mul, Div, Neg)]
|
#[derive(Clone, Copy, Default, Add, Sub, Mul, Div, Neg)]
|
||||||
pub struct Rems(f32);
|
pub struct Rems(f32);
|
||||||
|
|
||||||
|
|
|
@ -68,51 +68,56 @@ 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},
|
|
||||||
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 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 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, R>(
|
||||||
&mut self,
|
&mut self,
|
||||||
handle: &Model<T>,
|
handle: &Model<T>,
|
||||||
update: impl FnOnce(&mut T, &mut Self::ModelContext<'_, T>) -> R,
|
update: impl FnOnce(&mut T, &mut ModelContext<'_, T>) -> R,
|
||||||
) -> Self::Result<R>;
|
) -> Self::Result<R>
|
||||||
|
where
|
||||||
|
T: 'static;
|
||||||
|
|
||||||
|
fn update_window<T, F>(&mut self, window: AnyWindowHandle, f: F) -> Result<T>
|
||||||
|
where
|
||||||
|
F: FnOnce(AnyView, &mut WindowContext<'_>) -> T;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait VisualContext: Context {
|
pub trait VisualContext: Context {
|
||||||
type ViewContext<'a, 'w, V>;
|
|
||||||
|
|
||||||
fn build_view<V>(
|
fn build_view<V>(
|
||||||
&mut self,
|
&mut self,
|
||||||
build_view_state: impl FnOnce(&mut Self::ViewContext<'_, '_, V>) -> V,
|
build_view: impl FnOnce(&mut 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,
|
||||||
view: &View<V>,
|
view: &View<V>,
|
||||||
update: impl FnOnce(&mut V, &mut Self::ViewContext<'_, '_, V>) -> R,
|
update: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
|
||||||
) -> Self::Result<R>;
|
) -> Self::Result<R>;
|
||||||
|
|
||||||
|
fn replace_root_view<V>(
|
||||||
|
&mut self,
|
||||||
|
build_view: impl FnOnce(&mut ViewContext<'_, V>) -> V,
|
||||||
|
) -> Self::Result<View<V>>
|
||||||
|
where
|
||||||
|
V: Render;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub trait Entity<T>: Sealed {
|
pub trait Entity<T>: Sealed {
|
||||||
type Weak: 'static + Send;
|
type Weak: 'static;
|
||||||
|
|
||||||
fn entity_id(&self) -> EntityId;
|
fn entity_id(&self) -> EntityId;
|
||||||
fn downgrade(&self) -> Self::Weak;
|
fn downgrade(&self) -> Self::Weak;
|
||||||
|
@ -127,106 +132,12 @@ 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
|
||||||
F: FnOnce(&mut Self) -> R;
|
F: FnOnce(&mut Self) -> R;
|
||||||
|
|
||||||
fn set_global<T: Send + 'static>(&mut self, global: T);
|
fn set_global<T: 'static>(&mut self, global: T);
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<C> BorrowAppContext for C
|
impl<C> BorrowAppContext for C
|
||||||
|
@ -243,7 +154,7 @@ where
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_global<G: 'static + Send>(&mut self, global: G) {
|
fn set_global<G: 'static>(&mut self, global: G) {
|
||||||
self.borrow_mut().set_global(global)
|
self.borrow_mut().set_global(global)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -306,59 +217,3 @@ impl<T: Into<ArcCow<'static, str>>> From<T> for SharedString {
|
||||||
Self(value.into())
|
Self(value.into())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub enum Reference<'a, T> {
|
|
||||||
Immutable(&'a T),
|
|
||||||
Mutable(&'a mut T),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T> Deref for Reference<'a, T> {
|
|
||||||
type Target = T;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
match self {
|
|
||||||
Reference::Immutable(target) => target,
|
|
||||||
Reference::Mutable(target) => target,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a, T> DerefMut for Reference<'a, T> {
|
|
||||||
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
||||||
match self {
|
|
||||||
Reference::Immutable(_) => {
|
|
||||||
panic!("cannot mutably deref an immutable reference. this is a bug in GPUI.");
|
|
||||||
}
|
|
||||||
Reference::Mutable(target) => target,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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> {}
|
|
||||||
|
|
|
@ -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,
|
||||||
>;
|
>;
|
||||||
|
|
|
@ -5,15 +5,19 @@ mod mac;
|
||||||
mod test;
|
mod test;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
AnyWindowHandle, Bounds, DevicePixels, Executor, Font, FontId, FontMetrics, FontRun,
|
point, size, AnyWindowHandle, BackgroundExecutor, Bounds, DevicePixels, Font, FontId,
|
||||||
GlobalPixels, GlyphId, InputEvent, LineLayout, Pixels, Point, RenderGlyphParams,
|
FontMetrics, FontRun, ForegroundExecutor, GlobalPixels, GlyphId, InputEvent, LineLayout,
|
||||||
RenderImageParams, RenderSvgParams, Result, Scene, SharedString, Size,
|
Pixels, Point, RenderGlyphParams, RenderImageParams, RenderSvgParams, Result, Scene,
|
||||||
|
SharedString, Size,
|
||||||
};
|
};
|
||||||
use anyhow::anyhow;
|
use anyhow::{anyhow, bail};
|
||||||
use async_task::Runnable;
|
use async_task::Runnable;
|
||||||
use futures::channel::oneshot;
|
use futures::channel::oneshot;
|
||||||
|
use parking::Unparker;
|
||||||
use seahash::SeaHasher;
|
use seahash::SeaHasher;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use sqlez::bindable::{Bind, Column, StaticColumnCount};
|
||||||
|
use sqlez::statement::Statement;
|
||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::hash::{Hash, Hasher};
|
use std::hash::{Hash, Hasher};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
@ -26,6 +30,7 @@ use std::{
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
sync::Arc,
|
sync::Arc,
|
||||||
};
|
};
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub use keystroke::*;
|
pub use keystroke::*;
|
||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
|
@ -35,12 +40,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()>);
|
||||||
|
@ -104,6 +110,9 @@ pub(crate) trait Platform: 'static {
|
||||||
|
|
||||||
pub trait PlatformDisplay: Send + Sync + Debug {
|
pub trait PlatformDisplay: Send + Sync + Debug {
|
||||||
fn id(&self) -> DisplayId;
|
fn id(&self) -> DisplayId;
|
||||||
|
/// Returns a stable identifier for this display that can be persisted and used
|
||||||
|
/// across system restarts.
|
||||||
|
fn uuid(&self) -> Result<Uuid>;
|
||||||
fn as_any(&self) -> &dyn Any;
|
fn as_any(&self) -> &dyn Any;
|
||||||
fn bounds(&self) -> Bounds<GlobalPixels>;
|
fn bounds(&self) -> Bounds<GlobalPixels>;
|
||||||
}
|
}
|
||||||
|
@ -129,12 +138,7 @@ pub(crate) trait PlatformWindow {
|
||||||
fn mouse_position(&self) -> Point<Pixels>;
|
fn mouse_position(&self) -> Point<Pixels>;
|
||||||
fn as_any_mut(&mut self) -> &mut dyn Any;
|
fn as_any_mut(&mut self) -> &mut dyn Any;
|
||||||
fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>);
|
fn set_input_handler(&mut self, input_handler: Box<dyn PlatformInputHandler>);
|
||||||
fn prompt(
|
fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize>;
|
||||||
&self,
|
|
||||||
level: WindowPromptLevel,
|
|
||||||
msg: &str,
|
|
||||||
answers: &[&str],
|
|
||||||
) -> oneshot::Receiver<usize>;
|
|
||||||
fn activate(&self);
|
fn activate(&self);
|
||||||
fn set_title(&mut self, title: &str);
|
fn set_title(&mut self, title: &str);
|
||||||
fn set_edited(&mut self, edited: bool);
|
fn set_edited(&mut self, edited: bool);
|
||||||
|
@ -161,7 +165,9 @@ pub trait PlatformDispatcher: Send + Sync {
|
||||||
fn dispatch(&self, runnable: Runnable);
|
fn dispatch(&self, runnable: Runnable);
|
||||||
fn dispatch_on_main_thread(&self, runnable: Runnable);
|
fn dispatch_on_main_thread(&self, runnable: Runnable);
|
||||||
fn dispatch_after(&self, duration: Duration, runnable: Runnable);
|
fn dispatch_after(&self, duration: Duration, runnable: Runnable);
|
||||||
fn poll(&self) -> bool;
|
fn poll(&self, background_only: bool) -> bool;
|
||||||
|
fn park(&self);
|
||||||
|
fn unparker(&self) -> Unparker;
|
||||||
|
|
||||||
#[cfg(any(test, feature = "test-support"))]
|
#[cfg(any(test, feature = "test-support"))]
|
||||||
fn as_test(&self) -> Option<&TestDispatcher> {
|
fn as_test(&self) -> Option<&TestDispatcher> {
|
||||||
|
@ -368,6 +374,67 @@ pub enum WindowBounds {
|
||||||
Fixed(Bounds<GlobalPixels>),
|
Fixed(Bounds<GlobalPixels>),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl StaticColumnCount for WindowBounds {
|
||||||
|
fn column_count() -> usize {
|
||||||
|
5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Bind for WindowBounds {
|
||||||
|
fn bind(&self, statement: &Statement, start_index: i32) -> Result<i32> {
|
||||||
|
let (region, next_index) = match self {
|
||||||
|
WindowBounds::Fullscreen => {
|
||||||
|
let next_index = statement.bind(&"Fullscreen", start_index)?;
|
||||||
|
(None, next_index)
|
||||||
|
}
|
||||||
|
WindowBounds::Maximized => {
|
||||||
|
let next_index = statement.bind(&"Maximized", start_index)?;
|
||||||
|
(None, next_index)
|
||||||
|
}
|
||||||
|
WindowBounds::Fixed(region) => {
|
||||||
|
let next_index = statement.bind(&"Fixed", start_index)?;
|
||||||
|
(Some(*region), next_index)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
statement.bind(
|
||||||
|
®ion.map(|region| {
|
||||||
|
(
|
||||||
|
region.origin.x,
|
||||||
|
region.origin.y,
|
||||||
|
region.size.width,
|
||||||
|
region.size.height,
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
next_index,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Column for WindowBounds {
|
||||||
|
fn column(statement: &mut Statement, start_index: i32) -> Result<(Self, i32)> {
|
||||||
|
let (window_state, next_index) = String::column(statement, start_index)?;
|
||||||
|
let bounds = match window_state.as_str() {
|
||||||
|
"Fullscreen" => WindowBounds::Fullscreen,
|
||||||
|
"Maximized" => WindowBounds::Maximized,
|
||||||
|
"Fixed" => {
|
||||||
|
let ((x, y, width, height), _) = Column::column(statement, next_index)?;
|
||||||
|
let x: f64 = x;
|
||||||
|
let y: f64 = y;
|
||||||
|
let width: f64 = width;
|
||||||
|
let height: f64 = height;
|
||||||
|
WindowBounds::Fixed(Bounds {
|
||||||
|
origin: point(x.into(), y.into()),
|
||||||
|
size: size(width.into(), height.into()),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => bail!("Window State did not have a valid string"),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok((bounds, next_index + 4))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug)]
|
#[derive(Copy, Clone, Debug)]
|
||||||
pub enum WindowAppearance {
|
pub enum WindowAppearance {
|
||||||
Light,
|
Light,
|
||||||
|
@ -382,14 +449,6 @@ impl Default for WindowAppearance {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, PartialEq, Default)]
|
|
||||||
pub enum WindowPromptLevel {
|
|
||||||
#[default]
|
|
||||||
Info,
|
|
||||||
Warning,
|
|
||||||
Critical,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug)]
|
#[derive(Copy, Clone, Debug)]
|
||||||
pub struct PathPromptOptions {
|
pub struct PathPromptOptions {
|
||||||
pub files: bool,
|
pub files: bool,
|
||||||
|
|
|
@ -9,8 +9,11 @@ use objc::{
|
||||||
runtime::{BOOL, YES},
|
runtime::{BOOL, YES},
|
||||||
sel, sel_impl,
|
sel, sel_impl,
|
||||||
};
|
};
|
||||||
|
use parking::{Parker, Unparker};
|
||||||
|
use parking_lot::Mutex;
|
||||||
use std::{
|
use std::{
|
||||||
ffi::c_void,
|
ffi::c_void,
|
||||||
|
sync::Arc,
|
||||||
time::{Duration, SystemTime},
|
time::{Duration, SystemTime},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -20,7 +23,17 @@ pub fn dispatch_get_main_queue() -> dispatch_queue_t {
|
||||||
unsafe { &_dispatch_main_q as *const _ as dispatch_queue_t }
|
unsafe { &_dispatch_main_q as *const _ as dispatch_queue_t }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct MacDispatcher;
|
pub struct MacDispatcher {
|
||||||
|
parker: Arc<Mutex<Parker>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MacDispatcher {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
MacDispatcher {
|
||||||
|
parker: Arc::new(Mutex::new(Parker::new())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl PlatformDispatcher for MacDispatcher {
|
impl PlatformDispatcher for MacDispatcher {
|
||||||
fn is_main_thread(&self) -> bool {
|
fn is_main_thread(&self) -> bool {
|
||||||
|
@ -68,33 +81,20 @@ impl PlatformDispatcher for MacDispatcher {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll(&self) -> bool {
|
fn poll(&self, _background_only: bool) -> bool {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn park(&self) {
|
||||||
|
self.parker.lock().park()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unparker(&self) -> Unparker {
|
||||||
|
self.parker.lock().unparker()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
extern "C" fn trampoline(runnable: *mut c_void) {
|
extern "C" fn trampoline(runnable: *mut c_void) {
|
||||||
let task = unsafe { Runnable::from_raw(runnable as *mut ()) };
|
let task = unsafe { Runnable::from_raw(runnable as *mut ()) };
|
||||||
task.run();
|
task.run();
|
||||||
}
|
}
|
||||||
|
|
||||||
// #include <dispatch/dispatch.h>
|
|
||||||
|
|
||||||
// int main(void) {
|
|
||||||
|
|
||||||
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
|
|
||||||
// // Do some lengthy background work here...
|
|
||||||
// printf("Background Work\n");
|
|
||||||
|
|
||||||
// dispatch_async(dispatch_get_main_queue(), ^{
|
|
||||||
// // Once done, update your UI on the main queue here.
|
|
||||||
// printf("UI Updated\n");
|
|
||||||
|
|
||||||
// });
|
|
||||||
// });
|
|
||||||
|
|
||||||
// sleep(3); // prevent the program from terminating immediately
|
|
||||||
|
|
||||||
// return 0;
|
|
||||||
// }
|
|
||||||
// ```
|
|
||||||
|
|
|
@ -1,9 +1,12 @@
|
||||||
use crate::{point, size, Bounds, DisplayId, GlobalPixels, PlatformDisplay};
|
use crate::{point, size, Bounds, DisplayId, GlobalPixels, PlatformDisplay};
|
||||||
|
use anyhow::Result;
|
||||||
|
use core_foundation::uuid::{CFUUIDGetUUIDBytes, CFUUIDRef};
|
||||||
use core_graphics::{
|
use core_graphics::{
|
||||||
display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList},
|
display::{CGDirectDisplayID, CGDisplayBounds, CGGetActiveDisplayList},
|
||||||
geometry::{CGPoint, CGRect, CGSize},
|
geometry::{CGPoint, CGRect, CGSize},
|
||||||
};
|
};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct MacDisplay(pub(crate) CGDirectDisplayID);
|
pub struct MacDisplay(pub(crate) CGDirectDisplayID);
|
||||||
|
@ -11,17 +14,23 @@ pub struct MacDisplay(pub(crate) CGDirectDisplayID);
|
||||||
unsafe impl Send for MacDisplay {}
|
unsafe impl Send for MacDisplay {}
|
||||||
|
|
||||||
impl MacDisplay {
|
impl MacDisplay {
|
||||||
/// Get the screen with the given UUID.
|
/// Get the screen with the given [DisplayId].
|
||||||
pub fn find_by_id(id: DisplayId) -> Option<Self> {
|
pub fn find_by_id(id: DisplayId) -> Option<Self> {
|
||||||
Self::all().find(|screen| screen.id() == id)
|
Self::all().find(|screen| screen.id() == id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the screen with the given persistent [Uuid].
|
||||||
|
pub fn find_by_uuid(uuid: Uuid) -> Option<Self> {
|
||||||
|
Self::all().find(|screen| screen.uuid().ok() == Some(uuid))
|
||||||
|
}
|
||||||
|
|
||||||
/// Get the primary screen - the one with the menu bar, and whose bottom left
|
/// Get the primary screen - the one with the menu bar, and whose bottom left
|
||||||
/// corner is at the origin of the AppKit coordinate system.
|
/// corner is at the origin of the AppKit coordinate system.
|
||||||
pub fn primary() -> Self {
|
pub fn primary() -> Self {
|
||||||
Self::all().next().unwrap()
|
Self::all().next().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Obtains an iterator over all currently active system displays.
|
||||||
pub fn all() -> impl Iterator<Item = Self> {
|
pub fn all() -> impl Iterator<Item = Self> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut display_count: u32 = 0;
|
let mut display_count: u32 = 0;
|
||||||
|
@ -40,6 +49,11 @@ impl MacDisplay {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[link(name = "ApplicationServices", kind = "framework")]
|
||||||
|
extern "C" {
|
||||||
|
pub fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef;
|
||||||
|
}
|
||||||
|
|
||||||
/// Convert the given rectangle from CoreGraphics' native coordinate space to GPUI's coordinate space.
|
/// Convert the given rectangle from CoreGraphics' native coordinate space to GPUI's coordinate space.
|
||||||
///
|
///
|
||||||
/// CoreGraphics' coordinate space has its origin at the bottom left of the primary screen,
|
/// CoreGraphics' coordinate space has its origin at the bottom left of the primary screen,
|
||||||
|
@ -88,6 +102,34 @@ impl PlatformDisplay for MacDisplay {
|
||||||
DisplayId(self.0)
|
DisplayId(self.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn uuid(&self) -> Result<Uuid> {
|
||||||
|
let cfuuid = unsafe { CGDisplayCreateUUIDFromDisplayID(self.0 as CGDirectDisplayID) };
|
||||||
|
anyhow::ensure!(
|
||||||
|
!cfuuid.is_null(),
|
||||||
|
"AppKit returned a null from CGDisplayCreateUUIDFromDisplayID"
|
||||||
|
);
|
||||||
|
|
||||||
|
let bytes = unsafe { CFUUIDGetUUIDBytes(cfuuid) };
|
||||||
|
Ok(Uuid::from_bytes([
|
||||||
|
bytes.byte0,
|
||||||
|
bytes.byte1,
|
||||||
|
bytes.byte2,
|
||||||
|
bytes.byte3,
|
||||||
|
bytes.byte4,
|
||||||
|
bytes.byte5,
|
||||||
|
bytes.byte6,
|
||||||
|
bytes.byte7,
|
||||||
|
bytes.byte8,
|
||||||
|
bytes.byte9,
|
||||||
|
bytes.byte10,
|
||||||
|
bytes.byte11,
|
||||||
|
bytes.byte12,
|
||||||
|
bytes.byte13,
|
||||||
|
bytes.byte14,
|
||||||
|
bytes.byte15,
|
||||||
|
]))
|
||||||
|
}
|
||||||
|
|
||||||
fn as_any(&self) -> &dyn Any {
|
fn as_any(&self) -> &dyn Any {
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
|
@ -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::new());
|
||||||
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),
|
||||||
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 {
|
||||||
|
|
|
@ -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,
|
||||||
Timer, WindowAppearance, WindowBounds, WindowKind, WindowOptions, WindowPromptLevel,
|
PromptLevel, Scene, Size, Timer, WindowAppearance, WindowBounds, WindowKind, WindowOptions,
|
||||||
};
|
};
|
||||||
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();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -741,12 +742,7 @@ impl PlatformWindow for MacWindow {
|
||||||
self.0.as_ref().lock().input_handler = Some(input_handler);
|
self.0.as_ref().lock().input_handler = Some(input_handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prompt(
|
fn prompt(&self, level: PromptLevel, msg: &str, answers: &[&str]) -> oneshot::Receiver<usize> {
|
||||||
&self,
|
|
||||||
level: WindowPromptLevel,
|
|
||||||
msg: &str,
|
|
||||||
answers: &[&str],
|
|
||||||
) -> oneshot::Receiver<usize> {
|
|
||||||
// macOs applies overrides to modal window buttons after they are added.
|
// macOs applies overrides to modal window buttons after they are added.
|
||||||
// Two most important for this logic are:
|
// Two most important for this logic are:
|
||||||
// * Buttons with "Cancel" title will be displayed as the last buttons in the modal
|
// * Buttons with "Cancel" title will be displayed as the last buttons in the modal
|
||||||
|
@ -776,9 +772,9 @@ impl PlatformWindow for MacWindow {
|
||||||
let alert: id = msg_send![class!(NSAlert), alloc];
|
let alert: id = msg_send![class!(NSAlert), alloc];
|
||||||
let alert: id = msg_send![alert, init];
|
let alert: id = msg_send![alert, init];
|
||||||
let alert_style = match level {
|
let alert_style = match level {
|
||||||
WindowPromptLevel::Info => 1,
|
PromptLevel::Info => 1,
|
||||||
WindowPromptLevel::Warning => 0,
|
PromptLevel::Warning => 0,
|
||||||
WindowPromptLevel::Critical => 2,
|
PromptLevel::Critical => 2,
|
||||||
};
|
};
|
||||||
let _: () = msg_send![alert, setAlertStyle: alert_style];
|
let _: () = msg_send![alert, setAlertStyle: alert_style];
|
||||||
let _: () = msg_send![alert, setMessageText: ns_string(msg)];
|
let _: () = msg_send![alert, setMessageText: ns_string(msg)];
|
||||||
|
@ -807,7 +803,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 +820,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 +868,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 +1177,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 +1305,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);
|
||||||
|
|
|
@ -2,6 +2,7 @@ use crate::PlatformDispatcher;
|
||||||
use async_task::Runnable;
|
use async_task::Runnable;
|
||||||
use backtrace::Backtrace;
|
use backtrace::Backtrace;
|
||||||
use collections::{HashMap, VecDeque};
|
use collections::{HashMap, VecDeque};
|
||||||
|
use parking::{Parker, Unparker};
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
use rand::prelude::*;
|
use rand::prelude::*;
|
||||||
use std::{
|
use std::{
|
||||||
|
@ -19,6 +20,8 @@ struct TestDispatcherId(usize);
|
||||||
pub struct TestDispatcher {
|
pub struct TestDispatcher {
|
||||||
id: TestDispatcherId,
|
id: TestDispatcherId,
|
||||||
state: Arc<Mutex<TestDispatcherState>>,
|
state: Arc<Mutex<TestDispatcherState>>,
|
||||||
|
parker: Arc<Mutex<Parker>>,
|
||||||
|
unparker: Unparker,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct TestDispatcherState {
|
struct TestDispatcherState {
|
||||||
|
@ -35,6 +38,7 @@ struct TestDispatcherState {
|
||||||
|
|
||||||
impl TestDispatcher {
|
impl TestDispatcher {
|
||||||
pub fn new(random: StdRng) -> Self {
|
pub fn new(random: StdRng) -> Self {
|
||||||
|
let (parker, unparker) = parking::pair();
|
||||||
let state = TestDispatcherState {
|
let state = TestDispatcherState {
|
||||||
random,
|
random,
|
||||||
foreground: HashMap::default(),
|
foreground: HashMap::default(),
|
||||||
|
@ -50,6 +54,8 @@ impl TestDispatcher {
|
||||||
TestDispatcher {
|
TestDispatcher {
|
||||||
id: TestDispatcherId(0),
|
id: TestDispatcherId(0),
|
||||||
state: Arc::new(Mutex::new(state)),
|
state: Arc::new(Mutex::new(state)),
|
||||||
|
parker: Arc::new(Mutex::new(parker)),
|
||||||
|
unparker,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -96,7 +102,7 @@ impl TestDispatcher {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn run_until_parked(&self) {
|
pub fn run_until_parked(&self) {
|
||||||
while self.poll() {}
|
while self.poll(false) {}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn parking_allowed(&self) -> bool {
|
pub fn parking_allowed(&self) -> bool {
|
||||||
|
@ -129,6 +135,8 @@ impl Clone for TestDispatcher {
|
||||||
Self {
|
Self {
|
||||||
id: TestDispatcherId(id),
|
id: TestDispatcherId(id),
|
||||||
state: self.state.clone(),
|
state: self.state.clone(),
|
||||||
|
parker: self.parker.clone(),
|
||||||
|
unparker: self.unparker.clone(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -140,6 +148,7 @@ impl PlatformDispatcher for TestDispatcher {
|
||||||
|
|
||||||
fn dispatch(&self, runnable: Runnable) {
|
fn dispatch(&self, runnable: Runnable) {
|
||||||
self.state.lock().background.push(runnable);
|
self.state.lock().background.push(runnable);
|
||||||
|
self.unparker.unpark();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dispatch_on_main_thread(&self, runnable: Runnable) {
|
fn dispatch_on_main_thread(&self, runnable: Runnable) {
|
||||||
|
@ -149,6 +158,7 @@ impl PlatformDispatcher for TestDispatcher {
|
||||||
.entry(self.id)
|
.entry(self.id)
|
||||||
.or_default()
|
.or_default()
|
||||||
.push_back(runnable);
|
.push_back(runnable);
|
||||||
|
self.unparker.unpark();
|
||||||
}
|
}
|
||||||
|
|
||||||
fn dispatch_after(&self, duration: std::time::Duration, runnable: Runnable) {
|
fn dispatch_after(&self, duration: std::time::Duration, runnable: Runnable) {
|
||||||
|
@ -160,7 +170,7 @@ impl PlatformDispatcher for TestDispatcher {
|
||||||
state.delayed.insert(ix, (next_time, runnable));
|
state.delayed.insert(ix, (next_time, runnable));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn poll(&self) -> bool {
|
fn poll(&self, background_only: bool) -> bool {
|
||||||
let mut state = self.state.lock();
|
let mut state = self.state.lock();
|
||||||
|
|
||||||
while let Some((deadline, _)) = state.delayed.first() {
|
while let Some((deadline, _)) = state.delayed.first() {
|
||||||
|
@ -171,11 +181,15 @@ impl PlatformDispatcher for TestDispatcher {
|
||||||
state.background.push(runnable);
|
state.background.push(runnable);
|
||||||
}
|
}
|
||||||
|
|
||||||
let foreground_len: usize = state
|
let foreground_len: usize = if background_only {
|
||||||
.foreground
|
0
|
||||||
.values()
|
} else {
|
||||||
.map(|runnables| runnables.len())
|
state
|
||||||
.sum();
|
.foreground
|
||||||
|
.values()
|
||||||
|
.map(|runnables| runnables.len())
|
||||||
|
.sum()
|
||||||
|
};
|
||||||
let background_len = state.background.len();
|
let background_len = state.background.len();
|
||||||
|
|
||||||
if foreground_len == 0 && background_len == 0 {
|
if foreground_len == 0 && background_len == 0 {
|
||||||
|
@ -211,62 +225,15 @@ impl PlatformDispatcher for TestDispatcher {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn park(&self) {
|
||||||
|
self.parker.lock().park();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unparker(&self) -> Unparker {
|
||||||
|
self.unparker.clone()
|
||||||
|
}
|
||||||
|
|
||||||
fn as_test(&self) -> Option<&TestDispatcher> {
|
fn as_test(&self) -> Option<&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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
@ -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> {
|
||||||
|
|
|
@ -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 {
|
||||||
|
|
|
@ -1,13 +1,16 @@
|
||||||
use crate::{
|
use crate::{
|
||||||
private::Sealed, AnyBox, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace,
|
private::Sealed, AnyBox, AnyElement, AnyModel, AnyWeakModel, AppContext, AvailableSpace,
|
||||||
BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, LayoutId, Model, Pixels,
|
BorrowWindow, Bounds, Component, Element, ElementId, Entity, EntityId, Flatten, LayoutId,
|
||||||
Size, ViewContext, VisualContext, WeakModel, WindowContext,
|
Model, Pixels, Size, ViewContext, VisualContext, WeakModel, WindowContext,
|
||||||
};
|
};
|
||||||
use anyhow::{Context, Result};
|
use anyhow::{Context, Result};
|
||||||
use std::{any::TypeId, marker::PhantomData};
|
use std::{
|
||||||
|
any::{Any, TypeId},
|
||||||
|
hash::{Hash, Hasher},
|
||||||
|
};
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
|
@ -49,7 +52,7 @@ impl<V: 'static> View<V> {
|
||||||
pub fn update<C, R>(
|
pub fn update<C, R>(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut C,
|
cx: &mut C,
|
||||||
f: impl FnOnce(&mut V, &mut C::ViewContext<'_, '_, V>) -> R,
|
f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
|
||||||
) -> C::Result<R>
|
) -> C::Result<R>
|
||||||
where
|
where
|
||||||
C: VisualContext,
|
C: VisualContext,
|
||||||
|
@ -70,55 +73,23 @@ impl<V> Clone for View<V> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: Render, ParentViewState: 'static> Component<ParentViewState> for View<V> {
|
impl<V> Hash for View<V> {
|
||||||
fn render(self) -> AnyElement<ParentViewState> {
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
AnyElement::new(EraseViewState {
|
self.model.hash(state);
|
||||||
view: self,
|
|
||||||
parent_view_state_type: PhantomData,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V> Element<()> for View<V>
|
impl<V> PartialEq for View<V> {
|
||||||
where
|
fn eq(&self, other: &Self) -> bool {
|
||||||
V: Render,
|
self.model == other.model
|
||||||
{
|
|
||||||
type ElementState = AnyElement<V>;
|
|
||||||
|
|
||||||
fn id(&self) -> Option<crate::ElementId> {
|
|
||||||
Some(ElementId::View(self.model.entity_id))
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn initialize(
|
impl<V> Eq for View<V> {}
|
||||||
&mut self,
|
|
||||||
_: &mut (),
|
|
||||||
_: Option<Self::ElementState>,
|
|
||||||
cx: &mut ViewContext<()>,
|
|
||||||
) -> Self::ElementState {
|
|
||||||
self.update(cx, |state, cx| {
|
|
||||||
let mut any_element = AnyElement::new(state.render(cx));
|
|
||||||
any_element.initialize(state, cx);
|
|
||||||
any_element
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layout(
|
impl<V: Render, ParentViewState: 'static> Component<ParentViewState> for View<V> {
|
||||||
&mut self,
|
fn render(self) -> AnyElement<ParentViewState> {
|
||||||
_: &mut (),
|
AnyElement::new(AnyView::from(self))
|
||||||
element: &mut Self::ElementState,
|
|
||||||
cx: &mut ViewContext<()>,
|
|
||||||
) -> LayoutId {
|
|
||||||
self.update(cx, |state, cx| element.layout(state, cx))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint(
|
|
||||||
&mut self,
|
|
||||||
_: Bounds<Pixels>,
|
|
||||||
_: &mut (),
|
|
||||||
element: &mut Self::ElementState,
|
|
||||||
cx: &mut ViewContext<()>,
|
|
||||||
) {
|
|
||||||
self.update(cx, |state, cx| element.paint(state, cx))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -127,17 +98,25 @@ pub struct WeakView<V> {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: 'static> WeakView<V> {
|
impl<V: 'static> WeakView<V> {
|
||||||
|
pub fn entity_id(&self) -> EntityId {
|
||||||
|
self.model.entity_id
|
||||||
|
}
|
||||||
|
|
||||||
pub fn upgrade(&self) -> Option<View<V>> {
|
pub fn upgrade(&self) -> Option<View<V>> {
|
||||||
Entity::upgrade_from(self)
|
Entity::upgrade_from(self)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update<R>(
|
pub fn update<C, R>(
|
||||||
&self,
|
&self,
|
||||||
cx: &mut WindowContext,
|
cx: &mut C,
|
||||||
f: impl FnOnce(&mut V, &mut ViewContext<V>) -> R,
|
f: impl FnOnce(&mut V, &mut ViewContext<'_, V>) -> R,
|
||||||
) -> Result<R> {
|
) -> Result<R>
|
||||||
|
where
|
||||||
|
C: VisualContext,
|
||||||
|
Result<C::Result<R>>: Flatten<R>,
|
||||||
|
{
|
||||||
let view = self.upgrade().context("error upgrading view")?;
|
let view = self.upgrade().context("error upgrading view")?;
|
||||||
Ok(view.update(cx, f))
|
Ok(view.update(cx, f)).flatten()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -149,115 +128,19 @@ impl<V> Clone for WeakView<V> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
struct EraseViewState<V, ParentV> {
|
impl<V> Hash for WeakView<V> {
|
||||||
view: View<V>,
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
parent_view_state_type: PhantomData<ParentV>,
|
self.model.hash(state);
|
||||||
}
|
|
||||||
|
|
||||||
unsafe impl<V, ParentV> Send for EraseViewState<V, ParentV> {}
|
|
||||||
|
|
||||||
impl<V: Render, ParentV: 'static> Component<ParentV> for EraseViewState<V, ParentV> {
|
|
||||||
fn render(self) -> AnyElement<ParentV> {
|
|
||||||
AnyElement::new(self)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<V: Render, ParentV: 'static> Element<ParentV> for EraseViewState<V, ParentV> {
|
impl<V> PartialEq for WeakView<V> {
|
||||||
type ElementState = AnyBox;
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.model == other.model
|
||||||
fn id(&self) -> Option<crate::ElementId> {
|
|
||||||
Element::id(&self.view)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn initialize(
|
|
||||||
&mut self,
|
|
||||||
_: &mut ParentV,
|
|
||||||
_: Option<Self::ElementState>,
|
|
||||||
cx: &mut ViewContext<ParentV>,
|
|
||||||
) -> Self::ElementState {
|
|
||||||
ViewObject::initialize(&mut self.view, cx)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layout(
|
|
||||||
&mut self,
|
|
||||||
_: &mut ParentV,
|
|
||||||
element: &mut Self::ElementState,
|
|
||||||
cx: &mut ViewContext<ParentV>,
|
|
||||||
) -> LayoutId {
|
|
||||||
ViewObject::layout(&mut self.view, element, cx)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint(
|
|
||||||
&mut self,
|
|
||||||
bounds: Bounds<Pixels>,
|
|
||||||
_: &mut ParentV,
|
|
||||||
element: &mut Self::ElementState,
|
|
||||||
cx: &mut ViewContext<ParentV>,
|
|
||||||
) {
|
|
||||||
ViewObject::paint(&mut self.view, bounds, element, cx)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trait ViewObject: Send + Sync {
|
impl<V> Eq for WeakView<V> {}
|
||||||
fn entity_type(&self) -> TypeId;
|
|
||||||
fn entity_id(&self) -> EntityId;
|
|
||||||
fn model(&self) -> AnyModel;
|
|
||||||
fn initialize(&self, cx: &mut WindowContext) -> AnyBox;
|
|
||||||
fn layout(&self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId;
|
|
||||||
fn paint(&self, bounds: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext);
|
|
||||||
fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<V> ViewObject for View<V>
|
|
||||||
where
|
|
||||||
V: Render,
|
|
||||||
{
|
|
||||||
fn entity_type(&self) -> TypeId {
|
|
||||||
TypeId::of::<V>()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn entity_id(&self) -> EntityId {
|
|
||||||
Entity::entity_id(self)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn model(&self) -> AnyModel {
|
|
||||||
self.model.clone().into_any()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn initialize(&self, cx: &mut WindowContext) -> AnyBox {
|
|
||||||
cx.with_element_id(ViewObject::entity_id(self), |_global_id, cx| {
|
|
||||||
self.update(cx, |state, cx| {
|
|
||||||
let mut any_element = Box::new(AnyElement::new(state.render(cx)));
|
|
||||||
any_element.initialize(state, cx);
|
|
||||||
any_element
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layout(&self, element: &mut AnyBox, cx: &mut WindowContext) -> LayoutId {
|
|
||||||
cx.with_element_id(ViewObject::entity_id(self), |_global_id, cx| {
|
|
||||||
self.update(cx, |state, cx| {
|
|
||||||
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
|
|
||||||
element.layout(state, cx)
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint(&self, _: Bounds<Pixels>, element: &mut AnyBox, cx: &mut WindowContext) {
|
|
||||||
cx.with_element_id(ViewObject::entity_id(self), |_global_id, cx| {
|
|
||||||
self.update(cx, |state, cx| {
|
|
||||||
let element = element.downcast_mut::<AnyElement<V>>().unwrap();
|
|
||||||
element.paint(state, cx);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn debug(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
||||||
f.debug_struct(&format!("AnyView<{}>", std::any::type_name::<V>()))
|
|
||||||
.field("entity_id", &ViewObject::entity_id(self).as_u64())
|
|
||||||
.finish()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub struct AnyView {
|
pub struct AnyView {
|
||||||
|
@ -289,7 +172,7 @@ impl AnyView {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn entity_type(&self) -> TypeId {
|
pub fn entity_type(&self) -> TypeId {
|
||||||
self.model.entity_type
|
self.model.entity_type
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -343,7 +226,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())
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -30,7 +30,7 @@ pub fn derive_component(input: TokenStream) -> TokenStream {
|
||||||
let expanded = quote! {
|
let expanded = quote! {
|
||||||
impl #impl_generics gpui2::Component<#view_type> for #name #ty_generics #where_clause {
|
impl #impl_generics gpui2::Component<#view_type> for #name #ty_generics #where_clause {
|
||||||
fn render(self) -> gpui2::AnyElement<#view_type> {
|
fn render(self) -> gpui2::AnyElement<#view_type> {
|
||||||
(move |view_state: &mut #view_type, cx: &mut gpui2::ViewContext<'_, '_, #view_type>| self.render(view_state, cx))
|
(move |view_state: &mut #view_type, cx: &mut gpui2::ViewContext<'_, #view_type>| self.render(view_state, cx))
|
||||||
.render()
|
.render()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -89,9 +89,9 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
|
||||||
inner_fn_args.extend(quote!(rand::SeedableRng::seed_from_u64(_seed),));
|
inner_fn_args.extend(quote!(rand::SeedableRng::seed_from_u64(_seed),));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
Some("Executor") => {
|
Some("BackgroundExecutor") => {
|
||||||
inner_fn_args.extend(quote!(gpui2::Executor::new(
|
inner_fn_args.extend(quote!(gpui2::BackgroundExecutor::new(
|
||||||
std::sync::Arc::new(dispatcher.clone())
|
std::sync::Arc::new(dispatcher.clone()),
|
||||||
),));
|
),));
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
@ -134,9 +134,9 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
|
||||||
#num_iterations as u64,
|
#num_iterations as u64,
|
||||||
#max_retries,
|
#max_retries,
|
||||||
&mut |dispatcher, _seed| {
|
&mut |dispatcher, _seed| {
|
||||||
let executor = gpui2::Executor::new(std::sync::Arc::new(dispatcher.clone()));
|
let executor = gpui2::BackgroundExecutor::new(std::sync::Arc::new(dispatcher.clone()));
|
||||||
#cx_vars
|
#cx_vars
|
||||||
executor.block(#inner_fn_name(#inner_fn_args));
|
executor.block_test(#inner_fn_name(#inner_fn_args));
|
||||||
#cx_teardowns
|
#cx_teardowns
|
||||||
},
|
},
|
||||||
#on_failure_fn_name,
|
#on_failure_fn_name,
|
||||||
|
@ -170,7 +170,7 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream {
|
||||||
let mut #cx_varname = gpui2::TestAppContext::new(
|
let mut #cx_varname = gpui2::TestAppContext::new(
|
||||||
dispatcher.clone()
|
dispatcher.clone()
|
||||||
);
|
);
|
||||||
let mut #cx_varname_lock = #cx_varname.app.lock();
|
let mut #cx_varname_lock = #cx_varname.app.borrow_mut();
|
||||||
));
|
));
|
||||||
inner_fn_args.extend(quote!(&mut #cx_varname_lock,));
|
inner_fn_args.extend(quote!(&mut #cx_varname_lock,));
|
||||||
cx_teardowns.extend(quote!(
|
cx_teardowns.extend(quote!(
|
||||||
|
|
|
@ -7,9 +7,7 @@ use util::ResultExt;
|
||||||
// actions!(cli, [Install]);
|
// actions!(cli, [Install]);
|
||||||
|
|
||||||
pub async fn install_cli(cx: &AsyncAppContext) -> Result<()> {
|
pub async fn install_cli(cx: &AsyncAppContext) -> Result<()> {
|
||||||
let cli_path = cx
|
let cli_path = cx.update(|cx| cx.path_for_auxiliary_executable("cli"))??;
|
||||||
.run_on_main(|cx| cx.path_for_auxiliary_executable("cli"))?
|
|
||||||
.await?;
|
|
||||||
let link_path = Path::new("/usr/local/bin/zed");
|
let link_path = Path::new("/usr/local/bin/zed");
|
||||||
let bin_dir_path = link_path.parent().unwrap();
|
let bin_dir_path = link_path.parent().unwrap();
|
||||||
|
|
||||||
|
|
|
@ -77,7 +77,7 @@ pub fn new_journal_entry(_: Arc<AppState>, cx: &mut AppContext) {
|
||||||
let now = now.time();
|
let now = now.time();
|
||||||
let _entry_heading = heading_entry(now, &settings.hour_format);
|
let _entry_heading = heading_entry(now, &settings.hour_format);
|
||||||
|
|
||||||
let _create_entry = cx.executor().spawn(async move {
|
let _create_entry = cx.background_executor().spawn(async move {
|
||||||
std::fs::create_dir_all(month_dir)?;
|
std::fs::create_dir_all(month_dir)?;
|
||||||
OpenOptions::new()
|
OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
|
|
|
@ -434,7 +434,7 @@ impl Buffer {
|
||||||
));
|
));
|
||||||
|
|
||||||
let text_operations = self.text.operations().clone();
|
let text_operations = self.text.operations().clone();
|
||||||
cx.spawn(|_| async move {
|
cx.background_executor().spawn(async move {
|
||||||
let since = since.unwrap_or_default();
|
let since = since.unwrap_or_default();
|
||||||
operations.extend(
|
operations.extend(
|
||||||
text_operations
|
text_operations
|
||||||
|
@ -652,7 +652,7 @@ impl Buffer {
|
||||||
|
|
||||||
if !self.is_dirty() {
|
if !self.is_dirty() {
|
||||||
let reload = self.reload(cx).log_err().map(drop);
|
let reload = self.reload(cx).log_err().map(drop);
|
||||||
task = cx.executor().spawn(reload);
|
task = cx.background_executor().spawn(reload);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -684,7 +684,7 @@ impl Buffer {
|
||||||
let snapshot = self.snapshot();
|
let snapshot = self.snapshot();
|
||||||
|
|
||||||
let mut diff = self.git_diff.clone();
|
let mut diff = self.git_diff.clone();
|
||||||
let diff = cx.executor().spawn(async move {
|
let diff = cx.background_executor().spawn(async move {
|
||||||
diff.update(&diff_base, &snapshot).await;
|
diff.update(&diff_base, &snapshot).await;
|
||||||
diff
|
diff
|
||||||
});
|
});
|
||||||
|
@ -793,7 +793,7 @@ impl Buffer {
|
||||||
let mut syntax_snapshot = syntax_map.snapshot();
|
let mut syntax_snapshot = syntax_map.snapshot();
|
||||||
drop(syntax_map);
|
drop(syntax_map);
|
||||||
|
|
||||||
let parse_task = cx.executor().spawn({
|
let parse_task = cx.background_executor().spawn({
|
||||||
let language = language.clone();
|
let language = language.clone();
|
||||||
let language_registry = language_registry.clone();
|
let language_registry = language_registry.clone();
|
||||||
async move {
|
async move {
|
||||||
|
@ -803,7 +803,7 @@ impl Buffer {
|
||||||
});
|
});
|
||||||
|
|
||||||
match cx
|
match cx
|
||||||
.executor()
|
.background_executor()
|
||||||
.block_with_timeout(self.sync_parse_timeout, parse_task)
|
.block_with_timeout(self.sync_parse_timeout, parse_task)
|
||||||
{
|
{
|
||||||
Ok(new_syntax_snapshot) => {
|
Ok(new_syntax_snapshot) => {
|
||||||
|
@ -866,9 +866,9 @@ impl Buffer {
|
||||||
|
|
||||||
fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
|
fn request_autoindent(&mut self, cx: &mut ModelContext<Self>) {
|
||||||
if let Some(indent_sizes) = self.compute_autoindents() {
|
if let Some(indent_sizes) = self.compute_autoindents() {
|
||||||
let indent_sizes = cx.executor().spawn(indent_sizes);
|
let indent_sizes = cx.background_executor().spawn(indent_sizes);
|
||||||
match cx
|
match cx
|
||||||
.executor()
|
.background_executor()
|
||||||
.block_with_timeout(Duration::from_micros(500), indent_sizes)
|
.block_with_timeout(Duration::from_micros(500), indent_sizes)
|
||||||
{
|
{
|
||||||
Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
|
Ok(indent_sizes) => self.apply_autoindents(indent_sizes, cx),
|
||||||
|
@ -1117,7 +1117,7 @@ impl Buffer {
|
||||||
pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
|
pub fn diff(&self, mut new_text: String, cx: &AppContext) -> Task<Diff> {
|
||||||
let old_text = self.as_rope().clone();
|
let old_text = self.as_rope().clone();
|
||||||
let base_version = self.version();
|
let base_version = self.version();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
let old_text = old_text.to_string();
|
let old_text = old_text.to_string();
|
||||||
let line_ending = LineEnding::detect(&new_text);
|
let line_ending = LineEnding::detect(&new_text);
|
||||||
LineEnding::normalize(&mut new_text);
|
LineEnding::normalize(&mut new_text);
|
||||||
|
@ -1155,7 +1155,7 @@ impl Buffer {
|
||||||
let old_text = self.as_rope().clone();
|
let old_text = self.as_rope().clone();
|
||||||
let line_ending = self.line_ending();
|
let line_ending = self.line_ending();
|
||||||
let base_version = self.version();
|
let base_version = self.version();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
let ranges = trailing_whitespace_ranges(&old_text);
|
let ranges = trailing_whitespace_ranges(&old_text);
|
||||||
let empty = Arc::<str>::from("");
|
let empty = Arc::<str>::from("");
|
||||||
Diff {
|
Diff {
|
||||||
|
|
|
@ -559,7 +559,7 @@ async fn test_outline(cx: &mut gpui2::TestAppContext) {
|
||||||
cx: &'a gpui2::TestAppContext,
|
cx: &'a gpui2::TestAppContext,
|
||||||
) -> Vec<(&'a str, Vec<usize>)> {
|
) -> Vec<(&'a str, Vec<usize>)> {
|
||||||
let matches = cx
|
let matches = cx
|
||||||
.update(|cx| outline.search(query, cx.executor().clone()))
|
.update(|cx| outline.search(query, cx.background_executor().clone()))
|
||||||
.await;
|
.await;
|
||||||
matches
|
matches
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
@ -1879,7 +1879,7 @@ fn test_serialization(cx: &mut gpui2::AppContext) {
|
||||||
|
|
||||||
let state = buffer1.read(cx).to_proto();
|
let state = buffer1.read(cx).to_proto();
|
||||||
let ops = cx
|
let ops = cx
|
||||||
.executor()
|
.background_executor()
|
||||||
.block(buffer1.read(cx).serialize_ops(None, cx));
|
.block(buffer1.read(cx).serialize_ops(None, cx));
|
||||||
let buffer2 = cx.build_model(|cx| {
|
let buffer2 = cx.build_model(|cx| {
|
||||||
let mut buffer = Buffer::from_proto(1, state, None).unwrap();
|
let mut buffer = Buffer::from_proto(1, state, None).unwrap();
|
||||||
|
@ -1921,7 +1921,7 @@ fn test_random_collaboration(cx: &mut AppContext, mut rng: StdRng) {
|
||||||
let buffer = cx.build_model(|cx| {
|
let buffer = cx.build_model(|cx| {
|
||||||
let state = base_buffer.read(cx).to_proto();
|
let state = base_buffer.read(cx).to_proto();
|
||||||
let ops = cx
|
let ops = cx
|
||||||
.executor()
|
.background_executor()
|
||||||
.block(base_buffer.read(cx).serialize_ops(None, cx));
|
.block(base_buffer.read(cx).serialize_ops(None, cx));
|
||||||
let mut buffer = Buffer::from_proto(i as ReplicaId, state, None).unwrap();
|
let mut buffer = Buffer::from_proto(i as ReplicaId, state, None).unwrap();
|
||||||
buffer
|
buffer
|
||||||
|
@ -1943,6 +1943,7 @@ fn test_random_collaboration(cx: &mut AppContext, mut rng: StdRng) {
|
||||||
.detach();
|
.detach();
|
||||||
buffer
|
buffer
|
||||||
});
|
});
|
||||||
|
|
||||||
buffers.push(buffer);
|
buffers.push(buffer);
|
||||||
replica_ids.push(i as ReplicaId);
|
replica_ids.push(i as ReplicaId);
|
||||||
network.lock().add_peer(i as ReplicaId);
|
network.lock().add_peer(i as ReplicaId);
|
||||||
|
@ -2025,7 +2026,9 @@ fn test_random_collaboration(cx: &mut AppContext, mut rng: StdRng) {
|
||||||
}
|
}
|
||||||
50..=59 if replica_ids.len() < max_peers => {
|
50..=59 if replica_ids.len() < max_peers => {
|
||||||
let old_buffer_state = buffer.read(cx).to_proto();
|
let old_buffer_state = buffer.read(cx).to_proto();
|
||||||
let old_buffer_ops = cx.executor().block(buffer.read(cx).serialize_ops(None, cx));
|
let old_buffer_ops = cx
|
||||||
|
.background_executor()
|
||||||
|
.block(buffer.read(cx).serialize_ops(None, cx));
|
||||||
let new_replica_id = (0..=replica_ids.len() as ReplicaId)
|
let new_replica_id = (0..=replica_ids.len() as ReplicaId)
|
||||||
.filter(|replica_id| *replica_id != buffer.read(cx).replica_id())
|
.filter(|replica_id| *replica_id != buffer.read(cx).replica_id())
|
||||||
.choose(&mut rng)
|
.choose(&mut rng)
|
||||||
|
|
|
@ -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>()
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
use fuzzy2::{StringMatch, StringMatchCandidate};
|
use fuzzy2::{StringMatch, StringMatchCandidate};
|
||||||
use gpui2::{Executor, HighlightStyle};
|
use gpui2::{BackgroundExecutor, HighlightStyle};
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
@ -57,7 +57,7 @@ impl<T> Outline<T> {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn search(&self, query: &str, executor: Executor) -> Vec<StringMatch> {
|
pub async fn search(&self, query: &str, executor: BackgroundExecutor) -> Vec<StringMatch> {
|
||||||
let query = query.trim_start();
|
let query = query.trim_start();
|
||||||
let is_path_query = query.contains(' ');
|
let is_path_query = query.contains(' ');
|
||||||
let smart_case = query.chars().any(|c| c.is_uppercase());
|
let smart_case = query.chars().any(|c| c.is_uppercase());
|
||||||
|
|
|
@ -42,7 +42,7 @@ fn main() {
|
||||||
let live_kit_key = std::env::var("LIVE_KIT_KEY").unwrap_or("devkey".into());
|
let live_kit_key = std::env::var("LIVE_KIT_KEY").unwrap_or("devkey".into());
|
||||||
let live_kit_secret = std::env::var("LIVE_KIT_SECRET").unwrap_or("secret".into());
|
let live_kit_secret = std::env::var("LIVE_KIT_SECRET").unwrap_or("secret".into());
|
||||||
|
|
||||||
cx.spawn_on_main(|cx| async move {
|
cx.spawn(|cx| async move {
|
||||||
let user_a_token = token::create(
|
let user_a_token = token::create(
|
||||||
&live_kit_key,
|
&live_kit_key,
|
||||||
&live_kit_secret,
|
&live_kit_secret,
|
||||||
|
@ -104,7 +104,7 @@ fn main() {
|
||||||
}
|
}
|
||||||
|
|
||||||
println!("Pausing for 5 seconds to test audio, make some noise!");
|
println!("Pausing for 5 seconds to test audio, make some noise!");
|
||||||
let timer = cx.executor().timer(Duration::from_secs(5));
|
let timer = cx.background_executor().timer(Duration::from_secs(5));
|
||||||
timer.await;
|
timer.await;
|
||||||
let remote_audio_track = room_b
|
let remote_audio_track = room_b
|
||||||
.remote_audio_tracks("test-participant-1")
|
.remote_audio_tracks("test-participant-1")
|
||||||
|
|
|
@ -2,7 +2,7 @@ use anyhow::{anyhow, Context, Result};
|
||||||
use async_trait::async_trait;
|
use async_trait::async_trait;
|
||||||
use collections::{BTreeMap, HashMap};
|
use collections::{BTreeMap, HashMap};
|
||||||
use futures::Stream;
|
use futures::Stream;
|
||||||
use gpui2::Executor;
|
use gpui2::BackgroundExecutor;
|
||||||
use live_kit_server::token;
|
use live_kit_server::token;
|
||||||
use media::core_video::CVImageBuffer;
|
use media::core_video::CVImageBuffer;
|
||||||
use parking_lot::Mutex;
|
use parking_lot::Mutex;
|
||||||
|
@ -16,7 +16,7 @@ pub struct TestServer {
|
||||||
pub api_key: String,
|
pub api_key: String,
|
||||||
pub secret_key: String,
|
pub secret_key: String,
|
||||||
rooms: Mutex<HashMap<String, TestServerRoom>>,
|
rooms: Mutex<HashMap<String, TestServerRoom>>,
|
||||||
executor: Arc<Executor>,
|
executor: Arc<BackgroundExecutor>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TestServer {
|
impl TestServer {
|
||||||
|
@ -24,7 +24,7 @@ impl TestServer {
|
||||||
url: String,
|
url: String,
|
||||||
api_key: String,
|
api_key: String,
|
||||||
secret_key: String,
|
secret_key: String,
|
||||||
executor: Arc<Executor>,
|
executor: Arc<BackgroundExecutor>,
|
||||||
) -> Result<Arc<TestServer>> {
|
) -> Result<Arc<TestServer>> {
|
||||||
let mut servers = SERVERS.lock();
|
let mut servers = SERVERS.lock();
|
||||||
if servers.contains_key(&url) {
|
if servers.contains_key(&url) {
|
||||||
|
|
|
@ -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(),
|
||||||
|
@ -595,8 +595,8 @@ impl LanguageServer {
|
||||||
where
|
where
|
||||||
T: request::Request,
|
T: request::Request,
|
||||||
T::Params: 'static + Send,
|
T::Params: 'static + Send,
|
||||||
F: 'static + Send + FnMut(T::Params, AsyncAppContext) -> Fut,
|
F: 'static + FnMut(T::Params, AsyncAppContext) -> Fut + Send,
|
||||||
Fut: 'static + Future<Output = Result<T::Result>> + Send,
|
Fut: 'static + Future<Output = Result<T::Result>>,
|
||||||
{
|
{
|
||||||
self.on_custom_request(T::METHOD, f)
|
self.on_custom_request(T::METHOD, f)
|
||||||
}
|
}
|
||||||
|
@ -629,7 +629,7 @@ impl LanguageServer {
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
|
pub fn on_custom_notification<Params, F>(&self, method: &'static str, mut f: F) -> Subscription
|
||||||
where
|
where
|
||||||
F: 'static + Send + FnMut(Params, AsyncAppContext),
|
F: 'static + FnMut(Params, AsyncAppContext) + Send,
|
||||||
Params: DeserializeOwned,
|
Params: DeserializeOwned,
|
||||||
{
|
{
|
||||||
let prev_handler = self.notification_handlers.lock().insert(
|
let prev_handler = self.notification_handlers.lock().insert(
|
||||||
|
@ -657,8 +657,8 @@ impl LanguageServer {
|
||||||
mut f: F,
|
mut f: F,
|
||||||
) -> Subscription
|
) -> Subscription
|
||||||
where
|
where
|
||||||
F: 'static + Send + FnMut(Params, AsyncAppContext) -> Fut,
|
F: 'static + FnMut(Params, AsyncAppContext) -> Fut + Send,
|
||||||
Fut: 'static + Future<Output = Result<Res>> + Send,
|
Fut: 'static + Future<Output = Result<Res>>,
|
||||||
Params: DeserializeOwned + Send + 'static,
|
Params: DeserializeOwned + Send + 'static,
|
||||||
Res: Serialize,
|
Res: Serialize,
|
||||||
{
|
{
|
||||||
|
@ -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
|
||||||
|
@ -1047,8 +1047,9 @@ impl FakeLanguageServer {
|
||||||
.on_request::<T, _, _>(move |params, cx| {
|
.on_request::<T, _, _>(move |params, cx| {
|
||||||
let result = handler(params, cx.clone());
|
let result = handler(params, cx.clone());
|
||||||
let responded_tx = responded_tx.clone();
|
let responded_tx = responded_tx.clone();
|
||||||
|
let executor = cx.background_executor().clone();
|
||||||
async move {
|
async move {
|
||||||
cx.executor().simulate_random_delay().await;
|
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
|
||||||
|
|
|
@ -878,7 +878,7 @@ impl MultiBuffer {
|
||||||
cx.spawn(move |this, mut cx| async move {
|
cx.spawn(move |this, mut cx| async move {
|
||||||
let mut excerpt_ranges = Vec::new();
|
let mut excerpt_ranges = Vec::new();
|
||||||
let mut range_counts = Vec::new();
|
let mut range_counts = Vec::new();
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.scoped(|scope| {
|
.scoped(|scope| {
|
||||||
scope.spawn(async {
|
scope.spawn(async {
|
||||||
let (ranges, counts) =
|
let (ranges, counts) =
|
||||||
|
@ -4177,7 +4177,7 @@ mod tests {
|
||||||
let guest_buffer = cx.build_model(|cx| {
|
let guest_buffer = cx.build_model(|cx| {
|
||||||
let state = host_buffer.read(cx).to_proto();
|
let state = host_buffer.read(cx).to_proto();
|
||||||
let ops = cx
|
let ops = cx
|
||||||
.executor()
|
.background_executor()
|
||||||
.block(host_buffer.read(cx).serialize_ops(None, cx));
|
.block(host_buffer.read(cx).serialize_ops(None, cx));
|
||||||
let mut buffer = Buffer::from_proto(1, state, None).unwrap();
|
let mut buffer = Buffer::from_proto(1, state, None).unwrap();
|
||||||
buffer
|
buffer
|
||||||
|
|
|
@ -143,7 +143,7 @@ impl Prettier {
|
||||||
) -> anyhow::Result<Self> {
|
) -> anyhow::Result<Self> {
|
||||||
use lsp2::LanguageServerBinary;
|
use lsp2::LanguageServerBinary;
|
||||||
|
|
||||||
let executor = cx.executor().clone();
|
let executor = cx.background_executor().clone();
|
||||||
anyhow::ensure!(
|
anyhow::ensure!(
|
||||||
prettier_dir.is_dir(),
|
prettier_dir.is_dir(),
|
||||||
"Prettier dir {prettier_dir:?} is not a directory"
|
"Prettier dir {prettier_dir:?} is not a directory"
|
||||||
|
|
|
@ -32,7 +32,7 @@ pub fn lsp_formatting_options(tab_size: u32) -> lsp2::FormattingOptions {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
pub(crate) trait LspCommand: 'static + Sized + Send {
|
pub(crate) trait LspCommand: 'static + Sized + Send {
|
||||||
type Response: 'static + Default + Send;
|
type Response: 'static + Default + Send;
|
||||||
type LspRequest: 'static + Send + lsp2::request::Request;
|
type LspRequest: 'static + Send + lsp2::request::Request;
|
||||||
|
@ -148,7 +148,7 @@ impl From<lsp2::FormattingOptions> for FormattingOptions {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for PrepareRename {
|
impl LspCommand for PrepareRename {
|
||||||
type Response = Option<Range<Anchor>>;
|
type Response = Option<Range<Anchor>>;
|
||||||
type LspRequest = lsp2::request::PrepareRenameRequest;
|
type LspRequest = lsp2::request::PrepareRenameRequest;
|
||||||
|
@ -279,7 +279,7 @@ impl LspCommand for PrepareRename {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for PerformRename {
|
impl LspCommand for PerformRename {
|
||||||
type Response = ProjectTransaction;
|
type Response = ProjectTransaction;
|
||||||
type LspRequest = lsp2::request::Rename;
|
type LspRequest = lsp2::request::Rename;
|
||||||
|
@ -398,7 +398,7 @@ impl LspCommand for PerformRename {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetDefinition {
|
impl LspCommand for GetDefinition {
|
||||||
type Response = Vec<LocationLink>;
|
type Response = Vec<LocationLink>;
|
||||||
type LspRequest = lsp2::request::GotoDefinition;
|
type LspRequest = lsp2::request::GotoDefinition;
|
||||||
|
@ -491,7 +491,7 @@ impl LspCommand for GetDefinition {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetTypeDefinition {
|
impl LspCommand for GetTypeDefinition {
|
||||||
type Response = Vec<LocationLink>;
|
type Response = Vec<LocationLink>;
|
||||||
type LspRequest = lsp2::request::GotoTypeDefinition;
|
type LspRequest = lsp2::request::GotoTypeDefinition;
|
||||||
|
@ -783,7 +783,7 @@ fn location_links_to_proto(
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetReferences {
|
impl LspCommand for GetReferences {
|
||||||
type Response = Vec<Location>;
|
type Response = Vec<Location>;
|
||||||
type LspRequest = lsp2::request::References;
|
type LspRequest = lsp2::request::References;
|
||||||
|
@ -945,7 +945,7 @@ impl LspCommand for GetReferences {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetDocumentHighlights {
|
impl LspCommand for GetDocumentHighlights {
|
||||||
type Response = Vec<DocumentHighlight>;
|
type Response = Vec<DocumentHighlight>;
|
||||||
type LspRequest = lsp2::request::DocumentHighlightRequest;
|
type LspRequest = lsp2::request::DocumentHighlightRequest;
|
||||||
|
@ -1096,7 +1096,7 @@ impl LspCommand for GetDocumentHighlights {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetHover {
|
impl LspCommand for GetHover {
|
||||||
type Response = Option<Hover>;
|
type Response = Option<Hover>;
|
||||||
type LspRequest = lsp2::request::HoverRequest;
|
type LspRequest = lsp2::request::HoverRequest;
|
||||||
|
@ -1314,7 +1314,7 @@ impl LspCommand for GetHover {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetCompletions {
|
impl LspCommand for GetCompletions {
|
||||||
type Response = Vec<Completion>;
|
type Response = Vec<Completion>;
|
||||||
type LspRequest = lsp2::request::Completion;
|
type LspRequest = lsp2::request::Completion;
|
||||||
|
@ -1545,7 +1545,7 @@ impl LspCommand for GetCompletions {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for GetCodeActions {
|
impl LspCommand for GetCodeActions {
|
||||||
type Response = Vec<CodeAction>;
|
type Response = Vec<CodeAction>;
|
||||||
type LspRequest = lsp2::request::CodeActionRequest;
|
type LspRequest = lsp2::request::CodeActionRequest;
|
||||||
|
@ -1684,7 +1684,7 @@ impl LspCommand for GetCodeActions {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for OnTypeFormatting {
|
impl LspCommand for OnTypeFormatting {
|
||||||
type Response = Option<Transaction>;
|
type Response = Option<Transaction>;
|
||||||
type LspRequest = lsp2::request::OnTypeFormatting;
|
type LspRequest = lsp2::request::OnTypeFormatting;
|
||||||
|
@ -2192,7 +2192,7 @@ impl InlayHints {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait]
|
#[async_trait(?Send)]
|
||||||
impl LspCommand for InlayHints {
|
impl LspCommand for InlayHints {
|
||||||
type Response = Vec<InlayHint>;
|
type Response = Vec<InlayHint>;
|
||||||
type LspRequest = lsp2::InlayHintRequest;
|
type LspRequest = lsp2::InlayHintRequest;
|
||||||
|
|
|
@ -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() {
|
||||||
|
@ -1758,7 +1758,7 @@ impl Project {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
wait_for_loading_buffer(loading_watch)
|
wait_for_loading_buffer(loading_watch)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| anyhow!("{}", error))
|
.map_err(|error| anyhow!("{}", error))
|
||||||
|
@ -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 {
|
||||||
|
@ -5593,7 +5593,7 @@ impl Project {
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
let background = cx.executor().clone();
|
let background = cx.background_executor().clone();
|
||||||
let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
|
let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
|
||||||
if path_count == 0 {
|
if path_count == 0 {
|
||||||
let (_, rx) = smol::channel::bounded(1024);
|
let (_, rx) = smol::channel::bounded(1024);
|
||||||
|
@ -5616,11 +5616,11 @@ impl Project {
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(Self::background_search(
|
.spawn(Self::background_search(
|
||||||
unnamed_files,
|
unnamed_files,
|
||||||
opened_buffers,
|
opened_buffers,
|
||||||
cx.executor().clone(),
|
cx.background_executor().clone(),
|
||||||
self.fs.clone(),
|
self.fs.clone(),
|
||||||
workers,
|
workers,
|
||||||
query.clone(),
|
query.clone(),
|
||||||
|
@ -5631,9 +5631,9 @@ impl Project {
|
||||||
.detach();
|
.detach();
|
||||||
|
|
||||||
let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
|
let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
|
||||||
let background = cx.executor().clone();
|
let background = cx.background_executor().clone();
|
||||||
let (result_tx, result_rx) = smol::channel::bounded(1024);
|
let (result_tx, result_rx) = smol::channel::bounded(1024);
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(async move {
|
.spawn(async move {
|
||||||
let Ok(buffers) = buffers.await else {
|
let Ok(buffers) = buffers.await else {
|
||||||
return;
|
return;
|
||||||
|
@ -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,
|
||||||
|
@ -5993,7 +5993,7 @@ impl Project {
|
||||||
Task::ready(Ok((tree, relative_path)))
|
Task::ready(Ok((tree, relative_path)))
|
||||||
} else {
|
} else {
|
||||||
let worktree = self.create_local_worktree(abs_path, visible, cx);
|
let worktree = self.create_local_worktree(abs_path, visible, cx);
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(async move { Ok((worktree.await?, PathBuf::new())) })
|
.spawn(async move { Ok((worktree.await?, PathBuf::new())) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -6064,7 +6064,7 @@ impl Project {
|
||||||
.shared()
|
.shared()
|
||||||
})
|
})
|
||||||
.clone();
|
.clone();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
match task.await {
|
match task.await {
|
||||||
Ok(worktree) => Ok(worktree),
|
Ok(worktree) => Ok(worktree),
|
||||||
Err(err) => Err(anyhow!("{}", err)),
|
Err(err) => Err(anyhow!("{}", err)),
|
||||||
|
@ -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()
|
||||||
|
@ -6519,7 +6519,7 @@ impl Project {
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
|
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(async move {
|
.spawn(async move {
|
||||||
for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| {
|
for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| {
|
||||||
async move {
|
async move {
|
||||||
|
@ -7358,7 +7358,7 @@ impl Project {
|
||||||
})
|
})
|
||||||
.log_err();
|
.log_err();
|
||||||
|
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(
|
.spawn(
|
||||||
async move {
|
async move {
|
||||||
let operations = operations.await;
|
let operations = operations.await;
|
||||||
|
@ -7960,7 +7960,7 @@ impl Project {
|
||||||
if let Some(buffer) = this.buffer_for_id(buffer_id) {
|
if let Some(buffer) = this.buffer_for_id(buffer_id) {
|
||||||
let operations =
|
let operations =
|
||||||
buffer.read(cx).serialize_ops(Some(remote_version), cx);
|
buffer.read(cx).serialize_ops(Some(remote_version), cx);
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
let operations = operations.await;
|
let operations = operations.await;
|
||||||
for chunk in split_operations(operations) {
|
for chunk in split_operations(operations) {
|
||||||
client
|
client
|
||||||
|
@ -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();
|
||||||
}
|
}
|
||||||
|
@ -8198,7 +8198,7 @@ impl Project {
|
||||||
cx: &mut ModelContext<Self>,
|
cx: &mut ModelContext<Self>,
|
||||||
) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
|
) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
|
||||||
let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
|
let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
let snapshot = snapshot?;
|
let snapshot = snapshot?;
|
||||||
let mut lsp_edits = lsp_edits
|
let mut lsp_edits = lsp_edits
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
@ -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 {
|
||||||
|
@ -8649,7 +8649,7 @@ impl Project {
|
||||||
.get(&(worktree, default_prettier_dir.to_path_buf()))
|
.get(&(worktree, default_prettier_dir.to_path_buf()))
|
||||||
.cloned();
|
.cloned();
|
||||||
let fs = Arc::clone(&self.fs);
|
let fs = Arc::clone(&self.fs);
|
||||||
cx.spawn_on_main(move |this, mut cx| async move {
|
cx.spawn(move |this, mut cx| async move {
|
||||||
if let Some(previous_installation_process) = previous_installation_process {
|
if let Some(previous_installation_process) = previous_installation_process {
|
||||||
previous_installation_process.await;
|
previous_installation_process.await;
|
||||||
}
|
}
|
||||||
|
|
File diff suppressed because it is too large
Load diff
|
@ -17,12 +17,13 @@ use futures::{
|
||||||
},
|
},
|
||||||
select_biased,
|
select_biased,
|
||||||
task::Poll,
|
task::Poll,
|
||||||
FutureExt, Stream, StreamExt,
|
FutureExt as _, Stream, StreamExt,
|
||||||
};
|
};
|
||||||
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::{
|
||||||
|
@ -296,6 +297,7 @@ impl Worktree {
|
||||||
// After determining whether the root entry is a file or a directory, populate the
|
// After determining whether the root entry is a file or a directory, populate the
|
||||||
// snapshot's "root name", which will be used for the purpose of fuzzy matching.
|
// snapshot's "root name", which will be used for the purpose of fuzzy matching.
|
||||||
let abs_path = path.into();
|
let abs_path = path.into();
|
||||||
|
|
||||||
let metadata = fs
|
let metadata = fs
|
||||||
.metadata(&abs_path)
|
.metadata(&abs_path)
|
||||||
.await
|
.await
|
||||||
|
@ -364,10 +366,10 @@ impl Worktree {
|
||||||
})
|
})
|
||||||
.detach();
|
.detach();
|
||||||
|
|
||||||
let background_scanner_task = cx.executor().spawn({
|
let background_scanner_task = cx.background_executor().spawn({
|
||||||
let fs = fs.clone();
|
let fs = fs.clone();
|
||||||
let snapshot = snapshot.clone();
|
let snapshot = snapshot.clone();
|
||||||
let background = cx.executor().clone();
|
let background = cx.background_executor().clone();
|
||||||
async move {
|
async move {
|
||||||
let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
|
let events = fs.watch(&abs_path, Duration::from_millis(100)).await;
|
||||||
BackgroundScanner::new(
|
BackgroundScanner::new(
|
||||||
|
@ -428,7 +430,7 @@ impl Worktree {
|
||||||
let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
|
let background_snapshot = Arc::new(Mutex::new(snapshot.clone()));
|
||||||
let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
|
let (mut snapshot_updated_tx, mut snapshot_updated_rx) = watch::channel();
|
||||||
|
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn({
|
.spawn({
|
||||||
let background_snapshot = background_snapshot.clone();
|
let background_snapshot = background_snapshot.clone();
|
||||||
async move {
|
async move {
|
||||||
|
@ -600,7 +602,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 +890,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) }),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
@ -1007,7 +1009,7 @@ impl LocalWorktree {
|
||||||
let lowest_ancestor = self.lowest_ancestor(&path);
|
let lowest_ancestor = self.lowest_ancestor(&path);
|
||||||
let abs_path = self.absolutize(&path);
|
let abs_path = self.absolutize(&path);
|
||||||
let fs = self.fs.clone();
|
let fs = self.fs.clone();
|
||||||
let write = cx.executor().spawn(async move {
|
let write = cx.background_executor().spawn(async move {
|
||||||
if is_dir {
|
if is_dir {
|
||||||
fs.create_dir(&abs_path).await
|
fs.create_dir(&abs_path).await
|
||||||
} else {
|
} else {
|
||||||
|
@ -1057,7 +1059,7 @@ impl LocalWorktree {
|
||||||
let abs_path = self.absolutize(&path);
|
let abs_path = self.absolutize(&path);
|
||||||
let fs = self.fs.clone();
|
let fs = self.fs.clone();
|
||||||
let write = cx
|
let write = cx
|
||||||
.executor()
|
.background_executor()
|
||||||
.spawn(async move { fs.save(&abs_path, &text, line_ending).await });
|
.spawn(async move { fs.save(&abs_path, &text, line_ending).await });
|
||||||
|
|
||||||
cx.spawn(|this, mut cx| async move {
|
cx.spawn(|this, mut cx| async move {
|
||||||
|
@ -1078,7 +1080,7 @@ impl LocalWorktree {
|
||||||
let abs_path = self.absolutize(&entry.path);
|
let abs_path = self.absolutize(&entry.path);
|
||||||
let fs = self.fs.clone();
|
let fs = self.fs.clone();
|
||||||
|
|
||||||
let delete = cx.executor().spawn(async move {
|
let delete = cx.background_executor().spawn(async move {
|
||||||
if entry.is_file() {
|
if entry.is_file() {
|
||||||
fs.remove_file(&abs_path, Default::default()).await?;
|
fs.remove_file(&abs_path, Default::default()).await?;
|
||||||
} else {
|
} else {
|
||||||
|
@ -1118,7 +1120,7 @@ impl LocalWorktree {
|
||||||
let abs_old_path = self.absolutize(&old_path);
|
let abs_old_path = self.absolutize(&old_path);
|
||||||
let abs_new_path = self.absolutize(&new_path);
|
let abs_new_path = self.absolutize(&new_path);
|
||||||
let fs = self.fs.clone();
|
let fs = self.fs.clone();
|
||||||
let rename = cx.executor().spawn(async move {
|
let rename = cx.background_executor().spawn(async move {
|
||||||
fs.rename(&abs_old_path, &abs_new_path, Default::default())
|
fs.rename(&abs_old_path, &abs_new_path, Default::default())
|
||||||
.await
|
.await
|
||||||
});
|
});
|
||||||
|
@ -1145,7 +1147,7 @@ impl LocalWorktree {
|
||||||
let abs_old_path = self.absolutize(&old_path);
|
let abs_old_path = self.absolutize(&old_path);
|
||||||
let abs_new_path = self.absolutize(&new_path);
|
let abs_new_path = self.absolutize(&new_path);
|
||||||
let fs = self.fs.clone();
|
let fs = self.fs.clone();
|
||||||
let copy = cx.executor().spawn(async move {
|
let copy = cx.background_executor().spawn(async move {
|
||||||
copy_recursive(
|
copy_recursive(
|
||||||
fs.as_ref(),
|
fs.as_ref(),
|
||||||
&abs_old_path,
|
&abs_old_path,
|
||||||
|
@ -1173,7 +1175,7 @@ impl LocalWorktree {
|
||||||
) -> Option<Task<Result<()>>> {
|
) -> Option<Task<Result<()>>> {
|
||||||
let path = self.entry_for_id(entry_id)?.path.clone();
|
let path = self.entry_for_id(entry_id)?.path.clone();
|
||||||
let mut refresh = self.refresh_entries_for_paths(vec![path]);
|
let mut refresh = self.refresh_entries_for_paths(vec![path]);
|
||||||
Some(cx.executor().spawn(async move {
|
Some(cx.background_executor().spawn(async move {
|
||||||
refresh.next().await;
|
refresh.next().await;
|
||||||
Ok(())
|
Ok(())
|
||||||
}))
|
}))
|
||||||
|
@ -1247,7 +1249,7 @@ impl LocalWorktree {
|
||||||
.ok();
|
.ok();
|
||||||
|
|
||||||
let worktree_id = cx.entity_id().as_u64();
|
let worktree_id = cx.entity_id().as_u64();
|
||||||
let _maintain_remote_snapshot = cx.executor().spawn(async move {
|
let _maintain_remote_snapshot = cx.background_executor().spawn(async move {
|
||||||
let mut is_first = true;
|
let mut is_first = true;
|
||||||
while let Some((snapshot, entry_changes, repo_changes)) = snapshots_rx.next().await {
|
while let Some((snapshot, entry_changes, repo_changes)) = snapshots_rx.next().await {
|
||||||
let update;
|
let update;
|
||||||
|
@ -1305,7 +1307,7 @@ impl LocalWorktree {
|
||||||
let rx = self.observe_updates(project_id, cx, move |update| {
|
let rx = self.observe_updates(project_id, cx, move |update| {
|
||||||
client.request(update).map(|result| result.is_ok())
|
client.request(update).map(|result| result.is_ok())
|
||||||
});
|
});
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(async move { rx.await.map_err(|_| anyhow!("share ended")) })
|
.spawn(async move { rx.await.map_err(|_| anyhow!("share ended")) })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2671,7 +2673,8 @@ impl language2::LocalFile for File {
|
||||||
let worktree = self.worktree.read(cx).as_local().unwrap();
|
let worktree = self.worktree.read(cx).as_local().unwrap();
|
||||||
let abs_path = worktree.absolutize(&self.path);
|
let abs_path = worktree.absolutize(&self.path);
|
||||||
let fs = worktree.fs.clone();
|
let fs = worktree.fs.clone();
|
||||||
cx.executor().spawn(async move { fs.load(&abs_path).await })
|
cx.background_executor()
|
||||||
|
.spawn(async move { fs.load(&abs_path).await })
|
||||||
}
|
}
|
||||||
|
|
||||||
fn buffer_reloaded(
|
fn buffer_reloaded(
|
||||||
|
@ -3012,7 +3015,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 +3035,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 {
|
||||||
|
@ -4050,7 +4053,8 @@ impl WorktreeModelHandle for Model<Worktree> {
|
||||||
&self,
|
&self,
|
||||||
cx: &'a mut gpui2::TestAppContext,
|
cx: &'a mut gpui2::TestAppContext,
|
||||||
) -> futures::future::LocalBoxFuture<'a, ()> {
|
) -> futures::future::LocalBoxFuture<'a, ()> {
|
||||||
let filename = "fs-event-sentinel";
|
let file_name = "fs-event-sentinel";
|
||||||
|
|
||||||
let tree = self.clone();
|
let tree = self.clone();
|
||||||
let (fs, root_path) = self.update(cx, |tree, _| {
|
let (fs, root_path) = self.update(cx, |tree, _| {
|
||||||
let tree = tree.as_local().unwrap();
|
let tree = tree.as_local().unwrap();
|
||||||
|
@ -4058,17 +4062,18 @@ impl WorktreeModelHandle for Model<Worktree> {
|
||||||
});
|
});
|
||||||
|
|
||||||
async move {
|
async move {
|
||||||
fs.create_file(&root_path.join(filename), Default::default())
|
fs.create_file(&root_path.join(file_name), Default::default())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
cx.executor().run_until_parked();
|
|
||||||
assert!(tree.update(cx, |tree, _| tree.entry_for_path(filename).is_some()));
|
|
||||||
|
|
||||||
fs.remove_file(&root_path.join(filename), Default::default())
|
cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_some())
|
||||||
|
.await;
|
||||||
|
|
||||||
|
fs.remove_file(&root_path.join(file_name), Default::default())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
cx.executor().run_until_parked();
|
cx.condition(&tree, |tree, _| tree.entry_for_path(file_name).is_none())
|
||||||
assert!(tree.update(cx, |tree, _| tree.entry_for_path(filename).is_none()));
|
.await;
|
||||||
|
|
||||||
cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
|
cx.update(|cx| tree.read(cx).as_local().unwrap().scan_complete())
|
||||||
.await;
|
.await;
|
||||||
|
|
|
@ -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>>>,
|
||||||
|
|
|
@ -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,
|
||||||
|
@ -559,7 +559,6 @@ mod tests {
|
||||||
use async_tungstenite::tungstenite::Message as WebSocketMessage;
|
use async_tungstenite::tungstenite::Message as WebSocketMessage;
|
||||||
use gpui2::TestAppContext;
|
use gpui2::TestAppContext;
|
||||||
|
|
||||||
#[ctor::ctor]
|
|
||||||
fn init_logger() {
|
fn init_logger() {
|
||||||
if std::env::var("RUST_LOG").is_ok() {
|
if std::env::var("RUST_LOG").is_ok() {
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
|
@ -568,6 +567,8 @@ mod tests {
|
||||||
|
|
||||||
#[gpui2::test(iterations = 50)]
|
#[gpui2::test(iterations = 50)]
|
||||||
async fn test_request_response(cx: &mut TestAppContext) {
|
async fn test_request_response(cx: &mut TestAppContext) {
|
||||||
|
init_logger();
|
||||||
|
|
||||||
let executor = cx.executor();
|
let executor = cx.executor();
|
||||||
|
|
||||||
// create 2 clients connected to 1 server
|
// create 2 clients connected to 1 server
|
||||||
|
|
|
@ -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> {
|
||||||
|
@ -63,7 +63,10 @@ pub fn handle_settings_file_changes(
|
||||||
mut user_settings_file_rx: mpsc::UnboundedReceiver<String>,
|
mut user_settings_file_rx: mpsc::UnboundedReceiver<String>,
|
||||||
cx: &mut AppContext,
|
cx: &mut AppContext,
|
||||||
) {
|
) {
|
||||||
let user_settings_content = cx.executor().block(user_settings_file_rx.next()).unwrap();
|
let user_settings_content = cx
|
||||||
|
.background_executor()
|
||||||
|
.block(user_settings_file_rx.next())
|
||||||
|
.unwrap();
|
||||||
cx.update_global(|store: &mut SettingsStore, cx| {
|
cx.update_global(|store: &mut SettingsStore, cx| {
|
||||||
store
|
store
|
||||||
.set_user_settings(&user_settings_content, cx)
|
.set_user_settings(&user_settings_content, cx)
|
||||||
|
|
|
@ -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;
|
||||||
"]
|
"]
|
||||||
|
|
|
@ -51,8 +51,8 @@ use thiserror::Error;
|
||||||
|
|
||||||
use gpui2::{
|
use gpui2::{
|
||||||
px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla, Keystroke,
|
px, AnyWindowHandle, AppContext, Bounds, ClipboardItem, EventEmitter, Hsla, Keystroke,
|
||||||
MainThread, ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent,
|
ModelContext, Modifiers, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels,
|
||||||
Pixels, Point, ScrollWheelEvent, Size, Task, TouchPhase,
|
Point, ScrollWheelEvent, Size, Task, TouchPhase,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
|
use crate::mappings::{colors::to_alac_rgb, keys::to_esc_str};
|
||||||
|
@ -403,7 +403,7 @@ impl TerminalBuilder {
|
||||||
|
|
||||||
pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
|
pub fn subscribe(mut self, cx: &mut ModelContext<Terminal>) -> Terminal {
|
||||||
//Event loop
|
//Event loop
|
||||||
cx.spawn_on_main(|this, mut cx| async move {
|
cx.spawn(|this, mut cx| async move {
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
|
|
||||||
while let Some(event) = self.events_rx.next().await {
|
while let Some(event) = self.events_rx.next().await {
|
||||||
|
@ -414,7 +414,10 @@ impl TerminalBuilder {
|
||||||
|
|
||||||
'outer: loop {
|
'outer: loop {
|
||||||
let mut events = vec![];
|
let mut events = vec![];
|
||||||
let mut timer = cx.executor().timer(Duration::from_millis(4)).fuse();
|
let mut timer = cx
|
||||||
|
.background_executor()
|
||||||
|
.timer(Duration::from_millis(4))
|
||||||
|
.fuse();
|
||||||
let mut wakeup = false;
|
let mut wakeup = false;
|
||||||
loop {
|
loop {
|
||||||
futures::select_biased! {
|
futures::select_biased! {
|
||||||
|
@ -551,7 +554,7 @@ pub struct Terminal {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Terminal {
|
impl Terminal {
|
||||||
fn process_event(&mut self, event: &AlacTermEvent, cx: &mut MainThread<ModelContext<Self>>) {
|
fn process_event(&mut self, event: &AlacTermEvent, cx: &mut ModelContext<Self>) {
|
||||||
match event {
|
match event {
|
||||||
AlacTermEvent::Title(title) => {
|
AlacTermEvent::Title(title) => {
|
||||||
self.breadcrumb_text = title.to_string();
|
self.breadcrumb_text = title.to_string();
|
||||||
|
@ -708,8 +711,7 @@ impl Terminal {
|
||||||
|
|
||||||
InternalEvent::Copy => {
|
InternalEvent::Copy => {
|
||||||
if let Some(txt) = term.selection_to_string() {
|
if let Some(txt) = term.selection_to_string() {
|
||||||
cx.run_on_main(|cx| cx.write_to_clipboard(ClipboardItem::new(txt)))
|
cx.write_to_clipboard(ClipboardItem::new(txt))
|
||||||
.detach();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
InternalEvent::ScrollToAlacPoint(point) => {
|
InternalEvent::ScrollToAlacPoint(point) => {
|
||||||
|
@ -982,7 +984,7 @@ impl Terminal {
|
||||||
term.lock_unfair() //It's been too long, force block
|
term.lock_unfair() //It's been too long, force block
|
||||||
} else if let None = self.sync_task {
|
} else if let None = self.sync_task {
|
||||||
//Skip this frame
|
//Skip this frame
|
||||||
let delay = cx.executor().timer(Duration::from_millis(16));
|
let delay = cx.background_executor().timer(Duration::from_millis(16));
|
||||||
self.sync_task = Some(cx.spawn(|weak_handle, mut cx| async move {
|
self.sync_task = Some(cx.spawn(|weak_handle, mut cx| async move {
|
||||||
delay.await;
|
delay.await;
|
||||||
if let Some(handle) = weak_handle.upgrade() {
|
if let Some(handle) = weak_handle.upgrade() {
|
||||||
|
@ -1189,7 +1191,7 @@ impl Terminal {
|
||||||
&mut self,
|
&mut self,
|
||||||
e: &MouseUpEvent,
|
e: &MouseUpEvent,
|
||||||
origin: Point<Pixels>,
|
origin: Point<Pixels>,
|
||||||
cx: &mut MainThread<ModelContext<Self>>,
|
cx: &mut ModelContext<Self>,
|
||||||
) {
|
) {
|
||||||
let setting = TerminalSettings::get_global(cx);
|
let setting = TerminalSettings::get_global(cx);
|
||||||
|
|
||||||
|
@ -1300,7 +1302,7 @@ impl Terminal {
|
||||||
cx: &mut ModelContext<Self>,
|
cx: &mut ModelContext<Self>,
|
||||||
) -> Task<Vec<RangeInclusive<AlacPoint>>> {
|
) -> Task<Vec<RangeInclusive<AlacPoint>>> {
|
||||||
let term = self.term.clone();
|
let term = self.term.clone();
|
||||||
cx.executor().spawn(async move {
|
cx.background_executor().spawn(async move {
|
||||||
let term = term.lock();
|
let term = term.lock();
|
||||||
|
|
||||||
all_search_matches(&term, &searcher).collect()
|
all_search_matches(&term, &searcher).collect()
|
||||||
|
|
|
@ -51,7 +51,7 @@ impl<V: 'static> Pane<V> {
|
||||||
.id("drag-target")
|
.id("drag-target")
|
||||||
.drag_over::<ExternalPaths>(|d| d.bg(red()))
|
.drag_over::<ExternalPaths>(|d| d.bg(red()))
|
||||||
.on_drop(|_, files: View<ExternalPaths>, cx| {
|
.on_drop(|_, files: View<ExternalPaths>, cx| {
|
||||||
dbg!("dropped files!", files.read(cx));
|
eprintln!("dropped files! {:?}", files.read(cx));
|
||||||
})
|
})
|
||||||
.absolute()
|
.absolute()
|
||||||
.inset_0(),
|
.inset_0(),
|
||||||
|
|
|
@ -129,7 +129,7 @@ impl Tab {
|
||||||
.on_drag(move |_view, cx| cx.build_view(|cx| drag_state.clone()))
|
.on_drag(move |_view, cx| cx.build_view(|cx| drag_state.clone()))
|
||||||
.drag_over::<TabDragState>(|d| d.bg(cx.theme().colors().element_drop_target))
|
.drag_over::<TabDragState>(|d| d.bg(cx.theme().colors().element_drop_target))
|
||||||
.on_drop(|_view, state: View<TabDragState>, cx| {
|
.on_drop(|_view, state: View<TabDragState>, cx| {
|
||||||
dbg!(state.read(cx));
|
eprintln!("{:?}", state.read(cx));
|
||||||
})
|
})
|
||||||
.px_2()
|
.px_2()
|
||||||
.py_0p5()
|
.py_0p5()
|
||||||
|
|
|
@ -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();
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
@ -111,7 +117,7 @@ fn main() {
|
||||||
let client = client2::Client::new(http.clone(), cx);
|
let client = client2::Client::new(http.clone(), cx);
|
||||||
let mut languages = LanguageRegistry::new(login_shell_env_loaded);
|
let mut languages = LanguageRegistry::new(login_shell_env_loaded);
|
||||||
let copilot_language_server_id = languages.next_language_server_id();
|
let copilot_language_server_id = languages.next_language_server_id();
|
||||||
languages.set_executor(cx.executor().clone());
|
languages.set_executor(cx.background_executor().clone());
|
||||||
languages.set_language_server_download_dir(paths::LANGUAGES_DIR.clone());
|
languages.set_language_server_download_dir(paths::LANGUAGES_DIR.clone());
|
||||||
let languages = Arc::new(languages);
|
let languages = Arc::new(languages);
|
||||||
let node_runtime = RealNodeRuntime::new(http.clone());
|
let node_runtime = RealNodeRuntime::new(http.clone());
|
||||||
|
@ -508,7 +514,7 @@ fn init_panic_hook(app: &App, installation_id: Option<String>, session_id: Strin
|
||||||
fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
|
fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
|
||||||
let telemetry_settings = *client2::TelemetrySettings::get_global(cx);
|
let telemetry_settings = *client2::TelemetrySettings::get_global(cx);
|
||||||
|
|
||||||
cx.executor()
|
cx.background_executor()
|
||||||
.spawn(async move {
|
.spawn(async move {
|
||||||
let panic_report_url = format!("{}/api/panic", &*client2::ZED_SERVER_URL);
|
let panic_report_url = format!("{}/api/panic", &*client2::ZED_SERVER_URL);
|
||||||
let mut children = smol::fs::read_dir(&*paths::LOGS_DIR).await?;
|
let mut children = smol::fs::read_dir(&*paths::LOGS_DIR).await?;
|
||||||
|
@ -638,7 +644,7 @@ fn load_embedded_fonts(cx: &AppContext) {
|
||||||
let asset_source = cx.asset_source();
|
let asset_source = cx.asset_source();
|
||||||
let font_paths = asset_source.list("fonts").unwrap();
|
let font_paths = asset_source.list("fonts").unwrap();
|
||||||
let embedded_fonts = Mutex::new(Vec::new());
|
let embedded_fonts = Mutex::new(Vec::new());
|
||||||
let executor = cx.executor();
|
let executor = cx.background_executor();
|
||||||
|
|
||||||
executor.block(executor.scoped(|scope| {
|
executor.block(executor.scoped(|scope| {
|
||||||
for font_path in &font_paths {
|
for font_path in &font_paths {
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue