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

112
Cargo.lock generated
View File

@ -385,7 +385,7 @@ dependencies = [
"language2",
"log",
"menu2",
"multi_buffer2",
"multi_buffer",
"ordered-float 2.10.0",
"parking_lot 0.11.2",
"project2",
@ -1093,7 +1093,7 @@ dependencies = [
"gpui2",
"itertools 0.10.5",
"language2",
"outline2",
"outline",
"project2",
"search",
"settings2",
@ -1947,33 +1947,6 @@ dependencies = [
[[package]]
name = "copilot"
version = "0.1.0"
dependencies = [
"anyhow",
"async-compression",
"async-tar",
"clock",
"collections",
"context_menu",
"fs",
"futures 0.3.28",
"gpui",
"language",
"log",
"lsp",
"node_runtime",
"parking_lot 0.11.2",
"rpc",
"serde",
"serde_derive",
"settings",
"smol",
"theme",
"util",
]
[[package]]
name = "copilot2"
version = "0.1.0"
dependencies = [
"anyhow",
"async-compression",
@ -2003,7 +1976,7 @@ name = "copilot_button"
version = "0.1.0"
dependencies = [
"anyhow",
"copilot2",
"copilot",
"editor",
"fs2",
"futures 0.3.28",
@ -2692,7 +2665,7 @@ dependencies = [
"clock",
"collections",
"convert_case 0.6.0",
"copilot2",
"copilot",
"ctor",
"db2",
"env_logger",
@ -2706,7 +2679,7 @@ dependencies = [
"lazy_static",
"log",
"lsp2",
"multi_buffer2",
"multi_buffer",
"ordered-float 2.10.0",
"parking_lot 0.11.2",
"postage",
@ -5071,55 +5044,6 @@ dependencies = [
[[package]]
name = "multi_buffer"
version = "0.1.0"
dependencies = [
"aho-corasick",
"anyhow",
"client",
"clock",
"collections",
"context_menu",
"convert_case 0.6.0",
"copilot",
"ctor",
"env_logger",
"futures 0.3.28",
"git",
"gpui",
"indoc",
"itertools 0.10.5",
"language",
"lazy_static",
"log",
"lsp",
"ordered-float 2.10.0",
"parking_lot 0.11.2",
"postage",
"project",
"pulldown-cmark",
"rand 0.8.5",
"rich_text",
"schemars",
"serde",
"serde_derive",
"settings",
"smallvec",
"smol",
"snippet",
"sum_tree",
"text",
"theme",
"tree-sitter",
"tree-sitter-html",
"tree-sitter-rust",
"tree-sitter-typescript",
"unindent",
"util",
"workspace",
]
[[package]]
name = "multi_buffer2"
version = "0.1.0"
dependencies = [
"aho-corasick",
"anyhow",
@ -5127,7 +5051,7 @@ dependencies = [
"clock",
"collections",
"convert_case 0.6.0",
"copilot2",
"copilot",
"ctor",
"env_logger",
"futures 0.3.28",
@ -5742,24 +5666,6 @@ dependencies = [
[[package]]
name = "outline"
version = "0.1.0"
dependencies = [
"editor",
"fuzzy",
"gpui",
"language",
"ordered-float 2.10.0",
"picker",
"postage",
"settings",
"smol",
"text",
"theme",
"workspace",
]
[[package]]
name = "outline2"
version = "0.1.0"
dependencies = [
"editor",
"fuzzy2",
@ -6353,7 +6259,7 @@ dependencies = [
"client2",
"clock",
"collections",
"copilot2",
"copilot",
"ctor",
"db2",
"env_logger",
@ -11013,7 +10919,7 @@ dependencies = [
"collab_ui",
"collections",
"command_palette",
"copilot2",
"copilot",
"copilot_button",
"ctor",
"db2",
@ -11045,7 +10951,7 @@ dependencies = [
"node_runtime",
"notifications2",
"num_cpus",
"outline2",
"outline",
"parking_lot 0.11.2",
"postage",
"project2",

View File

@ -24,7 +24,6 @@ members = [
"crates/component_test",
"crates/context_menu",
"crates/copilot",
"crates/copilot2",
"crates/copilot_button",
"crates/db",
"crates/db2",
@ -64,12 +63,10 @@ members = [
"crates/menu",
"crates/menu2",
"crates/multi_buffer",
"crates/multi_buffer2",
"crates/node_runtime",
"crates/notifications",
"crates/notifications2",
"crates/outline",
"crates/outline2",
"crates/picker",
"crates/plugin",
"crates/plugin_macros",

View File

@ -17,7 +17,7 @@ fs = { package = "fs2", path = "../fs2" }
gpui = { package = "gpui2", path = "../gpui2" }
language = { package = "language2", path = "../language2" }
menu = { package = "menu2", path = "../menu2" }
multi_buffer = { package = "multi_buffer2", path = "../multi_buffer2" }
multi_buffer = { path = "../multi_buffer" }
project = { package = "project2", path = "../project2" }
search = { path = "../search" }
semantic_index = { package = "semantic_index2", path = "../semantic_index2" }

View File

@ -19,7 +19,7 @@ search = { path = "../search" }
settings = { package = "settings2", path = "../settings2" }
theme = { package = "theme2", path = "../theme2" }
workspace = { package = "workspace2", path = "../workspace2" }
outline = { package = "outline2", path = "../outline2" }
outline = { path = "../outline" }
itertools = "0.10"
[dev-dependencies]

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)
}
}

View File

@ -1,51 +0,0 @@
[package]
name = "copilot2"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/copilot2.rs"
doctest = false
[features]
test-support = [
"collections/test-support",
"gpui/test-support",
"language/test-support",
"lsp/test-support",
"settings/test-support",
"util/test-support",
]
[dependencies]
collections = { path = "../collections" }
# 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
log.workspace = true
serde.workspace = true
serde_derive.workspace = true
smol.workspace = true
futures.workspace = true
parking_lot.workspace = true
[dev-dependencies]
clock = { path = "../clock" }
collections = { path = "../collections", features = ["test-support"] }
fs = { path = "../fs", 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"] }

File diff suppressed because it is too large Load Diff

View File

@ -1,225 +0,0 @@
use serde::{Deserialize, Serialize};
pub enum CheckStatus {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckStatusParams {
pub local_checks_only: bool,
}
impl lsp::request::Request for CheckStatus {
type Params = CheckStatusParams;
type Result = SignInStatus;
const METHOD: &'static str = "checkStatus";
}
pub enum SignInInitiate {}
#[derive(Debug, Serialize, Deserialize)]
pub struct SignInInitiateParams {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status")]
pub enum SignInInitiateResult {
AlreadySignedIn { user: String },
PromptUserDeviceFlow(PromptUserDeviceFlow),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PromptUserDeviceFlow {
pub user_code: String,
pub verification_uri: String,
}
impl lsp::request::Request for SignInInitiate {
type Params = SignInInitiateParams;
type Result = SignInInitiateResult;
const METHOD: &'static str = "signInInitiate";
}
pub enum SignInConfirm {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignInConfirmParams {
pub user_code: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(tag = "status")]
pub enum SignInStatus {
#[serde(rename = "OK")]
Ok {
user: String,
},
MaybeOk {
user: String,
},
AlreadySignedIn {
user: String,
},
NotAuthorized {
user: String,
},
NotSignedIn,
}
impl lsp::request::Request for SignInConfirm {
type Params = SignInConfirmParams;
type Result = SignInStatus;
const METHOD: &'static str = "signInConfirm";
}
pub enum SignOut {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignOutParams {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SignOutResult {}
impl lsp::request::Request for SignOut {
type Params = SignOutParams;
type Result = SignOutResult;
const METHOD: &'static str = "signOut";
}
pub enum GetCompletions {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCompletionsParams {
pub doc: GetCompletionsDocument,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCompletionsDocument {
pub tab_size: u32,
pub indent_size: u32,
pub insert_spaces: bool,
pub uri: lsp::Url,
pub relative_path: String,
pub position: lsp::Position,
pub version: usize,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetCompletionsResult {
pub completions: Vec<Completion>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Completion {
pub text: String,
pub position: lsp::Position,
pub uuid: String,
pub range: lsp::Range,
pub display_text: String,
}
impl lsp::request::Request for GetCompletions {
type Params = GetCompletionsParams;
type Result = GetCompletionsResult;
const METHOD: &'static str = "getCompletions";
}
pub enum GetCompletionsCycling {}
impl lsp::request::Request for GetCompletionsCycling {
type Params = GetCompletionsParams;
type Result = GetCompletionsResult;
const METHOD: &'static str = "getCompletionsCycling";
}
pub enum LogMessage {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct LogMessageParams {
pub level: u8,
pub message: String,
pub metadata_str: String,
pub extra: Vec<String>,
}
impl lsp::notification::Notification for LogMessage {
type Params = LogMessageParams;
const METHOD: &'static str = "LogMessage";
}
pub enum StatusNotification {}
#[derive(Debug, Serialize, Deserialize)]
pub struct StatusNotificationParams {
pub message: String,
pub status: String, // One of Normal/InProgress
}
impl lsp::notification::Notification for StatusNotification {
type Params = StatusNotificationParams;
const METHOD: &'static str = "statusNotification";
}
pub enum SetEditorInfo {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SetEditorInfoParams {
pub editor_info: EditorInfo,
pub editor_plugin_info: EditorPluginInfo,
}
impl lsp::request::Request for SetEditorInfo {
type Params = SetEditorInfoParams;
type Result = String;
const METHOD: &'static str = "setEditorInfo";
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EditorInfo {
pub name: String,
pub version: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EditorPluginInfo {
pub name: String,
pub version: String,
}
pub enum NotifyAccepted {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NotifyAcceptedParams {
pub uuid: String,
}
impl lsp::request::Request for NotifyAccepted {
type Params = NotifyAcceptedParams;
type Result = String;
const METHOD: &'static str = "notifyAccepted";
}
pub enum NotifyRejected {}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NotifyRejectedParams {
pub uuids: Vec<String>,
}
impl lsp::request::Request for NotifyRejected {
type Params = NotifyRejectedParams;
type Result = String;
const METHOD: &'static str = "notifyRejected";
}

View File

@ -1,211 +0,0 @@
use crate::{request::PromptUserDeviceFlow, Copilot, Status};
use gpui::{
div, size, AppContext, Bounds, ClipboardItem, Element, GlobalPixels, InteractiveElement,
IntoElement, ParentElement, Point, Render, Styled, ViewContext, VisualContext, WindowBounds,
WindowHandle, WindowKind, WindowOptions,
};
use theme::ActiveTheme;
use ui::{prelude::*, Button, Icon, IconElement, Label};
const COPILOT_SIGN_UP_URL: &'static str = "https://github.com/features/copilot";
pub fn init(cx: &mut AppContext) {
if let Some(copilot) = Copilot::global(cx) {
let mut verification_window: Option<WindowHandle<CopilotCodeVerification>> = None;
cx.observe(&copilot, move |copilot, cx| {
let status = copilot.read(cx).status();
match &status {
crate::Status::SigningIn { prompt } => {
if let Some(window) = verification_window.as_mut() {
let updated = window
.update(cx, |verification, cx| {
verification.set_status(status.clone(), cx);
cx.activate_window();
})
.is_ok();
if !updated {
verification_window = Some(create_copilot_auth_window(cx, &status));
}
} else if let Some(_prompt) = prompt {
verification_window = Some(create_copilot_auth_window(cx, &status));
}
}
Status::Authorized | Status::Unauthorized => {
if let Some(window) = verification_window.as_ref() {
window
.update(cx, |verification, cx| {
verification.set_status(status, cx);
cx.activate(true);
cx.activate_window();
})
.ok();
}
}
_ => {
if let Some(code_verification) = verification_window.take() {
code_verification
.update(cx, |_, cx| cx.remove_window())
.ok();
}
}
}
})
.detach();
}
}
fn create_copilot_auth_window(
cx: &mut AppContext,
status: &Status,
) -> WindowHandle<CopilotCodeVerification> {
let window_size = size(GlobalPixels::from(280.), GlobalPixels::from(280.));
let window_options = WindowOptions {
bounds: WindowBounds::Fixed(Bounds::new(Point::default(), window_size)),
titlebar: None,
center: true,
focus: true,
show: true,
kind: WindowKind::PopUp,
is_movable: true,
display_id: None,
};
let window = cx.open_window(window_options, |cx| {
cx.new_view(|_| CopilotCodeVerification::new(status.clone()))
});
window
}
pub struct CopilotCodeVerification {
status: Status,
connect_clicked: bool,
}
impl CopilotCodeVerification {
pub fn new(status: Status) -> Self {
Self {
status,
connect_clicked: false,
}
}
pub fn set_status(&mut self, status: Status, cx: &mut ViewContext<Self>) {
self.status = status;
cx.notify();
}
fn render_device_code(
data: &PromptUserDeviceFlow,
cx: &mut ViewContext<Self>,
) -> impl IntoElement {
let copied = cx
.read_from_clipboard()
.map(|item| item.text() == &data.user_code)
.unwrap_or(false);
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,
cx: &mut ViewContext<Self>,
) -> 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),
)
.child(
Button::new("connect-button", connect_button_label).on_click({
let verification_uri = data.verification_uri.clone();
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.",
))
.child(
Button::new("copilot-enabled-done-button", "Done")
.on_click(|_, cx| cx.remove_window()),
)
}
fn render_unauthorized_modal() -> impl Element {
v_stack()
.child(Label::new(
"Enable Copilot by connecting your existing license.",
))
.child(
Label::new("You must have an active Copilot license to use it in Zed.")
.color(Color::Warning),
)
.child(
Button::new("copilot-subscribe-button", "Subscibe on Github").on_click(|_, cx| {
cx.remove_window();
cx.open_url(COPILOT_SIGN_UP_URL)
}),
)
}
}
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)
}
}

View File

@ -9,7 +9,7 @@ path = "src/copilot_button.rs"
doctest = false
[dependencies]
copilot = { package = "copilot2", path = "../copilot2" }
copilot = { path = "../copilot" }
editor = { path = "../editor" }
fs = { package = "fs2", path = "../fs2" }
zed-actions = { package="zed_actions2", path = "../zed_actions2"}

View File

@ -25,7 +25,7 @@ test-support = [
[dependencies]
client = { package = "client2", path = "../client2" }
clock = { path = "../clock" }
copilot = { package="copilot2", path = "../copilot2" }
copilot = { path = "../copilot" }
db = { package="db2", path = "../db2" }
collections = { path = "../collections" }
# context_menu = { path = "../context_menu" }
@ -34,7 +34,7 @@ git = { package = "git3", path = "../git3" }
gpui = { package = "gpui2", path = "../gpui2" }
language = { package = "language2", path = "../language2" }
lsp = { package = "lsp2", path = "../lsp2" }
multi_buffer = { package = "multi_buffer2", path = "../multi_buffer2" }
multi_buffer = { path = "../multi_buffer" }
project = { package = "project2", path = "../project2" }
rpc = { package = "rpc2", path = "../rpc2" }
rich_text = { package = "rich_text2", path = "../rich_text2" }
@ -72,7 +72,7 @@ tree-sitter-html = { workspace = true, optional = true }
tree-sitter-typescript = { workspace = true, optional = true }
[dev-dependencies]
copilot = { package="copilot2", path = "../copilot2", features = ["test-support"] }
copilot = { path = "../copilot", features = ["test-support"] }
text = { package="text2", path = "../text2", features = ["test-support"] }
language = { package="language2", path = "../language2", features = ["test-support"] }
lsp = { package = "lsp2", path = "../lsp2", features = ["test-support"] }
@ -81,7 +81,7 @@ util = { path = "../util", features = ["test-support"] }
project = { package = "project2", path = "../project2", features = ["test-support"] }
settings = { package = "settings2", path = "../settings2", features = ["test-support"] }
workspace = { package = "workspace2", path = "../workspace2", features = ["test-support"] }
multi_buffer = { package = "multi_buffer2", path = "../multi_buffer2", features = ["test-support"] }
multi_buffer = { path = "../multi_buffer", features = ["test-support"] }
ctor.workspace = true
env_logger.workspace = true

File diff suppressed because it is too large Load Diff

View File

@ -20,20 +20,19 @@ test-support = [
]
[dependencies]
client = { path = "../client" }
client = { package = "client2", path = "../client2" }
clock = { path = "../clock" }
collections = { path = "../collections" }
context_menu = { path = "../context_menu" }
git = { path = "../git" }
gpui = { path = "../gpui" }
language = { path = "../language" }
lsp = { path = "../lsp" }
rich_text = { path = "../rich_text" }
settings = { path = "../settings" }
git = { package = "git3", path = "../git3" }
gpui = { package = "gpui2", path = "../gpui2" }
language = { package = "language2", path = "../language2" }
lsp = { package = "lsp2", path = "../lsp2" }
rich_text = { package = "rich_text2", path = "../rich_text2" }
settings = { package = "settings2", path = "../settings2" }
snippet = { path = "../snippet" }
sum_tree = { path = "../sum_tree" }
text = { path = "../text" }
theme = { path = "../theme" }
text = { package = "text2", path = "../text2" }
theme = { package = "theme2", path = "../theme2" }
util = { path = "../util" }
aho-corasick = "1.1"
@ -61,14 +60,13 @@ tree-sitter-typescript = { workspace = true, optional = true }
[dev-dependencies]
copilot = { path = "../copilot", features = ["test-support"] }
text = { path = "../text", features = ["test-support"] }
language = { path = "../language", features = ["test-support"] }
lsp = { path = "../lsp", features = ["test-support"] }
gpui = { path = "../gpui", features = ["test-support"] }
text = { package = "text2", path = "../text2", features = ["test-support"] }
language = { package = "language2", path = "../language2", features = ["test-support"] }
lsp = { package = "lsp2", path = "../lsp2", features = ["test-support"] }
gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
util = { path = "../util", features = ["test-support"] }
project = { path = "../project", features = ["test-support"] }
settings = { path = "../settings", features = ["test-support"] }
workspace = { path = "../workspace", features = ["test-support"] }
project = { package = "project2", path = "../project2", features = ["test-support"] }
settings = { package = "settings2", path = "../settings2", features = ["test-support"] }
ctor.workspace = true
env_logger.workspace = true

View File

@ -6,7 +6,7 @@ use clock::ReplicaId;
use collections::{BTreeMap, Bound, HashMap, HashSet};
use futures::{channel::mpsc, SinkExt};
use git::diff::DiffHunk;
use gpui::{AppContext, Entity, ModelContext, ModelHandle};
use gpui::{AppContext, EventEmitter, Model, ModelContext};
pub use language::Completion;
use language::{
char_kind,
@ -38,6 +38,9 @@ use text::{
use theme::SyntaxTheme;
use util::post_inc;
#[cfg(any(test, feature = "test-support"))]
use gpui::Context;
const NEWLINES: &[u8] = &[b'\n'; u8::MAX as usize];
#[derive(Debug, Default, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord)]
@ -57,7 +60,7 @@ pub struct MultiBuffer {
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Event {
ExcerptsAdded {
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
predecessor: ExcerptId,
excerpts: Vec<(ExcerptId, ExcerptRange<language::Anchor>)>,
},
@ -119,7 +122,7 @@ pub trait ToPointUtf16: 'static + fmt::Debug {
}
struct BufferState {
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
last_version: clock::Global,
last_parse_count: usize,
last_selections_update_count: usize,
@ -279,7 +282,7 @@ impl MultiBuffer {
self
}
pub fn singleton(buffer: ModelHandle<Buffer>, cx: &mut ModelContext<Self>) -> Self {
pub fn singleton(buffer: Model<Buffer>, cx: &mut ModelContext<Self>) -> Self {
let mut this = Self::new(buffer.read(cx).replica_id());
this.singleton = true;
this.push_excerpts(
@ -308,7 +311,7 @@ impl MultiBuffer {
self.snapshot.borrow()
}
pub fn as_singleton(&self) -> Option<ModelHandle<Buffer>> {
pub fn as_singleton(&self) -> Option<Model<Buffer>> {
if self.singleton {
return Some(
self.buffers
@ -681,7 +684,7 @@ impl MultiBuffer {
pub fn push_transaction<'a, T>(&mut self, buffer_transactions: T, cx: &mut ModelContext<Self>)
where
T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
{
self.history
.push_transaction(buffer_transactions, Instant::now(), cx);
@ -863,19 +866,19 @@ impl MultiBuffer {
pub fn stream_excerpts_with_context_lines(
&mut self,
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
ranges: Vec<Range<text::Anchor>>,
context_line_count: u32,
cx: &mut ModelContext<Self>,
) -> mpsc::Receiver<Range<Anchor>> {
let (mut tx, rx) = mpsc::channel(256);
cx.spawn(|this, mut cx| async move {
let (buffer_id, buffer_snapshot) =
buffer.read_with(&cx, |buffer, _| (buffer.remote_id(), buffer.snapshot()));
let (buffer_id, buffer_snapshot) =
buffer.update(cx, |buffer, _| (buffer.remote_id(), buffer.snapshot()));
let (mut tx, rx) = mpsc::channel(256);
cx.spawn(move |this, mut cx| async move {
let mut excerpt_ranges = Vec::new();
let mut range_counts = Vec::new();
cx.background()
cx.background_executor()
.scoped(|scope| {
scope.spawn(async {
let (ranges, counts) =
@ -889,9 +892,12 @@ impl MultiBuffer {
let mut ranges = ranges.into_iter();
let mut range_counts = range_counts.into_iter();
for excerpt_ranges in excerpt_ranges.chunks(100) {
let excerpt_ids = this.update(&mut cx, |this, cx| {
let excerpt_ids = match this.update(&mut cx, |this, cx| {
this.push_excerpts(buffer.clone(), excerpt_ranges.iter().cloned(), cx)
});
}) {
Ok(excerpt_ids) => excerpt_ids,
Err(_) => return,
};
for (excerpt_id, range_count) in excerpt_ids.into_iter().zip(range_counts.by_ref())
{
@ -920,7 +926,7 @@ impl MultiBuffer {
pub fn push_excerpts<O>(
&mut self,
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
ranges: impl IntoIterator<Item = ExcerptRange<O>>,
cx: &mut ModelContext<Self>,
) -> Vec<ExcerptId>
@ -932,7 +938,7 @@ impl MultiBuffer {
pub fn push_excerpts_with_context_lines<O>(
&mut self,
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
ranges: Vec<Range<O>>,
context_line_count: u32,
cx: &mut ModelContext<Self>,
@ -970,7 +976,7 @@ impl MultiBuffer {
pub fn insert_excerpts_after<O>(
&mut self,
prev_excerpt_id: ExcerptId,
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
ranges: impl IntoIterator<Item = ExcerptRange<O>>,
cx: &mut ModelContext<Self>,
) -> Vec<ExcerptId>
@ -995,7 +1001,7 @@ impl MultiBuffer {
pub fn insert_excerpts_with_ids_after<O>(
&mut self,
prev_excerpt_id: ExcerptId,
buffer: ModelHandle<Buffer>,
buffer: Model<Buffer>,
ranges: impl IntoIterator<Item = (ExcerptId, ExcerptRange<O>)>,
cx: &mut ModelContext<Self>,
) where
@ -1132,7 +1138,7 @@ impl MultiBuffer {
pub fn excerpts_for_buffer(
&self,
buffer: &ModelHandle<Buffer>,
buffer: &Model<Buffer>,
cx: &AppContext,
) -> Vec<(ExcerptId, ExcerptRange<text::Anchor>)> {
let mut excerpts = Vec::new();
@ -1169,7 +1175,7 @@ impl MultiBuffer {
&self,
position: impl ToOffset,
cx: &AppContext,
) -> Option<(ExcerptId, ModelHandle<Buffer>, Range<text::Anchor>)> {
) -> Option<(ExcerptId, Model<Buffer>, Range<text::Anchor>)> {
let snapshot = self.read(cx);
let position = position.to_offset(&snapshot);
@ -1197,7 +1203,7 @@ impl MultiBuffer {
&self,
point: T,
cx: &AppContext,
) -> Option<(ModelHandle<Buffer>, usize, ExcerptId)> {
) -> Option<(Model<Buffer>, usize, ExcerptId)> {
let snapshot = self.read(cx);
let offset = point.to_offset(&snapshot);
let mut cursor = snapshot.excerpts.cursor::<usize>();
@ -1219,7 +1225,7 @@ impl MultiBuffer {
&self,
range: Range<T>,
cx: &AppContext,
) -> Vec<(ModelHandle<Buffer>, Range<usize>, ExcerptId)> {
) -> Vec<(Model<Buffer>, Range<usize>, ExcerptId)> {
let snapshot = self.read(cx);
let start = range.start.to_offset(&snapshot);
let end = range.end.to_offset(&snapshot);
@ -1377,7 +1383,7 @@ impl MultiBuffer {
&self,
position: T,
cx: &AppContext,
) -> Option<(ModelHandle<Buffer>, language::Anchor)> {
) -> Option<(Model<Buffer>, language::Anchor)> {
let snapshot = self.read(cx);
let anchor = snapshot.anchor_before(position);
let buffer = self
@ -1391,7 +1397,7 @@ impl MultiBuffer {
fn on_buffer_event(
&mut self,
_: ModelHandle<Buffer>,
_: Model<Buffer>,
event: &language::Event,
cx: &mut ModelContext<Self>,
) {
@ -1414,7 +1420,7 @@ impl MultiBuffer {
});
}
pub fn all_buffers(&self) -> HashSet<ModelHandle<Buffer>> {
pub fn all_buffers(&self) -> HashSet<Model<Buffer>> {
self.buffers
.borrow()
.values()
@ -1422,7 +1428,7 @@ impl MultiBuffer {
.collect()
}
pub fn buffer(&self, buffer_id: u64) -> Option<ModelHandle<Buffer>> {
pub fn buffer(&self, buffer_id: u64) -> Option<Model<Buffer>> {
self.buffers
.borrow()
.get(&buffer_id)
@ -1487,7 +1493,7 @@ impl MultiBuffer {
language_settings(language.as_ref(), file, cx)
}
pub fn for_each_buffer(&self, mut f: impl FnMut(&ModelHandle<Buffer>)) {
pub fn for_each_buffer(&self, mut f: impl FnMut(&Model<Buffer>)) {
self.buffers
.borrow()
.values()
@ -1642,18 +1648,18 @@ impl MultiBuffer {
#[cfg(any(test, feature = "test-support"))]
impl MultiBuffer {
pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> ModelHandle<Self> {
let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text));
cx.add_model(|cx| Self::singleton(buffer, cx))
pub fn build_simple(text: &str, cx: &mut gpui::AppContext) -> Model<Self> {
let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), text));
cx.new_model(|cx| Self::singleton(buffer, cx))
}
pub fn build_multi<const COUNT: usize>(
excerpts: [(&str, Vec<Range<Point>>); COUNT],
cx: &mut gpui::AppContext,
) -> ModelHandle<Self> {
let multi = cx.add_model(|_| Self::new(0));
) -> Model<Self> {
let multi = cx.new_model(|_| Self::new(0));
for (text, ranges) in excerpts {
let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text));
let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), text));
let excerpt_ranges = ranges.into_iter().map(|range| ExcerptRange {
context: range,
primary: None,
@ -1666,15 +1672,12 @@ impl MultiBuffer {
multi
}
pub fn build_from_buffer(
buffer: ModelHandle<Buffer>,
cx: &mut gpui::AppContext,
) -> ModelHandle<Self> {
cx.add_model(|cx| Self::singleton(buffer, cx))
pub fn build_from_buffer(buffer: Model<Buffer>, cx: &mut gpui::AppContext) -> Model<Self> {
cx.new_model(|cx| Self::singleton(buffer, cx))
}
pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> ModelHandle<Self> {
cx.add_model(|cx| {
pub fn build_random(rng: &mut impl rand::Rng, cx: &mut gpui::AppContext) -> Model<Self> {
cx.new_model(|cx| {
let mut multibuffer = MultiBuffer::new(0);
let mutation_count = rng.gen_range(1..=5);
multibuffer.randomly_edit_excerpts(rng, mutation_count, cx);
@ -1745,7 +1748,7 @@ impl MultiBuffer {
if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
buffers.push(cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, text)));
buffers.push(cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), text)));
let buffer = buffers.last().unwrap().read(cx);
log::info!(
"Creating new buffer {} with text: {:?}",
@ -1868,9 +1871,7 @@ impl MultiBuffer {
}
}
impl Entity for MultiBuffer {
type Event = Event;
}
impl EventEmitter<Event> for MultiBuffer {}
impl MultiBufferSnapshot {
pub fn text(&self) -> String {
@ -3405,7 +3406,7 @@ impl History {
now: Instant,
cx: &mut ModelContext<MultiBuffer>,
) where
T: IntoIterator<Item = (&'a ModelHandle<Buffer>, &'a language::Transaction)>,
T: IntoIterator<Item = (&'a Model<Buffer>, &'a language::Transaction)>,
{
assert_eq!(self.transaction_depth, 0);
let transaction = Transaction {
@ -4131,18 +4132,19 @@ where
mod tests {
use super::*;
use futures::StreamExt;
use gpui::{AppContext, TestAppContext};
use gpui::{AppContext, Context, TestAppContext};
use language::{Buffer, Rope};
use parking_lot::RwLock;
use rand::prelude::*;
use settings::SettingsStore;
use std::{env, rc::Rc};
use std::env;
use util::test::sample_text;
#[gpui::test]
fn test_singleton(cx: &mut AppContext) {
let buffer =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(6, 6, 'a')));
let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(6, 6, 'a')));
let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
let snapshot = multibuffer.read(cx).snapshot(cx);
assert_eq!(snapshot.text(), buffer.read(cx).text());
@ -4168,11 +4170,11 @@ mod tests {
#[gpui::test]
fn test_remote(cx: &mut AppContext) {
let host_buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "a"));
let guest_buffer = cx.add_model(|cx| {
let host_buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "a"));
let guest_buffer = cx.new_model(|cx| {
let state = host_buffer.read(cx).to_proto();
let ops = cx
.background()
.background_executor()
.block(host_buffer.read(cx).serialize_ops(None, cx));
let mut buffer = Buffer::from_proto(1, state, None).unwrap();
buffer
@ -4184,7 +4186,7 @@ mod tests {
.unwrap();
buffer
});
let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(guest_buffer.clone(), cx));
let snapshot = multibuffer.read(cx).snapshot(cx);
assert_eq!(snapshot.text(), "a");
@ -4200,17 +4202,17 @@ mod tests {
#[gpui::test]
fn test_excerpt_boundaries_and_clipping(cx: &mut AppContext) {
let buffer_1 =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(6, 6, 'a')));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(6, 6, 'a')));
let buffer_2 =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(6, 6, 'g')));
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(6, 6, 'g')));
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let events = Rc::new(RefCell::new(Vec::<Event>::new()));
let events = Arc::new(RwLock::new(Vec::<Event>::new()));
multibuffer.update(cx, |_, cx| {
let events = events.clone();
cx.subscribe(&multibuffer, move |_, _, event, _| {
if let Event::Edited { .. } = event {
events.borrow_mut().push(event.clone())
events.write().push(event.clone())
}
})
.detach();
@ -4263,7 +4265,7 @@ mod tests {
// Adding excerpts emits an edited event.
assert_eq!(
events.borrow().as_slice(),
events.read().as_slice(),
&[
Event::Edited {
sigleton_buffer_edited: false
@ -4436,13 +4438,13 @@ mod tests {
#[gpui::test]
fn test_excerpt_events(cx: &mut AppContext) {
let buffer_1 =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(10, 3, 'a')));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(10, 3, 'a')));
let buffer_2 =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(10, 3, 'm')));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(10, 3, 'm')));
let leader_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
let follower_multibuffer = cx.add_model(|_| MultiBuffer::new(0));
let follower_edit_event_count = Rc::new(RefCell::new(0));
let leader_multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let follower_multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let follower_edit_event_count = Arc::new(RwLock::new(0));
follower_multibuffer.update(cx, |_, cx| {
let follower_edit_event_count = follower_edit_event_count.clone();
@ -4456,7 +4458,7 @@ mod tests {
} => follower.insert_excerpts_with_ids_after(predecessor, buffer, excerpts, cx),
Event::ExcerptsRemoved { ids } => follower.remove_excerpts(ids, cx),
Event::Edited { .. } => {
*follower_edit_event_count.borrow_mut() += 1;
*follower_edit_event_count.write() += 1;
}
_ => {}
},
@ -4499,7 +4501,7 @@ mod tests {
leader_multibuffer.read(cx).snapshot(cx).text(),
follower_multibuffer.read(cx).snapshot(cx).text(),
);
assert_eq!(*follower_edit_event_count.borrow(), 2);
assert_eq!(*follower_edit_event_count.read(), 2);
leader_multibuffer.update(cx, |leader, cx| {
let excerpt_ids = leader.excerpt_ids();
@ -4509,7 +4511,7 @@ mod tests {
leader_multibuffer.read(cx).snapshot(cx).text(),
follower_multibuffer.read(cx).snapshot(cx).text(),
);
assert_eq!(*follower_edit_event_count.borrow(), 3);
assert_eq!(*follower_edit_event_count.read(), 3);
// Removing an empty set of excerpts is a noop.
leader_multibuffer.update(cx, |leader, cx| {
@ -4519,7 +4521,7 @@ mod tests {
leader_multibuffer.read(cx).snapshot(cx).text(),
follower_multibuffer.read(cx).snapshot(cx).text(),
);
assert_eq!(*follower_edit_event_count.borrow(), 3);
assert_eq!(*follower_edit_event_count.read(), 3);
// Adding an empty set of excerpts is a noop.
leader_multibuffer.update(cx, |leader, cx| {
@ -4529,7 +4531,7 @@ mod tests {
leader_multibuffer.read(cx).snapshot(cx).text(),
follower_multibuffer.read(cx).snapshot(cx).text(),
);
assert_eq!(*follower_edit_event_count.borrow(), 3);
assert_eq!(*follower_edit_event_count.read(), 3);
leader_multibuffer.update(cx, |leader, cx| {
leader.clear(cx);
@ -4538,14 +4540,14 @@ mod tests {
leader_multibuffer.read(cx).snapshot(cx).text(),
follower_multibuffer.read(cx).snapshot(cx).text(),
);
assert_eq!(*follower_edit_event_count.borrow(), 4);
assert_eq!(*follower_edit_event_count.read(), 4);
}
#[gpui::test]
fn test_push_excerpts_with_context_lines(cx: &mut AppContext) {
let buffer =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(20, 3, 'a')));
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(20, 3, 'a')));
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
multibuffer.push_excerpts_with_context_lines(
buffer.clone(),
@ -4581,8 +4583,8 @@ mod tests {
#[gpui::test]
async fn test_stream_excerpts_with_context_lines(cx: &mut TestAppContext) {
let buffer =
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, sample_text(20, 3, 'a')));
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), sample_text(20, 3, 'a')));
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let anchor_ranges = multibuffer.update(cx, |multibuffer, cx| {
let snapshot = buffer.read(cx);
let ranges = vec![
@ -4596,7 +4598,7 @@ mod tests {
let anchor_ranges = anchor_ranges.collect::<Vec<_>>().await;
let snapshot = multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
let snapshot = multibuffer.update(cx, |multibuffer, cx| multibuffer.snapshot(cx));
assert_eq!(
snapshot.text(),
"bbb\nccc\nddd\neee\nfff\nggg\nhhh\niii\njjj\n\nnnn\nooo\nppp\nqqq\nrrr\n"
@ -4617,7 +4619,7 @@ mod tests {
#[gpui::test]
fn test_empty_multibuffer(cx: &mut AppContext) {
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let snapshot = multibuffer.read(cx).snapshot(cx);
assert_eq!(snapshot.text(), "");
@ -4627,8 +4629,8 @@ mod tests {
#[gpui::test]
fn test_singleton_multibuffer_anchors(cx: &mut AppContext) {
let buffer = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "abcd"));
let multibuffer = cx.add_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
let buffer = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "abcd"));
let multibuffer = cx.new_model(|cx| MultiBuffer::singleton(buffer.clone(), cx));
let old_snapshot = multibuffer.read(cx).snapshot(cx);
buffer.update(cx, |buffer, cx| {
buffer.edit([(0..0, "X")], None, cx);
@ -4647,9 +4649,9 @@ mod tests {
#[gpui::test]
fn test_multibuffer_anchors(cx: &mut AppContext) {
let buffer_1 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "abcd"));
let buffer_2 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "efghi"));
let multibuffer = cx.add_model(|cx| {
let buffer_1 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "abcd"));
let buffer_2 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "efghi"));
let multibuffer = cx.new_model(|cx| {
let mut multibuffer = MultiBuffer::new(0);
multibuffer.push_excerpts(
buffer_1.clone(),
@ -4705,9 +4707,10 @@ mod tests {
#[gpui::test]
fn test_resolving_anchors_after_replacing_their_excerpts(cx: &mut AppContext) {
let buffer_1 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "abcd"));
let buffer_2 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "ABCDEFGHIJKLMNOP"));
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
let buffer_1 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "abcd"));
let buffer_2 =
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "ABCDEFGHIJKLMNOP"));
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
// Create an insertion id in buffer 1 that doesn't exist in buffer 2.
// Add an excerpt from buffer 1 that spans this new insertion.
@ -4840,10 +4843,10 @@ mod tests {
.map(|i| i.parse().expect("invalid `OPERATIONS` variable"))
.unwrap_or(10);
let mut buffers: Vec<ModelHandle<Buffer>> = Vec::new();
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
let mut buffers: Vec<Model<Buffer>> = Vec::new();
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let mut excerpt_ids = Vec::<ExcerptId>::new();
let mut expected_excerpts = Vec::<(ModelHandle<Buffer>, Range<text::Anchor>)>::new();
let mut expected_excerpts = Vec::<(Model<Buffer>, Range<text::Anchor>)>::new();
let mut anchors = Vec::new();
let mut old_versions = Vec::new();
@ -4918,7 +4921,7 @@ mod tests {
.take(10)
.collect::<String>();
buffers.push(
cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, base_text)),
cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), base_text)),
);
buffers.last().unwrap()
} else {
@ -5258,11 +5261,12 @@ mod tests {
#[gpui::test]
fn test_history(cx: &mut AppContext) {
cx.set_global(SettingsStore::test(cx));
let test_settings = SettingsStore::test(cx);
cx.set_global(test_settings);
let buffer_1 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "1234"));
let buffer_2 = cx.add_model(|cx| Buffer::new(0, cx.model_id() as u64, "5678"));
let multibuffer = cx.add_model(|_| MultiBuffer::new(0));
let buffer_1 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "1234"));
let buffer_2 = cx.new_model(|cx| Buffer::new(0, cx.entity_id().as_u64(), "5678"));
let multibuffer = cx.new_model(|_| MultiBuffer::new(0));
let group_interval = multibuffer.read(cx).history.group_interval;
multibuffer.update(cx, |multibuffer, cx| {
multibuffer.push_excerpts(

View File

@ -1,78 +0,0 @@
[package]
name = "multi_buffer2"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/multi_buffer2.rs"
doctest = false
[features]
test-support = [
"copilot/test-support",
"text/test-support",
"language/test-support",
"gpui/test-support",
"util/test-support",
"tree-sitter-rust",
"tree-sitter-typescript"
]
[dependencies]
client = { package = "client2", path = "../client2" }
clock = { path = "../clock" }
collections = { path = "../collections" }
git = { package = "git3", path = "../git3" }
gpui = { package = "gpui2", path = "../gpui2" }
language = { package = "language2", path = "../language2" }
lsp = { package = "lsp2", path = "../lsp2" }
rich_text = { package = "rich_text2", path = "../rich_text2" }
settings = { package = "settings2", path = "../settings2" }
snippet = { path = "../snippet" }
sum_tree = { path = "../sum_tree" }
text = { package = "text2", path = "../text2" }
theme = { package = "theme2", path = "../theme2" }
util = { path = "../util" }
aho-corasick = "1.1"
anyhow.workspace = true
convert_case = "0.6.0"
futures.workspace = true
indoc = "1.0.4"
itertools = "0.10"
lazy_static.workspace = true
log.workspace = true
ordered-float.workspace = true
parking_lot.workspace = true
postage.workspace = true
pulldown-cmark = { version = "0.9.2", default-features = false }
rand.workspace = true
schemars.workspace = true
serde.workspace = true
serde_derive.workspace = true
smallvec.workspace = true
smol.workspace = true
tree-sitter-rust = { workspace = true, optional = true }
tree-sitter-html = { workspace = true, optional = true }
tree-sitter-typescript = { workspace = true, optional = true }
[dev-dependencies]
copilot = { package = "copilot2", path = "../copilot2", features = ["test-support"] }
text = { package = "text2", path = "../text2", features = ["test-support"] }
language = { package = "language2", path = "../language2", features = ["test-support"] }
lsp = { package = "lsp2", path = "../lsp2", features = ["test-support"] }
gpui = { package = "gpui2", path = "../gpui2", features = ["test-support"] }
util = { path = "../util", features = ["test-support"] }
project = { package = "project2", path = "../project2", features = ["test-support"] }
settings = { package = "settings2", path = "../settings2", features = ["test-support"] }
ctor.workspace = true
env_logger.workspace = true
rand.workspace = true
unindent.workspace = true
tree-sitter.workspace = true
tree-sitter-rust.workspace = true
tree-sitter-html.workspace = true
tree-sitter-typescript.workspace = true

View File

@ -1,138 +0,0 @@
use super::{ExcerptId, MultiBufferSnapshot, ToOffset, ToOffsetUtf16, ToPoint};
use language::{OffsetUtf16, Point, TextDimension};
use std::{
cmp::Ordering,
ops::{Range, Sub},
};
use sum_tree::Bias;
#[derive(Clone, Copy, Eq, PartialEq, Debug, Hash)]
pub struct Anchor {
pub buffer_id: Option<u64>,
pub excerpt_id: ExcerptId,
pub text_anchor: text::Anchor,
}
impl Anchor {
pub fn min() -> Self {
Self {
buffer_id: None,
excerpt_id: ExcerptId::min(),
text_anchor: text::Anchor::MIN,
}
}
pub fn max() -> Self {
Self {
buffer_id: None,
excerpt_id: ExcerptId::max(),
text_anchor: text::Anchor::MAX,
}
}
pub fn cmp(&self, other: &Anchor, snapshot: &MultiBufferSnapshot) -> Ordering {
let excerpt_id_cmp = self.excerpt_id.cmp(&other.excerpt_id, snapshot);
if excerpt_id_cmp.is_eq() {
if self.excerpt_id == ExcerptId::min() || self.excerpt_id == ExcerptId::max() {
Ordering::Equal
} else if let Some(excerpt) = snapshot.excerpt(self.excerpt_id) {
self.text_anchor.cmp(&other.text_anchor, &excerpt.buffer)
} else {
Ordering::Equal
}
} else {
excerpt_id_cmp
}
}
pub fn bias(&self) -> Bias {
self.text_anchor.bias
}
pub fn bias_left(&self, snapshot: &MultiBufferSnapshot) -> Anchor {
if self.text_anchor.bias != Bias::Left {
if let Some(excerpt) = snapshot.excerpt(self.excerpt_id) {
return Self {
buffer_id: self.buffer_id,
excerpt_id: self.excerpt_id.clone(),
text_anchor: self.text_anchor.bias_left(&excerpt.buffer),
};
}
}
self.clone()
}
pub fn bias_right(&self, snapshot: &MultiBufferSnapshot) -> Anchor {
if self.text_anchor.bias != Bias::Right {
if let Some(excerpt) = snapshot.excerpt(self.excerpt_id) {
return Self {
buffer_id: self.buffer_id,
excerpt_id: self.excerpt_id.clone(),
text_anchor: self.text_anchor.bias_right(&excerpt.buffer),
};
}
}
self.clone()
}
pub fn summary<D>(&self, snapshot: &MultiBufferSnapshot) -> D
where
D: TextDimension + Ord + Sub<D, Output = D>,
{
snapshot.summary_for_anchor(self)
}
pub fn is_valid(&self, snapshot: &MultiBufferSnapshot) -> bool {
if *self == Anchor::min() || *self == Anchor::max() {
true
} else if let Some(excerpt) = snapshot.excerpt(self.excerpt_id) {
excerpt.contains(self)
&& (self.text_anchor == excerpt.range.context.start
|| self.text_anchor == excerpt.range.context.end
|| self.text_anchor.is_valid(&excerpt.buffer))
} else {
false
}
}
}
impl ToOffset for Anchor {
fn to_offset(&self, snapshot: &MultiBufferSnapshot) -> usize {
self.summary(snapshot)
}
}
impl ToOffsetUtf16 for Anchor {
fn to_offset_utf16(&self, snapshot: &MultiBufferSnapshot) -> OffsetUtf16 {
self.summary(snapshot)
}
}
impl ToPoint for Anchor {
fn to_point<'a>(&self, snapshot: &MultiBufferSnapshot) -> Point {
self.summary(snapshot)
}
}
pub trait AnchorRangeExt {
fn cmp(&self, b: &Range<Anchor>, buffer: &MultiBufferSnapshot) -> Ordering;
fn to_offset(&self, content: &MultiBufferSnapshot) -> Range<usize>;
fn to_point(&self, content: &MultiBufferSnapshot) -> Range<Point>;
}
impl AnchorRangeExt for Range<Anchor> {
fn cmp(&self, other: &Range<Anchor>, buffer: &MultiBufferSnapshot) -> Ordering {
match self.start.cmp(&other.start, buffer) {
Ordering::Equal => other.end.cmp(&self.end, buffer),
ord => ord,
}
}
fn to_offset(&self, content: &MultiBufferSnapshot) -> Range<usize> {
self.start.to_offset(content)..self.end.to_offset(content)
}
fn to_point(&self, content: &MultiBufferSnapshot) -> Range<Point> {
self.start.to_point(content)..self.end.to_point(content)
}
}

File diff suppressed because it is too large Load Diff

View File

@ -10,14 +10,16 @@ doctest = false
[dependencies]
editor = { path = "../editor" }
fuzzy = { path = "../fuzzy" }
gpui = { path = "../gpui" }
language = { path = "../language" }
fuzzy = { package = "fuzzy2", path = "../fuzzy2" }
gpui = { package = "gpui2", path = "../gpui2" }
ui = { package = "ui2", path = "../ui2" }
language = { package = "language2", path = "../language2" }
picker = { path = "../picker" }
settings = { path = "../settings" }
text = { path = "../text" }
theme = { path = "../theme" }
workspace = { path = "../workspace" }
settings = { package = "settings2", path = "../settings2" }
text = { package = "text2", path = "../text2" }
theme = { package = "theme2", path = "../theme2" }
workspace = { package = "workspace2", path = "../workspace2" }
util = { path = "../util" }
ordered-float.workspace = true
postage.workspace = true

View File

@ -1,68 +1,109 @@
use editor::{
combine_syntax_and_fuzzy_match_highlights, display_map::ToDisplayPoint,
scroll::autoscroll::Autoscroll, Anchor, AnchorRangeExt, DisplayPoint, Editor, ToPoint,
display_map::ToDisplayPoint, scroll::autoscroll::Autoscroll, Anchor, AnchorRangeExt,
DisplayPoint, Editor, EditorMode, ToPoint,
};
use fuzzy::StringMatch;
use gpui::{
actions, elements::*, geometry::vector::Vector2F, AppContext, MouseState, Task, ViewContext,
ViewHandle, WindowContext,
actions, div, rems, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
FontStyle, FontWeight, HighlightStyle, ParentElement, Point, Render, Styled, StyledText, Task,
TextStyle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
};
use language::Outline;
use ordered_float::OrderedFloat;
use picker::{Picker, PickerDelegate, PickerEvent};
use picker::{Picker, PickerDelegate};
use settings::Settings;
use std::{
cmp::{self, Reverse},
sync::Arc,
};
use workspace::Workspace;
use theme::{color_alpha, ActiveTheme, ThemeSettings};
use ui::{prelude::*, ListItem, ListItemSpacing};
use util::ResultExt;
use workspace::ModalView;
actions!(outline, [Toggle]);
pub fn init(cx: &mut AppContext) {
cx.add_action(toggle);
OutlineView::init(cx);
cx.observe_new_views(OutlineView::register).detach();
}
pub fn toggle(workspace: &mut Workspace, _: &Toggle, cx: &mut ViewContext<Workspace>) {
if let Some(editor) = workspace
.active_item(cx)
.and_then(|item| item.downcast::<Editor>())
{
let outline = editor
.read(cx)
.buffer()
.read(cx)
.snapshot(cx)
.outline(Some(theme::current(cx).editor.syntax.as_ref()));
if let Some(outline) = outline {
workspace.toggle_modal(cx, |_, cx| {
cx.add_view(|cx| {
OutlineView::new(OutlineViewDelegate::new(outline, editor, cx), cx)
.with_max_size(800., 1200.)
})
});
}
pub fn toggle(editor: View<Editor>, _: &Toggle, cx: &mut WindowContext) {
let outline = editor
.read(cx)
.buffer()
.read(cx)
.snapshot(cx)
.outline(Some(&cx.theme().syntax()));
if let Some((workspace, outline)) = editor.read(cx).workspace().zip(outline) {
workspace.update(cx, |workspace, cx| {
workspace.toggle_modal(cx, |cx| OutlineView::new(outline, editor, cx));
})
}
}
type OutlineView = Picker<OutlineViewDelegate>;
pub struct OutlineView {
picker: View<Picker<OutlineViewDelegate>>,
}
impl FocusableView for OutlineView {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
self.picker.focus_handle(cx)
}
}
impl EventEmitter<DismissEvent> for OutlineView {}
impl ModalView for OutlineView {}
impl Render for OutlineView {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
v_stack().w(rems(34.)).child(self.picker.clone())
}
}
impl OutlineView {
fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
if editor.mode() == EditorMode::Full {
let handle = cx.view().downgrade();
editor.register_action(move |action, cx| {
if let Some(editor) = handle.upgrade() {
toggle(editor, action, cx);
}
});
}
}
fn new(
outline: Outline<Anchor>,
editor: View<Editor>,
cx: &mut ViewContext<Self>,
) -> OutlineView {
let delegate = OutlineViewDelegate::new(cx.view().downgrade(), outline, editor, cx);
let picker = cx.new_view(|cx| Picker::new(delegate, cx).max_height(vh(0.75, cx)));
OutlineView { picker }
}
}
struct OutlineViewDelegate {
active_editor: ViewHandle<Editor>,
outline_view: WeakView<OutlineView>,
active_editor: View<Editor>,
outline: Outline<Anchor>,
selected_match_index: usize,
prev_scroll_position: Option<Vector2F>,
prev_scroll_position: Option<Point<f32>>,
matches: Vec<StringMatch>,
last_query: String,
}
impl OutlineViewDelegate {
fn new(
outline_view: WeakView<OutlineView>,
outline: Outline<Anchor>,
editor: ViewHandle<Editor>,
editor: View<Editor>,
cx: &mut ViewContext<OutlineView>,
) -> Self {
Self {
outline_view,
last_query: Default::default(),
matches: Default::default(),
selected_match_index: 0,
@ -81,11 +122,18 @@ impl OutlineViewDelegate {
})
}
fn set_selected_index(&mut self, ix: usize, navigate: bool, cx: &mut ViewContext<OutlineView>) {
fn set_selected_index(
&mut self,
ix: usize,
navigate: bool,
cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
) {
self.selected_match_index = ix;
if navigate && !self.matches.is_empty() {
let selected_match = &self.matches[self.selected_match_index];
let outline_item = &self.outline.items[selected_match.candidate_id];
self.active_editor.update(cx, |active_editor, cx| {
let snapshot = active_editor.snapshot(cx).display_snapshot;
let buffer_snapshot = &snapshot.buffer_snapshot;
@ -101,6 +149,8 @@ impl OutlineViewDelegate {
}
impl PickerDelegate for OutlineViewDelegate {
type ListItem = ListItem;
fn placeholder_text(&self) -> Arc<str> {
"Search buffer symbols...".into()
}
@ -113,15 +163,15 @@ impl PickerDelegate for OutlineViewDelegate {
self.selected_match_index
}
fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<OutlineView>) {
fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
self.set_selected_index(ix, true, cx);
}
fn center_selection_after_match_updates(&self) -> bool {
true
}
fn update_matches(&mut self, query: String, cx: &mut ViewContext<OutlineView>) -> Task<()> {
fn update_matches(
&mut self,
query: String,
cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
) -> Task<()> {
let selected_index;
if query.is_empty() {
self.restore_active_editor(cx);
@ -163,7 +213,10 @@ impl PickerDelegate for OutlineViewDelegate {
.map(|(ix, _, _)| ix)
.unwrap_or(0);
} else {
self.matches = smol::block_on(self.outline.search(&query, cx.background().clone()));
self.matches = smol::block_on(
self.outline
.search(&query, cx.background_executor().clone()),
);
selected_index = self
.matches
.iter()
@ -177,8 +230,9 @@ impl PickerDelegate for OutlineViewDelegate {
Task::ready(())
}
fn confirm(&mut self, _: bool, cx: &mut ViewContext<OutlineView>) {
fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
self.prev_scroll_position.take();
self.active_editor.update(cx, |active_editor, cx| {
if let Some(rows) = active_editor.highlighted_rows() {
let snapshot = active_editor.snapshot(cx).display_snapshot;
@ -187,39 +241,69 @@ impl PickerDelegate for OutlineViewDelegate {
s.select_ranges([position..position])
});
active_editor.highlight_rows(None);
active_editor.focus(cx);
}
});
cx.emit(PickerEvent::Dismiss);
self.dismissed(cx);
}
fn dismissed(&mut self, cx: &mut ViewContext<OutlineView>) {
fn dismissed(&mut self, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
self.outline_view
.update(cx, |_, cx| cx.emit(DismissEvent))
.log_err();
self.restore_active_editor(cx);
}
fn render_match(
&self,
ix: usize,
mouse_state: &mut MouseState,
selected: bool,
cx: &AppContext,
) -> AnyElement<Picker<Self>> {
let theme = theme::current(cx);
let style = theme.picker.item.in_state(selected).style_for(mouse_state);
let string_match = &self.matches[ix];
let outline_item = &self.outline.items[string_match.candidate_id];
cx: &mut ViewContext<Picker<Self>>,
) -> Option<Self::ListItem> {
let settings = ThemeSettings::get_global(cx);
Text::new(outline_item.text.clone(), style.label.text.clone())
.with_soft_wrap(false)
.with_highlights(combine_syntax_and_fuzzy_match_highlights(
&outline_item.text,
style.label.text.clone().into(),
outline_item.highlight_ranges.iter().cloned(),
&string_match.positions,
))
.contained()
.with_padding_left(20. * outline_item.depth as f32)
.contained()
.with_style(style.container)
.into_any()
// TODO: We probably shouldn't need to build a whole new text style here
// but I'm not sure how to get the current one and modify it.
// Before this change TextStyle::default() was used here, which was giving us the wrong font and text color.
let text_style = TextStyle {
color: cx.theme().colors().text,
font_family: settings.buffer_font.family.clone(),
font_features: settings.buffer_font.features,
font_size: settings.buffer_font_size(cx).into(),
font_weight: FontWeight::NORMAL,
font_style: FontStyle::Normal,
line_height: relative(1.).into(),
background_color: None,
underline: None,
white_space: WhiteSpace::Normal,
};
let mut highlight_style = HighlightStyle::default();
highlight_style.background_color = Some(color_alpha(cx.theme().colors().text_accent, 0.3));
let mat = &self.matches[ix];
let outline_item = &self.outline.items[mat.candidate_id];
let highlights = gpui::combine_highlights(
mat.ranges().map(|range| (range, highlight_style)),
outline_item.highlight_ranges.iter().cloned(),
);
let styled_text =
StyledText::new(outline_item.text.clone()).with_highlights(&text_style, highlights);
Some(
ListItem::new(ix)
.inset(true)
.spacing(ListItemSpacing::Sparse)
.selected(selected)
.child(
div()
.text_ui()
.pl(rems(outline_item.depth as f32))
.child(styled_text),
),
)
}
}

View File

@ -1,29 +0,0 @@
[package]
name = "outline2"
version = "0.1.0"
edition = "2021"
publish = false
[lib]
path = "src/outline.rs"
doctest = false
[dependencies]
editor = { path = "../editor" }
fuzzy = { package = "fuzzy2", path = "../fuzzy2" }
gpui = { package = "gpui2", path = "../gpui2" }
ui = { package = "ui2", path = "../ui2" }
language = { package = "language2", path = "../language2" }
picker = { path = "../picker" }
settings = { package = "settings2", path = "../settings2" }
text = { package = "text2", path = "../text2" }
theme = { package = "theme2", path = "../theme2" }
workspace = { package = "workspace2", path = "../workspace2" }
util = { path = "../util" }
ordered-float.workspace = true
postage.workspace = true
smol.workspace = true
[dev-dependencies]
editor = { path = "../editor", features = ["test-support"] }

View File

@ -1,309 +0,0 @@
use editor::{
display_map::ToDisplayPoint, scroll::autoscroll::Autoscroll, Anchor, AnchorRangeExt,
DisplayPoint, Editor, EditorMode, ToPoint,
};
use fuzzy::StringMatch;
use gpui::{
actions, div, rems, AppContext, DismissEvent, EventEmitter, FocusHandle, FocusableView,
FontStyle, FontWeight, HighlightStyle, ParentElement, Point, Render, Styled, StyledText, Task,
TextStyle, View, ViewContext, VisualContext, WeakView, WhiteSpace, WindowContext,
};
use language::Outline;
use ordered_float::OrderedFloat;
use picker::{Picker, PickerDelegate};
use settings::Settings;
use std::{
cmp::{self, Reverse},
sync::Arc,
};
use theme::{color_alpha, ActiveTheme, ThemeSettings};
use ui::{prelude::*, ListItem, ListItemSpacing};
use util::ResultExt;
use workspace::ModalView;
actions!(outline, [Toggle]);
pub fn init(cx: &mut AppContext) {
cx.observe_new_views(OutlineView::register).detach();
}
pub fn toggle(editor: View<Editor>, _: &Toggle, cx: &mut WindowContext) {
let outline = editor
.read(cx)
.buffer()
.read(cx)
.snapshot(cx)
.outline(Some(&cx.theme().syntax()));
if let Some((workspace, outline)) = editor.read(cx).workspace().zip(outline) {
workspace.update(cx, |workspace, cx| {
workspace.toggle_modal(cx, |cx| OutlineView::new(outline, editor, cx));
})
}
}
pub struct OutlineView {
picker: View<Picker<OutlineViewDelegate>>,
}
impl FocusableView for OutlineView {
fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
self.picker.focus_handle(cx)
}
}
impl EventEmitter<DismissEvent> for OutlineView {}
impl ModalView for OutlineView {}
impl Render for OutlineView {
fn render(&mut self, _cx: &mut ViewContext<Self>) -> impl IntoElement {
v_stack().w(rems(34.)).child(self.picker.clone())
}
}
impl OutlineView {
fn register(editor: &mut Editor, cx: &mut ViewContext<Editor>) {
if editor.mode() == EditorMode::Full {
let handle = cx.view().downgrade();
editor.register_action(move |action, cx| {
if let Some(editor) = handle.upgrade() {
toggle(editor, action, cx);
}
});
}
}
fn new(
outline: Outline<Anchor>,
editor: View<Editor>,
cx: &mut ViewContext<Self>,
) -> OutlineView {
let delegate = OutlineViewDelegate::new(cx.view().downgrade(), outline, editor, cx);
let picker = cx.new_view(|cx| Picker::new(delegate, cx).max_height(vh(0.75, cx)));
OutlineView { picker }
}
}
struct OutlineViewDelegate {
outline_view: WeakView<OutlineView>,
active_editor: View<Editor>,
outline: Outline<Anchor>,
selected_match_index: usize,
prev_scroll_position: Option<Point<f32>>,
matches: Vec<StringMatch>,
last_query: String,
}
impl OutlineViewDelegate {
fn new(
outline_view: WeakView<OutlineView>,
outline: Outline<Anchor>,
editor: View<Editor>,
cx: &mut ViewContext<OutlineView>,
) -> Self {
Self {
outline_view,
last_query: Default::default(),
matches: Default::default(),
selected_match_index: 0,
prev_scroll_position: Some(editor.update(cx, |editor, cx| editor.scroll_position(cx))),
active_editor: editor,
outline,
}
}
fn restore_active_editor(&mut self, cx: &mut WindowContext) {
self.active_editor.update(cx, |editor, cx| {
editor.highlight_rows(None);
if let Some(scroll_position) = self.prev_scroll_position {
editor.set_scroll_position(scroll_position, cx);
}
})
}
fn set_selected_index(
&mut self,
ix: usize,
navigate: bool,
cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
) {
self.selected_match_index = ix;
if navigate && !self.matches.is_empty() {
let selected_match = &self.matches[self.selected_match_index];
let outline_item = &self.outline.items[selected_match.candidate_id];
self.active_editor.update(cx, |active_editor, cx| {
let snapshot = active_editor.snapshot(cx).display_snapshot;
let buffer_snapshot = &snapshot.buffer_snapshot;
let start = outline_item.range.start.to_point(buffer_snapshot);
let end = outline_item.range.end.to_point(buffer_snapshot);
let display_rows = start.to_display_point(&snapshot).row()
..end.to_display_point(&snapshot).row() + 1;
active_editor.highlight_rows(Some(display_rows));
active_editor.request_autoscroll(Autoscroll::center(), cx);
});
}
}
}
impl PickerDelegate for OutlineViewDelegate {
type ListItem = ListItem;
fn placeholder_text(&self) -> Arc<str> {
"Search buffer symbols...".into()
}
fn match_count(&self) -> usize {
self.matches.len()
}
fn selected_index(&self) -> usize {
self.selected_match_index
}
fn set_selected_index(&mut self, ix: usize, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
self.set_selected_index(ix, true, cx);
}
fn update_matches(
&mut self,
query: String,
cx: &mut ViewContext<Picker<OutlineViewDelegate>>,
) -> Task<()> {
let selected_index;
if query.is_empty() {
self.restore_active_editor(cx);
self.matches = self
.outline
.items
.iter()
.enumerate()
.map(|(index, _)| StringMatch {
candidate_id: index,
score: Default::default(),
positions: Default::default(),
string: Default::default(),
})
.collect();
let editor = self.active_editor.read(cx);
let cursor_offset = editor.selections.newest::<usize>(cx).head();
let buffer = editor.buffer().read(cx).snapshot(cx);
selected_index = self
.outline
.items
.iter()
.enumerate()
.map(|(ix, item)| {
let range = item.range.to_offset(&buffer);
let distance_to_closest_endpoint = cmp::min(
(range.start as isize - cursor_offset as isize).abs(),
(range.end as isize - cursor_offset as isize).abs(),
);
let depth = if range.contains(&cursor_offset) {
Some(item.depth)
} else {
None
};
(ix, depth, distance_to_closest_endpoint)
})
.max_by_key(|(_, depth, distance)| (*depth, Reverse(*distance)))
.map(|(ix, _, _)| ix)
.unwrap_or(0);
} else {
self.matches = smol::block_on(
self.outline
.search(&query, cx.background_executor().clone()),
);
selected_index = self
.matches
.iter()
.enumerate()
.max_by_key(|(_, m)| OrderedFloat(m.score))
.map(|(ix, _)| ix)
.unwrap_or(0);
}
self.last_query = query;
self.set_selected_index(selected_index, !self.last_query.is_empty(), cx);
Task::ready(())
}
fn confirm(&mut self, _: bool, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
self.prev_scroll_position.take();
self.active_editor.update(cx, |active_editor, cx| {
if let Some(rows) = active_editor.highlighted_rows() {
let snapshot = active_editor.snapshot(cx).display_snapshot;
let position = DisplayPoint::new(rows.start, 0).to_point(&snapshot);
active_editor.change_selections(Some(Autoscroll::center()), cx, |s| {
s.select_ranges([position..position])
});
active_editor.highlight_rows(None);
active_editor.focus(cx);
}
});
self.dismissed(cx);
}
fn dismissed(&mut self, cx: &mut ViewContext<Picker<OutlineViewDelegate>>) {
self.outline_view
.update(cx, |_, cx| cx.emit(DismissEvent))
.log_err();
self.restore_active_editor(cx);
}
fn render_match(
&self,
ix: usize,
selected: bool,
cx: &mut ViewContext<Picker<Self>>,
) -> Option<Self::ListItem> {
let settings = ThemeSettings::get_global(cx);
// TODO: We probably shouldn't need to build a whole new text style here
// but I'm not sure how to get the current one and modify it.
// Before this change TextStyle::default() was used here, which was giving us the wrong font and text color.
let text_style = TextStyle {
color: cx.theme().colors().text,
font_family: settings.buffer_font.family.clone(),
font_features: settings.buffer_font.features,
font_size: settings.buffer_font_size(cx).into(),
font_weight: FontWeight::NORMAL,
font_style: FontStyle::Normal,
line_height: relative(1.).into(),
background_color: None,
underline: None,
white_space: WhiteSpace::Normal,
};
let mut highlight_style = HighlightStyle::default();
highlight_style.background_color = Some(color_alpha(cx.theme().colors().text_accent, 0.3));
let mat = &self.matches[ix];
let outline_item = &self.outline.items[mat.candidate_id];
let highlights = gpui::combine_highlights(
mat.ranges().map(|range| (range, highlight_style)),
outline_item.highlight_ranges.iter().cloned(),
);
let styled_text =
StyledText::new(outline_item.text.clone()).with_highlights(&text_style, highlights);
Some(
ListItem::new(ix)
.inset(true)
.spacing(ListItemSpacing::Sparse)
.selected(selected)
.child(
div()
.text_ui()
.pl(rems(outline_item.depth as f32))
.child(styled_text),
),
)
}
}

View File

@ -21,7 +21,7 @@ test-support = [
[dependencies]
text = { package = "text2", path = "../text2" }
copilot = { package = "copilot2", path = "../copilot2" }
copilot = { path = "../copilot" }
client = { package = "client2", path = "../client2" }
clock = { path = "../clock" }
collections = { path = "../collections" }

View File

@ -29,7 +29,7 @@ command_palette = { path = "../command_palette" }
# component_test = { path = "../component_test" }
client = { package = "client2", path = "../client2" }
# clock = { path = "../clock" }
copilot = { package = "copilot2", path = "../copilot2" }
copilot = { path = "../copilot" }
copilot_button = { path = "../copilot_button" }
diagnostics = { path = "../diagnostics" }
db = { package = "db2", path = "../db2" }
@ -51,7 +51,7 @@ language_tools = { path = "../language_tools" }
node_runtime = { path = "../node_runtime" }
notifications = { package = "notifications2", path = "../notifications2" }
assistant = { package = "assistant2", path = "../assistant2" }
outline = { package = "outline2", path = "../outline2" }
outline = { path = "../outline" }
# plugin_runtime = { path = "../plugin_runtime",optional = true }
project = { package = "project2", path = "../project2" }
project_panel = { path = "../project_panel" }