Remove 2 suffix for multi_buffer, outline, copilot

Co-authored-by: Mikayla <mikayla@zed.dev>
This commit is contained in:
Max Brunsfeld 2024-01-03 11:01:58 -08:00
parent 588976d27a
commit 492805af9c
25 changed files with 603 additions and 16691 deletions

View file

@ -20,14 +20,15 @@ test-support = [
[dependencies]
collections = { path = "../collections" }
context_menu = { path = "../context_menu" }
gpui = { path = "../gpui" }
language = { path = "../language" }
settings = { path = "../settings" }
theme = { path = "../theme" }
lsp = { path = "../lsp" }
# context_menu = { path = "../context_menu" }
gpui = { package = "gpui2", path = "../gpui2" }
language = { package = "language2", path = "../language2" }
settings = { package = "settings2", path = "../settings2" }
theme = { package = "theme2", path = "../theme2" }
lsp = { package = "lsp2", path = "../lsp2" }
node_runtime = { path = "../node_runtime"}
util = { path = "../util" }
ui = { package = "ui2", path = "../ui2" }
async-compression.workspace = true
async-tar = "0.4.2"
anyhow.workspace = true
@ -42,9 +43,9 @@ parking_lot.workspace = true
clock = { path = "../clock" }
collections = { path = "../collections", features = ["test-support"] }
fs = { path = "../fs", features = ["test-support"] }
gpui = { path = "../gpui", features = ["test-support"] }
language = { path = "../language", features = ["test-support"] }
lsp = { path = "../lsp", features = ["test-support"] }
rpc = { path = "../rpc", features = ["test-support"] }
settings = { path = "../settings", features = ["test-support"] }
gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
language = { package = "language2", path = "../language2", features = ["test-support"] }
lsp = { package = "lsp2", path = "../lsp2", features = ["test-support"] }
rpc = { package = "rpc2", path = "../rpc2", features = ["test-support"] }
settings = { package = "settings2", path = "../settings2", features = ["test-support"] }
util = { path = "../util", features = ["test-support"] }

View file

@ -1,13 +1,14 @@
pub mod request;
mod sign_in;
use anyhow::{anyhow, Context, Result};
use anyhow::{anyhow, Context as _, Result};
use async_compression::futures::bufread::GzipDecoder;
use async_tar::Archive;
use collections::{HashMap, HashSet};
use futures::{channel::oneshot, future::Shared, Future, FutureExt, TryFutureExt};
use gpui::{
actions, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, Task, WeakModelHandle,
actions, AppContext, AsyncAppContext, Context, Entity, EntityId, EventEmitter, Model,
ModelContext, Task, WeakModel,
};
use language::{
language_settings::{all_language_settings, language_settings},
@ -21,24 +22,27 @@ use request::StatusNotification;
use settings::SettingsStore;
use smol::{fs, io::BufReader, stream::StreamExt};
use std::{
any::TypeId,
ffi::OsString,
mem,
ops::Range,
path::{Path, PathBuf},
pin::Pin,
sync::Arc,
};
use util::{
fs::remove_matching, github::latest_github_release, http::HttpClient, paths, ResultExt,
};
const COPILOT_AUTH_NAMESPACE: &'static str = "copilot_auth";
actions!(copilot_auth, [SignIn, SignOut]);
const COPILOT_NAMESPACE: &'static str = "copilot";
actions!(
copilot,
[Suggest, NextSuggestion, PreviousSuggestion, Reinstall]
[
Suggest,
NextSuggestion,
PreviousSuggestion,
Reinstall,
SignIn,
SignOut
]
);
pub fn init(
@ -47,50 +51,69 @@ pub fn init(
node_runtime: Arc<dyn NodeRuntime>,
cx: &mut AppContext,
) {
let copilot = cx.add_model({
let copilot = cx.new_model({
let node_runtime = node_runtime.clone();
move |cx| Copilot::start(new_server_id, http, node_runtime, cx)
});
cx.set_global(copilot.clone());
cx.observe(&copilot, |handle, cx| {
let copilot_action_types = [
TypeId::of::<Suggest>(),
TypeId::of::<NextSuggestion>(),
TypeId::of::<PreviousSuggestion>(),
TypeId::of::<Reinstall>(),
];
let copilot_auth_action_types = [TypeId::of::<SignOut>()];
let copilot_no_auth_action_types = [TypeId::of::<SignIn>()];
let status = handle.read(cx).status();
cx.update_default_global::<collections::CommandPaletteFilter, _, _>(move |filter, _cx| {
match status {
Status::Disabled => {
filter.hidden_namespaces.insert(COPILOT_NAMESPACE);
filter.hidden_namespaces.insert(COPILOT_AUTH_NAMESPACE);
}
Status::Authorized => {
filter.hidden_namespaces.remove(COPILOT_NAMESPACE);
filter.hidden_namespaces.remove(COPILOT_AUTH_NAMESPACE);
}
_ => {
filter.hidden_namespaces.insert(COPILOT_NAMESPACE);
filter.hidden_namespaces.remove(COPILOT_AUTH_NAMESPACE);
let filter = cx.default_global::<collections::CommandPaletteFilter>();
match status {
Status::Disabled => {
filter.hidden_action_types.extend(copilot_action_types);
filter.hidden_action_types.extend(copilot_auth_action_types);
filter
.hidden_action_types
.extend(copilot_no_auth_action_types);
}
Status::Authorized => {
filter
.hidden_action_types
.extend(copilot_no_auth_action_types);
for type_id in copilot_action_types
.iter()
.chain(&copilot_auth_action_types)
{
filter.hidden_action_types.remove(type_id);
}
}
});
_ => {
filter.hidden_action_types.extend(copilot_action_types);
filter.hidden_action_types.extend(copilot_auth_action_types);
for type_id in &copilot_no_auth_action_types {
filter.hidden_action_types.remove(type_id);
}
}
}
})
.detach();
sign_in::init(cx);
cx.add_global_action(|_: &SignIn, cx| {
cx.on_action(|_: &SignIn, cx| {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| copilot.sign_in(cx))
.detach_and_log_err(cx);
}
});
cx.add_global_action(|_: &SignOut, cx| {
cx.on_action(|_: &SignOut, cx| {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| copilot.sign_out(cx))
.detach_and_log_err(cx);
}
});
cx.add_global_action(|_: &Reinstall, cx| {
cx.on_action(|_: &Reinstall, cx| {
if let Some(copilot) = Copilot::global(cx) {
copilot
.update(cx, |copilot, cx| copilot.reinstall(cx))
@ -133,7 +156,7 @@ struct RunningCopilotServer {
name: LanguageServerName,
lsp: Arc<LanguageServer>,
sign_in_status: SignInStatus,
registered_buffers: HashMap<usize, RegisteredBuffer>,
registered_buffers: HashMap<EntityId, RegisteredBuffer>,
}
#[derive(Clone, Debug)]
@ -180,7 +203,7 @@ struct RegisteredBuffer {
impl RegisteredBuffer {
fn report_changes(
&mut self,
buffer: &ModelHandle<Buffer>,
buffer: &Model<Buffer>,
cx: &mut ModelContext<Copilot>,
) -> oneshot::Receiver<(i32, BufferSnapshot)> {
let (done_tx, done_rx) = oneshot::channel();
@ -189,23 +212,23 @@ impl RegisteredBuffer {
let _ = done_tx.send((self.snapshot_version, self.snapshot.clone()));
} else {
let buffer = buffer.downgrade();
let id = buffer.id();
let id = buffer.entity_id();
let prev_pending_change =
mem::replace(&mut self.pending_buffer_change, Task::ready(None));
self.pending_buffer_change = cx.spawn_weak(|copilot, mut cx| async move {
self.pending_buffer_change = cx.spawn(move |copilot, mut cx| async move {
prev_pending_change.await;
let old_version = copilot.upgrade(&cx)?.update(&mut cx, |copilot, _| {
let server = copilot.server.as_authenticated().log_err()?;
let buffer = server.registered_buffers.get_mut(&id)?;
Some(buffer.snapshot.version.clone())
})?;
let new_snapshot = buffer
.upgrade(&cx)?
.read_with(&cx, |buffer, _| buffer.snapshot());
let old_version = copilot
.update(&mut cx, |copilot, _| {
let server = copilot.server.as_authenticated().log_err()?;
let buffer = server.registered_buffers.get_mut(&id)?;
Some(buffer.snapshot.version.clone())
})
.ok()??;
let new_snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot()).ok()?;
let content_changes = cx
.background()
.background_executor()
.spawn({
let new_snapshot = new_snapshot.clone();
async move {
@ -231,28 +254,30 @@ impl RegisteredBuffer {
})
.await;
copilot.upgrade(&cx)?.update(&mut cx, |copilot, _| {
let server = copilot.server.as_authenticated().log_err()?;
let buffer = server.registered_buffers.get_mut(&id)?;
if !content_changes.is_empty() {
buffer.snapshot_version += 1;
buffer.snapshot = new_snapshot;
server
.lsp
.notify::<lsp::notification::DidChangeTextDocument>(
lsp::DidChangeTextDocumentParams {
text_document: lsp::VersionedTextDocumentIdentifier::new(
buffer.uri.clone(),
buffer.snapshot_version,
),
content_changes,
},
)
.log_err();
}
let _ = done_tx.send((buffer.snapshot_version, buffer.snapshot.clone()));
Some(())
})?;
copilot
.update(&mut cx, |copilot, _| {
let server = copilot.server.as_authenticated().log_err()?;
let buffer = server.registered_buffers.get_mut(&id)?;
if !content_changes.is_empty() {
buffer.snapshot_version += 1;
buffer.snapshot = new_snapshot;
server
.lsp
.notify::<lsp::notification::DidChangeTextDocument>(
lsp::DidChangeTextDocumentParams {
text_document: lsp::VersionedTextDocumentIdentifier::new(
buffer.uri.clone(),
buffer.snapshot_version,
),
content_changes,
},
)
.log_err();
}
let _ = done_tx.send((buffer.snapshot_version, buffer.snapshot.clone()));
Some(())
})
.ok()?;
Some(())
});
@ -273,36 +298,21 @@ pub struct Copilot {
http: Arc<dyn HttpClient>,
node_runtime: Arc<dyn NodeRuntime>,
server: CopilotServer,
buffers: HashSet<WeakModelHandle<Buffer>>,
buffers: HashSet<WeakModel<Buffer>>,
server_id: LanguageServerId,
_subscription: gpui::Subscription,
}
pub enum Event {
CopilotLanguageServerStarted,
}
impl Entity for Copilot {
type Event = Event;
fn app_will_quit(
&mut self,
_: &mut AppContext,
) -> Option<Pin<Box<dyn 'static + Future<Output = ()>>>> {
match mem::replace(&mut self.server, CopilotServer::Disabled) {
CopilotServer::Running(server) => Some(Box::pin(async move {
if let Some(shutdown) = server.lsp.shutdown() {
shutdown.await;
}
})),
_ => None,
}
}
}
impl EventEmitter<Event> for Copilot {}
impl Copilot {
pub fn global(cx: &AppContext) -> Option<ModelHandle<Self>> {
if cx.has_global::<ModelHandle<Self>>() {
Some(cx.global::<ModelHandle<Self>>().clone())
pub fn global(cx: &AppContext) -> Option<Model<Self>> {
if cx.has_global::<Model<Self>>() {
Some(cx.global::<Model<Self>>().clone())
} else {
None
}
@ -320,24 +330,39 @@ impl Copilot {
node_runtime,
server: CopilotServer::Disabled,
buffers: Default::default(),
_subscription: cx.on_app_quit(Self::shutdown_language_server),
};
this.enable_or_disable_copilot(cx);
cx.observe_global::<SettingsStore, _>(move |this, cx| this.enable_or_disable_copilot(cx))
cx.observe_global::<SettingsStore>(move |this, cx| this.enable_or_disable_copilot(cx))
.detach();
this
}
fn enable_or_disable_copilot(&mut self, cx: &mut ModelContext<Copilot>) {
fn shutdown_language_server(
&mut self,
_cx: &mut ModelContext<Self>,
) -> impl Future<Output = ()> {
let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
_ => None,
};
async move {
if let Some(shutdown) = shutdown {
shutdown.await;
}
}
}
fn enable_or_disable_copilot(&mut self, cx: &mut ModelContext<Self>) {
let server_id = self.server_id;
let http = self.http.clone();
let node_runtime = self.node_runtime.clone();
if all_language_settings(None, cx).copilot_enabled(None, None) {
if matches!(self.server, CopilotServer::Disabled) {
let start_task = cx
.spawn({
move |this, cx| {
Self::start_language_server(server_id, http, node_runtime, this, cx)
}
.spawn(move |this, cx| {
Self::start_language_server(server_id, http, node_runtime, this, cx)
})
.shared();
self.server = CopilotServer::Starting { task: start_task };
@ -350,14 +375,14 @@ impl Copilot {
}
#[cfg(any(test, feature = "test-support"))]
pub fn fake(cx: &mut gpui::TestAppContext) -> (ModelHandle<Self>, lsp::FakeLanguageServer) {
pub fn fake(cx: &mut gpui::TestAppContext) -> (Model<Self>, lsp::FakeLanguageServer) {
use node_runtime::FakeNodeRuntime;
let (server, fake_server) =
LanguageServer::fake("copilot".into(), Default::default(), cx.to_async());
let http = util::http::FakeHttpClient::create(|_| async { unreachable!() });
let node_runtime = FakeNodeRuntime::new();
let this = cx.add_model(|_| Self {
let this = cx.new_model(|cx| Self {
server_id: LanguageServerId(0),
http: http.clone(),
node_runtime,
@ -367,6 +392,7 @@ impl Copilot {
sign_in_status: SignInStatus::Authorized,
registered_buffers: Default::default(),
}),
_subscription: cx.on_app_quit(Self::shutdown_language_server),
buffers: Default::default(),
});
(this, fake_server)
@ -376,7 +402,7 @@ impl Copilot {
new_server_id: LanguageServerId,
http: Arc<dyn HttpClient>,
node_runtime: Arc<dyn NodeRuntime>,
this: ModelHandle<Self>,
this: WeakModel<Self>,
mut cx: AsyncAppContext,
) -> impl Future<Output = ()> {
async move {
@ -448,6 +474,7 @@ impl Copilot {
}
}
})
.ok();
}
}
@ -489,7 +516,7 @@ impl Copilot {
cx.notify();
}
}
});
})?;
let response = lsp
.request::<request::SignInConfirm>(
request::SignInConfirmParams {
@ -515,7 +542,7 @@ impl Copilot {
);
Err(Arc::new(error))
}
})
})?
})
.shared();
server.sign_in_status = SignInStatus::SigningIn {
@ -527,7 +554,7 @@ impl Copilot {
}
};
cx.foreground()
cx.background_executor()
.spawn(task.map_err(|err| anyhow!("{:?}", err)))
} else {
// If we're downloading, wait until download is finished
@ -540,7 +567,7 @@ impl Copilot {
self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
if let CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) = &self.server {
let server = server.clone();
cx.background().spawn(async move {
cx.background_executor().spawn(async move {
server
.request::<request::SignOut>(request::SignOutParams {})
.await?;
@ -570,7 +597,7 @@ impl Copilot {
cx.notify();
cx.foreground().spawn(start_task)
cx.background_executor().spawn(start_task)
}
pub fn language_server(&self) -> Option<(&LanguageServerName, &Arc<LanguageServer>)> {
@ -581,7 +608,7 @@ impl Copilot {
}
}
pub fn register_buffer(&mut self, buffer: &ModelHandle<Buffer>, cx: &mut ModelContext<Self>) {
pub fn register_buffer(&mut self, buffer: &Model<Buffer>, cx: &mut ModelContext<Self>) {
let weak_buffer = buffer.downgrade();
self.buffers.insert(weak_buffer.clone());
@ -596,51 +623,54 @@ impl Copilot {
return;
}
registered_buffers.entry(buffer.id()).or_insert_with(|| {
let uri: lsp::Url = uri_for_buffer(buffer, cx);
let language_id = id_for_language(buffer.read(cx).language());
let snapshot = buffer.read(cx).snapshot();
server
.notify::<lsp::notification::DidOpenTextDocument>(
lsp::DidOpenTextDocumentParams {
text_document: lsp::TextDocumentItem {
uri: uri.clone(),
language_id: language_id.clone(),
version: 0,
text: snapshot.text(),
registered_buffers
.entry(buffer.entity_id())
.or_insert_with(|| {
let uri: lsp::Url = uri_for_buffer(buffer, cx);
let language_id = id_for_language(buffer.read(cx).language());
let snapshot = buffer.read(cx).snapshot();
server
.notify::<lsp::notification::DidOpenTextDocument>(
lsp::DidOpenTextDocumentParams {
text_document: lsp::TextDocumentItem {
uri: uri.clone(),
language_id: language_id.clone(),
version: 0,
text: snapshot.text(),
},
},
},
)
.log_err();
)
.log_err();
RegisteredBuffer {
uri,
language_id,
snapshot,
snapshot_version: 0,
pending_buffer_change: Task::ready(Some(())),
_subscriptions: [
cx.subscribe(buffer, |this, buffer, event, cx| {
this.handle_buffer_event(buffer, event, cx).log_err();
}),
cx.observe_release(buffer, move |this, _buffer, _cx| {
this.buffers.remove(&weak_buffer);
this.unregister_buffer(&weak_buffer);
}),
],
}
});
RegisteredBuffer {
uri,
language_id,
snapshot,
snapshot_version: 0,
pending_buffer_change: Task::ready(Some(())),
_subscriptions: [
cx.subscribe(buffer, |this, buffer, event, cx| {
this.handle_buffer_event(buffer, event, cx).log_err();
}),
cx.observe_release(buffer, move |this, _buffer, _cx| {
this.buffers.remove(&weak_buffer);
this.unregister_buffer(&weak_buffer);
}),
],
}
});
}
}
fn handle_buffer_event(
&mut self,
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
event: &language::Event,
cx: &mut ModelContext<Self>,
) -> Result<()> {
if let Ok(server) = self.server.as_running() {
if let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.id()) {
if let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
{
match event {
language::Event::Edited => {
let _ = registered_buffer.report_changes(&buffer, cx);
@ -694,9 +724,9 @@ impl Copilot {
Ok(())
}
fn unregister_buffer(&mut self, buffer: &WeakModelHandle<Buffer>) {
fn unregister_buffer(&mut self, buffer: &WeakModel<Buffer>) {
if let Ok(server) = self.server.as_running() {
if let Some(buffer) = server.registered_buffers.remove(&buffer.id()) {
if let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id()) {
server
.lsp
.notify::<lsp::notification::DidCloseTextDocument>(
@ -711,7 +741,7 @@ impl Copilot {
pub fn completions<T>(
&mut self,
buffer: &ModelHandle<Buffer>,
buffer: &Model<Buffer>,
position: T,
cx: &mut ModelContext<Self>,
) -> Task<Result<Vec<Completion>>>
@ -723,7 +753,7 @@ impl Copilot {
pub fn completions_cycling<T>(
&mut self,
buffer: &ModelHandle<Buffer>,
buffer: &Model<Buffer>,
position: T,
cx: &mut ModelContext<Self>,
) -> Task<Result<Vec<Completion>>>
@ -748,7 +778,7 @@ impl Copilot {
.request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
uuid: completion.uuid.clone(),
});
cx.background().spawn(async move {
cx.background_executor().spawn(async move {
request.await?;
Ok(())
})
@ -772,7 +802,7 @@ impl Copilot {
.map(|completion| completion.uuid.clone())
.collect(),
});
cx.background().spawn(async move {
cx.background_executor().spawn(async move {
request.await?;
Ok(())
})
@ -780,7 +810,7 @@ impl Copilot {
fn request_completions<R, T>(
&mut self,
buffer: &ModelHandle<Buffer>,
buffer: &Model<Buffer>,
position: T,
cx: &mut ModelContext<Self>,
) -> Task<Result<Vec<Completion>>>
@ -799,7 +829,10 @@ impl Copilot {
Err(error) => return Task::ready(Err(error)),
};
let lsp = server.lsp.clone();
let registered_buffer = server.registered_buffers.get_mut(&buffer.id()).unwrap();
let registered_buffer = server
.registered_buffers
.get_mut(&buffer.entity_id())
.unwrap();
let snapshot = registered_buffer.report_changes(buffer, cx);
let buffer = buffer.read(cx);
let uri = registered_buffer.uri.clone();
@ -812,7 +845,7 @@ impl Copilot {
.map(|file| file.path().to_path_buf())
.unwrap_or_default();
cx.foreground().spawn(async move {
cx.background_executor().spawn(async move {
let (version, snapshot) = snapshot.await?;
let result = lsp
.request::<R>(request::GetCompletionsParams {
@ -869,7 +902,7 @@ impl Copilot {
lsp_status: request::SignInStatus,
cx: &mut ModelContext<Self>,
) {
self.buffers.retain(|buffer| buffer.is_upgradable(cx));
self.buffers.retain(|buffer| buffer.is_upgradable());
if let Ok(server) = self.server.as_running() {
match lsp_status {
@ -878,20 +911,20 @@ impl Copilot {
| request::SignInStatus::AlreadySignedIn { .. } => {
server.sign_in_status = SignInStatus::Authorized;
for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
if let Some(buffer) = buffer.upgrade(cx) {
if let Some(buffer) = buffer.upgrade() {
self.register_buffer(&buffer, cx);
}
}
}
request::SignInStatus::NotAuthorized { .. } => {
server.sign_in_status = SignInStatus::Unauthorized;
for buffer in self.buffers.iter().copied().collect::<Vec<_>>() {
for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
self.unregister_buffer(&buffer);
}
}
request::SignInStatus::NotSignedIn => {
server.sign_in_status = SignInStatus::SignedOut;
for buffer in self.buffers.iter().copied().collect::<Vec<_>>() {
for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
self.unregister_buffer(&buffer);
}
}
@ -911,11 +944,11 @@ fn id_for_language(language: Option<&Arc<Language>>) -> String {
}
}
fn uri_for_buffer(buffer: &ModelHandle<Buffer>, cx: &AppContext) -> lsp::Url {
fn uri_for_buffer(buffer: &Model<Buffer>, cx: &AppContext) -> lsp::Url {
if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
lsp::Url::from_file_path(file.abs_path(cx)).unwrap()
} else {
format!("buffer://{}", buffer.id()).parse().unwrap()
format!("buffer://{}", buffer.entity_id()).parse().unwrap()
}
}
@ -994,15 +1027,16 @@ async fn get_copilot_lsp(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
#[cfg(test)]
mod tests {
use super::*;
use gpui::{executor::Deterministic, TestAppContext};
use gpui::TestAppContext;
#[gpui::test(iterations = 10)]
async fn test_buffer_management(deterministic: Arc<Deterministic>, cx: &mut TestAppContext) {
deterministic.forbid_parking();
async fn test_buffer_management(cx: &mut TestAppContext) {
let (copilot, mut lsp) = Copilot::fake(cx);
let buffer_1 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "Hello"));
let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.id()).parse().unwrap();
let buffer_1 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "Hello"));
let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.entity_id().as_u64())
.parse()
.unwrap();
copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
assert_eq!(
lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
@ -1017,8 +1051,10 @@ mod tests {
}
);
let buffer_2 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "Goodbye"));
let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.id()).parse().unwrap();
let buffer_2 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "Goodbye"));
let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.entity_id().as_u64())
.parse()
.unwrap();
copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
assert_eq!(
lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
@ -1114,6 +1150,7 @@ mod tests {
.update(cx, |copilot, cx| copilot.sign_in(cx))
.await
.unwrap();
assert_eq!(
lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
.await,
@ -1138,7 +1175,6 @@ mod tests {
),
}
);
// Dropping a buffer causes it to be closed on the LSP side as well.
cx.update(|_| drop(buffer_2));
assert_eq!(

View file

@ -1,18 +1,11 @@
use crate::{request::PromptUserDeviceFlow, Copilot, Status};
use gpui::{
elements::*,
geometry::rect::RectF,
platform::{WindowBounds, WindowKind, WindowOptions},
AnyElement, AnyViewHandle, AppContext, ClipboardItem, Element, Entity, View, ViewContext,
WindowHandle,
div, size, AppContext, Bounds, ClipboardItem, Element, GlobalPixels, InteractiveElement,
IntoElement, ParentElement, Point, Render, Styled, ViewContext, VisualContext, WindowBounds,
WindowHandle, WindowKind, WindowOptions,
};
use theme::ui::modal;
#[derive(PartialEq, Eq, Debug, Clone)]
struct CopyUserCode;
#[derive(PartialEq, Eq, Debug, Clone)]
struct OpenGithub;
use theme::ActiveTheme;
use ui::{prelude::*, Button, Icon, IconElement, Label};
const COPILOT_SIGN_UP_URL: &'static str = "https://github.com/features/copilot";
@ -26,14 +19,11 @@ pub fn init(cx: &mut AppContext) {
crate::Status::SigningIn { prompt } => {
if let Some(window) = verification_window.as_mut() {
let updated = window
.root(cx)
.map(|root| {
root.update(cx, |verification, cx| {
verification.set_status(status.clone(), cx);
cx.activate_window();
})
.update(cx, |verification, cx| {
verification.set_status(status.clone(), cx);
cx.activate_window();
})
.is_some();
.is_ok();
if !updated {
verification_window = Some(create_copilot_auth_window(cx, &status));
}
@ -43,18 +33,20 @@ pub fn init(cx: &mut AppContext) {
}
Status::Authorized | Status::Unauthorized => {
if let Some(window) = verification_window.as_ref() {
if let Some(verification) = window.root(cx) {
verification.update(cx, |verification, cx| {
window
.update(cx, |verification, cx| {
verification.set_status(status, cx);
cx.platform().activate(true);
cx.activate(true);
cx.activate_window();
});
}
})
.ok();
}
}
_ => {
if let Some(code_verification) = verification_window.take() {
code_verification.update(cx, |cx| cx.remove_window());
code_verification
.update(cx, |_, cx| cx.remove_window())
.ok();
}
}
}
@ -67,20 +59,21 @@ fn create_copilot_auth_window(
cx: &mut AppContext,
status: &Status,
) -> WindowHandle<CopilotCodeVerification> {
let window_size = theme::current(cx).copilot.modal.dimensions();
let window_size = size(GlobalPixels::from(280.), GlobalPixels::from(280.));
let window_options = WindowOptions {
bounds: WindowBounds::Fixed(RectF::new(Default::default(), window_size)),
bounds: WindowBounds::Fixed(Bounds::new(Point::default(), window_size)),
titlebar: None,
center: true,
focus: true,
show: true,
kind: WindowKind::Normal,
kind: WindowKind::PopUp,
is_movable: true,
screen: None,
display_id: None,
};
cx.add_window(window_options, |_cx| {
CopilotCodeVerification::new(status.clone())
})
let window = cx.open_window(window_options, |cx| {
cx.new_view(|_| CopilotCodeVerification::new(status.clone()))
});
window
}
pub struct CopilotCodeVerification {
@ -103,273 +96,116 @@ impl CopilotCodeVerification {
fn render_device_code(
data: &PromptUserDeviceFlow,
style: &theme::Copilot,
cx: &mut ViewContext<Self>,
) -> impl Element<Self> {
) -> impl IntoElement {
let copied = cx
.read_from_clipboard()
.map(|item| item.text() == &data.user_code)
.unwrap_or(false);
let device_code_style = &style.auth.prompting.device_code;
MouseEventHandler::new::<Self, _>(0, cx, |state, _cx| {
Flex::row()
.with_child(
Label::new(data.user_code.clone(), device_code_style.text.clone())
.aligned()
.contained()
.with_style(device_code_style.left_container)
.constrained()
.with_width(device_code_style.left),
)
.with_child(
Label::new(
if copied { "Copied!" } else { "Copy" },
device_code_style.cta.style_for(state).text.clone(),
)
.aligned()
.contained()
.with_style(*device_code_style.right_container.style_for(state))
.constrained()
.with_width(device_code_style.right),
)
.contained()
.with_style(device_code_style.cta.style_for(state).container)
})
.on_click(gpui::platform::MouseButton::Left, {
let user_code = data.user_code.clone();
move |_, _, cx| {
cx.platform()
.write_to_clipboard(ClipboardItem::new(user_code.clone()));
cx.notify();
}
})
.with_cursor_style(gpui::platform::CursorStyle::PointingHand)
h_stack()
.cursor_pointer()
.justify_between()
.on_mouse_down(gpui::MouseButton::Left, {
let user_code = data.user_code.clone();
move |_, cx| {
cx.write_to_clipboard(ClipboardItem::new(user_code.clone()));
cx.notify();
}
})
.child(Label::new(data.user_code.clone()))
.child(div())
.child(Label::new(if copied { "Copied!" } else { "Copy" }))
}
fn render_prompting_modal(
connect_clicked: bool,
data: &PromptUserDeviceFlow,
style: &theme::Copilot,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
enum ConnectButton {}
Flex::column()
.with_child(
Flex::column()
.with_children([
Label::new(
"Enable Copilot by connecting",
style.auth.prompting.subheading.text.clone(),
)
.aligned(),
Label::new(
"your existing license.",
style.auth.prompting.subheading.text.clone(),
)
.aligned(),
])
.align_children_center()
.contained()
.with_style(style.auth.prompting.subheading.container),
) -> impl Element {
let connect_button_label = if connect_clicked {
"Waiting for connection..."
} else {
"Connect to Github"
};
v_stack()
.flex_1()
.items_center()
.justify_between()
.w_full()
.child(Label::new(
"Enable Copilot by connecting your existing license",
))
.child(Self::render_device_code(data, cx))
.child(
Label::new("Paste this code into GitHub after clicking the button below.")
.size(ui::LabelSize::Small),
)
.with_child(Self::render_device_code(data, &style, cx))
.with_child(
Flex::column()
.with_children([
Label::new(
"Paste this code into GitHub after",
style.auth.prompting.hint.text.clone(),
)
.aligned(),
Label::new(
"clicking the button below.",
style.auth.prompting.hint.text.clone(),
)
.aligned(),
])
.align_children_center()
.contained()
.with_style(style.auth.prompting.hint.container.clone()),
)
.with_child(theme::ui::cta_button::<ConnectButton, _, _, _>(
if connect_clicked {
"Waiting for connection..."
} else {
"Connect to GitHub"
},
style.auth.content_width,
&style.auth.cta_button,
cx,
{
.child(
Button::new("connect-button", connect_button_label).on_click({
let verification_uri = data.verification_uri.clone();
move |_, verification, cx| {
cx.platform().open_url(&verification_uri);
verification.connect_clicked = true;
}
},
cx.listener(move |this, _, cx| {
cx.open_url(&verification_uri);
this.connect_clicked = true;
})
}),
)
}
fn render_enabled_modal() -> impl Element {
v_stack()
.child(Label::new("Copilot Enabled!"))
.child(Label::new(
"You can update your settings or sign out from the Copilot menu in the status bar.",
))
.align_children_center()
.into_any()
.child(
Button::new("copilot-enabled-done-button", "Done")
.on_click(|_, cx| cx.remove_window()),
)
}
fn render_enabled_modal(
style: &theme::Copilot,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
enum DoneButton {}
let enabled_style = &style.auth.authorized;
Flex::column()
.with_child(
Label::new("Copilot Enabled!", enabled_style.subheading.text.clone())
.contained()
.with_style(enabled_style.subheading.container)
.aligned(),
)
.with_child(
Flex::column()
.with_children([
Label::new(
"You can update your settings or",
enabled_style.hint.text.clone(),
)
.aligned(),
Label::new(
"sign out from the Copilot menu in",
enabled_style.hint.text.clone(),
)
.aligned(),
Label::new("the status bar.", enabled_style.hint.text.clone()).aligned(),
])
.align_children_center()
.contained()
.with_style(enabled_style.hint.container),
)
.with_child(theme::ui::cta_button::<DoneButton, _, _, _>(
"Done",
style.auth.content_width,
&style.auth.cta_button,
cx,
|_, _, cx| cx.remove_window(),
fn render_unauthorized_modal() -> impl Element {
v_stack()
.child(Label::new(
"Enable Copilot by connecting your existing license.",
))
.align_children_center()
.into_any()
}
fn render_unauthorized_modal(
style: &theme::Copilot,
cx: &mut ViewContext<Self>,
) -> AnyElement<Self> {
let unauthorized_style = &style.auth.not_authorized;
Flex::column()
.with_child(
Flex::column()
.with_children([
Label::new(
"Enable Copilot by connecting",
unauthorized_style.subheading.text.clone(),
)
.aligned(),
Label::new(
"your existing license.",
unauthorized_style.subheading.text.clone(),
)
.aligned(),
])
.align_children_center()
.contained()
.with_style(unauthorized_style.subheading.container),
.child(
Label::new("You must have an active Copilot license to use it in Zed.")
.color(Color::Warning),
)
.with_child(
Flex::column()
.with_children([
Label::new(
"You must have an active copilot",
unauthorized_style.warning.text.clone(),
)
.aligned(),
Label::new(
"license to use it in Zed.",
unauthorized_style.warning.text.clone(),
)
.aligned(),
])
.align_children_center()
.contained()
.with_style(unauthorized_style.warning.container),
)
.with_child(theme::ui::cta_button::<Self, _, _, _>(
"Subscribe on GitHub",
style.auth.content_width,
&style.auth.cta_button,
cx,
|_, _, cx| {
.child(
Button::new("copilot-subscribe-button", "Subscibe on Github").on_click(|_, cx| {
cx.remove_window();
cx.platform().open_url(COPILOT_SIGN_UP_URL)
},
))
.align_children_center()
.into_any()
cx.open_url(COPILOT_SIGN_UP_URL)
}),
)
}
}
impl Entity for CopilotCodeVerification {
type Event = ();
}
impl View for CopilotCodeVerification {
fn ui_name() -> &'static str {
"CopilotCodeVerification"
}
fn focus_in(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
cx.notify()
}
fn focus_out(&mut self, _: AnyViewHandle, cx: &mut ViewContext<Self>) {
cx.notify()
}
fn render(&mut self, cx: &mut ViewContext<Self>) -> AnyElement<Self> {
enum ConnectModal {}
let style = theme::current(cx).clone();
modal::<ConnectModal, _, _, _, _>(
"Connect Copilot to Zed",
&style.copilot.modal,
cx,
|cx| {
Flex::column()
.with_children([
theme::ui::icon(&style.copilot.auth.header).into_any(),
match &self.status {
Status::SigningIn {
prompt: Some(prompt),
} => Self::render_prompting_modal(
self.connect_clicked,
&prompt,
&style.copilot,
cx,
),
Status::Unauthorized => {
self.connect_clicked = false;
Self::render_unauthorized_modal(&style.copilot, cx)
}
Status::Authorized => {
self.connect_clicked = false;
Self::render_enabled_modal(&style.copilot, cx)
}
_ => Empty::new().into_any(),
},
])
.align_children_center()
},
)
.into_any()
impl Render for CopilotCodeVerification {
fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
let prompt = match &self.status {
Status::SigningIn {
prompt: Some(prompt),
} => Self::render_prompting_modal(self.connect_clicked, &prompt, cx).into_any_element(),
Status::Unauthorized => {
self.connect_clicked = false;
Self::render_unauthorized_modal().into_any_element()
}
Status::Authorized => {
self.connect_clicked = false;
Self::render_enabled_modal().into_any_element()
}
_ => div().into_any_element(),
};
div()
.id("copilot code verification")
.flex()
.flex_col()
.size_full()
.items_center()
.p_10()
.bg(cx.theme().colors().element_background)
.child(ui::Label::new("Connect Copilot to Zed"))
.child(IconElement::new(Icon::ZedXCopilot))
.child(prompt)
}
}