project.rs

   1pub mod fs;
   2mod ignore;
   3mod lsp_command;
   4pub mod search;
   5pub mod worktree;
   6
   7use anyhow::{anyhow, Context, Result};
   8use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
   9use clock::ReplicaId;
  10use collections::{hash_map, BTreeMap, HashMap, HashSet};
  11use futures::{future::Shared, Future, FutureExt, StreamExt, TryFutureExt};
  12use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
  13use gpui::{
  14    AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
  15    MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
  16};
  17use language::{
  18    point_to_lsp,
  19    proto::{deserialize_anchor, deserialize_version, serialize_anchor, serialize_version},
  20    range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CodeAction, CodeLabel, Completion,
  21    Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _, Language,
  22    LanguageRegistry, LanguageServerName, LocalFile, LspAdapter, OffsetRangeExt, Operation, Patch,
  23    PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
  24};
  25use lsp::{DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer};
  26use lsp_command::*;
  27use parking_lot::Mutex;
  28use postage::watch;
  29use rand::prelude::*;
  30use search::SearchQuery;
  31use serde::Serialize;
  32use settings::Settings;
  33use sha2::{Digest, Sha256};
  34use similar::{ChangeTag, TextDiff};
  35use std::{
  36    cell::RefCell,
  37    cmp::{self, Ordering},
  38    convert::TryInto,
  39    ffi::OsString,
  40    hash::Hash,
  41    mem,
  42    ops::Range,
  43    os::unix::{ffi::OsStrExt, prelude::OsStringExt},
  44    path::{Component, Path, PathBuf},
  45    rc::Rc,
  46    sync::{
  47        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
  48        Arc,
  49    },
  50    time::Instant,
  51};
  52use thiserror::Error;
  53use util::{post_inc, ResultExt, TryFutureExt as _};
  54
  55pub use fs::*;
  56pub use worktree::*;
  57
  58pub trait Item: Entity {
  59    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  60}
  61
  62pub struct Project {
  63    worktrees: Vec<WorktreeHandle>,
  64    active_entry: Option<ProjectEntryId>,
  65    languages: Arc<LanguageRegistry>,
  66    language_servers:
  67        HashMap<(WorktreeId, LanguageServerName), (Arc<dyn LspAdapter>, Arc<LanguageServer>)>,
  68    started_language_servers:
  69        HashMap<(WorktreeId, LanguageServerName), Task<Option<Arc<LanguageServer>>>>,
  70    language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
  71    language_server_settings: Arc<Mutex<serde_json::Value>>,
  72    last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
  73    next_language_server_id: usize,
  74    client: Arc<client::Client>,
  75    next_entry_id: Arc<AtomicUsize>,
  76    user_store: ModelHandle<UserStore>,
  77    fs: Arc<dyn Fs>,
  78    client_state: ProjectClientState,
  79    collaborators: HashMap<PeerId, Collaborator>,
  80    subscriptions: Vec<client::Subscription>,
  81    opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
  82    shared_buffers: HashMap<PeerId, HashSet<u64>>,
  83    loading_buffers: HashMap<
  84        ProjectPath,
  85        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
  86    >,
  87    loading_local_worktrees:
  88        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
  89    opened_buffers: HashMap<u64, OpenBuffer>,
  90    buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
  91    nonce: u128,
  92}
  93
  94#[derive(Error, Debug)]
  95pub enum JoinProjectError {
  96    #[error("host declined join request")]
  97    HostDeclined,
  98    #[error("host closed the project")]
  99    HostClosedProject,
 100    #[error("host went offline")]
 101    HostWentOffline,
 102    #[error("{0}")]
 103    Other(#[from] anyhow::Error),
 104}
 105
 106enum OpenBuffer {
 107    Strong(ModelHandle<Buffer>),
 108    Weak(WeakModelHandle<Buffer>),
 109    Loading(Vec<Operation>),
 110}
 111
 112enum WorktreeHandle {
 113    Strong(ModelHandle<Worktree>),
 114    Weak(WeakModelHandle<Worktree>),
 115}
 116
 117enum ProjectClientState {
 118    Local {
 119        is_shared: bool,
 120        remote_id_tx: watch::Sender<Option<u64>>,
 121        remote_id_rx: watch::Receiver<Option<u64>>,
 122        _maintain_remote_id_task: Task<Option<()>>,
 123    },
 124    Remote {
 125        sharing_has_stopped: bool,
 126        remote_id: u64,
 127        replica_id: ReplicaId,
 128        _detect_unshare_task: Task<Option<()>>,
 129    },
 130}
 131
 132#[derive(Clone, Debug)]
 133pub struct Collaborator {
 134    pub user: Arc<User>,
 135    pub peer_id: PeerId,
 136    pub replica_id: ReplicaId,
 137}
 138
 139#[derive(Clone, Debug, PartialEq, Eq)]
 140pub enum Event {
 141    ActiveEntryChanged(Option<ProjectEntryId>),
 142    WorktreeAdded,
 143    WorktreeRemoved(WorktreeId),
 144    DiskBasedDiagnosticsStarted,
 145    DiskBasedDiagnosticsUpdated,
 146    DiskBasedDiagnosticsFinished,
 147    DiagnosticsUpdated(ProjectPath),
 148    RemoteIdChanged(Option<u64>),
 149    CollaboratorLeft(PeerId),
 150    ContactRequestedJoin(Arc<User>),
 151    ContactCancelledJoinRequest(Arc<User>),
 152}
 153
 154#[derive(Serialize)]
 155pub struct LanguageServerStatus {
 156    pub name: String,
 157    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 158    pub pending_diagnostic_updates: isize,
 159}
 160
 161#[derive(Clone, Debug, Serialize)]
 162pub struct LanguageServerProgress {
 163    pub message: Option<String>,
 164    pub percentage: Option<usize>,
 165    #[serde(skip_serializing)]
 166    pub last_update_at: Instant,
 167}
 168
 169#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 170pub struct ProjectPath {
 171    pub worktree_id: WorktreeId,
 172    pub path: Arc<Path>,
 173}
 174
 175#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 176pub struct DiagnosticSummary {
 177    pub error_count: usize,
 178    pub warning_count: usize,
 179}
 180
 181#[derive(Debug)]
 182pub struct Location {
 183    pub buffer: ModelHandle<Buffer>,
 184    pub range: Range<language::Anchor>,
 185}
 186
 187#[derive(Debug)]
 188pub struct DocumentHighlight {
 189    pub range: Range<language::Anchor>,
 190    pub kind: DocumentHighlightKind,
 191}
 192
 193#[derive(Clone, Debug)]
 194pub struct Symbol {
 195    pub source_worktree_id: WorktreeId,
 196    pub worktree_id: WorktreeId,
 197    pub language_server_name: LanguageServerName,
 198    pub path: PathBuf,
 199    pub label: CodeLabel,
 200    pub name: String,
 201    pub kind: lsp::SymbolKind,
 202    pub range: Range<PointUtf16>,
 203    pub signature: [u8; 32],
 204}
 205
 206#[derive(Default)]
 207pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 208
 209impl DiagnosticSummary {
 210    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 211        let mut this = Self {
 212            error_count: 0,
 213            warning_count: 0,
 214        };
 215
 216        for entry in diagnostics {
 217            if entry.diagnostic.is_primary {
 218                match entry.diagnostic.severity {
 219                    DiagnosticSeverity::ERROR => this.error_count += 1,
 220                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 221                    _ => {}
 222                }
 223            }
 224        }
 225
 226        this
 227    }
 228
 229    pub fn is_empty(&self) -> bool {
 230        self.error_count == 0 && self.warning_count == 0
 231    }
 232
 233    pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
 234        proto::DiagnosticSummary {
 235            path: path.to_string_lossy().to_string(),
 236            error_count: self.error_count as u32,
 237            warning_count: self.warning_count as u32,
 238        }
 239    }
 240}
 241
 242#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 243pub struct ProjectEntryId(usize);
 244
 245impl ProjectEntryId {
 246    pub const MAX: Self = Self(usize::MAX);
 247
 248    pub fn new(counter: &AtomicUsize) -> Self {
 249        Self(counter.fetch_add(1, SeqCst))
 250    }
 251
 252    pub fn from_proto(id: u64) -> Self {
 253        Self(id as usize)
 254    }
 255
 256    pub fn to_proto(&self) -> u64 {
 257        self.0 as u64
 258    }
 259
 260    pub fn to_usize(&self) -> usize {
 261        self.0
 262    }
 263}
 264
 265impl Project {
 266    pub fn init(client: &Arc<Client>) {
 267        client.add_model_message_handler(Self::handle_request_join_project);
 268        client.add_model_message_handler(Self::handle_add_collaborator);
 269        client.add_model_message_handler(Self::handle_buffer_reloaded);
 270        client.add_model_message_handler(Self::handle_buffer_saved);
 271        client.add_model_message_handler(Self::handle_start_language_server);
 272        client.add_model_message_handler(Self::handle_update_language_server);
 273        client.add_model_message_handler(Self::handle_remove_collaborator);
 274        client.add_model_message_handler(Self::handle_join_project_request_cancelled);
 275        client.add_model_message_handler(Self::handle_register_worktree);
 276        client.add_model_message_handler(Self::handle_unregister_worktree);
 277        client.add_model_message_handler(Self::handle_unregister_project);
 278        client.add_model_message_handler(Self::handle_project_unshared);
 279        client.add_model_message_handler(Self::handle_update_buffer_file);
 280        client.add_model_message_handler(Self::handle_update_buffer);
 281        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 282        client.add_model_message_handler(Self::handle_update_worktree);
 283        client.add_model_request_handler(Self::handle_create_project_entry);
 284        client.add_model_request_handler(Self::handle_rename_project_entry);
 285        client.add_model_request_handler(Self::handle_delete_project_entry);
 286        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 287        client.add_model_request_handler(Self::handle_apply_code_action);
 288        client.add_model_request_handler(Self::handle_reload_buffers);
 289        client.add_model_request_handler(Self::handle_format_buffers);
 290        client.add_model_request_handler(Self::handle_get_code_actions);
 291        client.add_model_request_handler(Self::handle_get_completions);
 292        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 293        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 294        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 295        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 296        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 297        client.add_model_request_handler(Self::handle_search_project);
 298        client.add_model_request_handler(Self::handle_get_project_symbols);
 299        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 300        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 301        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 302        client.add_model_request_handler(Self::handle_save_buffer);
 303    }
 304
 305    pub fn local(
 306        client: Arc<Client>,
 307        user_store: ModelHandle<UserStore>,
 308        languages: Arc<LanguageRegistry>,
 309        fs: Arc<dyn Fs>,
 310        cx: &mut MutableAppContext,
 311    ) -> ModelHandle<Self> {
 312        cx.add_model(|cx: &mut ModelContext<Self>| {
 313            let (remote_id_tx, remote_id_rx) = watch::channel();
 314            let _maintain_remote_id_task = cx.spawn_weak({
 315                let rpc = client.clone();
 316                move |this, mut cx| {
 317                    async move {
 318                        let mut status = rpc.status();
 319                        while let Some(status) = status.next().await {
 320                            if let Some(this) = this.upgrade(&cx) {
 321                                if status.is_connected() {
 322                                    this.update(&mut cx, |this, cx| this.register(cx)).await?;
 323                                } else {
 324                                    this.update(&mut cx, |this, cx| this.unregister(cx));
 325                                }
 326                            }
 327                        }
 328                        Ok(())
 329                    }
 330                    .log_err()
 331                }
 332            });
 333
 334            let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
 335            Self {
 336                worktrees: Default::default(),
 337                collaborators: Default::default(),
 338                opened_buffers: Default::default(),
 339                shared_buffers: Default::default(),
 340                loading_buffers: Default::default(),
 341                loading_local_worktrees: Default::default(),
 342                buffer_snapshots: Default::default(),
 343                client_state: ProjectClientState::Local {
 344                    is_shared: false,
 345                    remote_id_tx,
 346                    remote_id_rx,
 347                    _maintain_remote_id_task,
 348                },
 349                opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
 350                subscriptions: Vec::new(),
 351                active_entry: None,
 352                languages,
 353                client,
 354                user_store,
 355                fs,
 356                next_entry_id: Default::default(),
 357                language_servers: Default::default(),
 358                started_language_servers: Default::default(),
 359                language_server_statuses: Default::default(),
 360                last_workspace_edits_by_language_server: Default::default(),
 361                language_server_settings: Default::default(),
 362                next_language_server_id: 0,
 363                nonce: StdRng::from_entropy().gen(),
 364            }
 365        })
 366    }
 367
 368    pub async fn remote(
 369        remote_id: u64,
 370        client: Arc<Client>,
 371        user_store: ModelHandle<UserStore>,
 372        languages: Arc<LanguageRegistry>,
 373        fs: Arc<dyn Fs>,
 374        cx: &mut AsyncAppContext,
 375    ) -> Result<ModelHandle<Self>, JoinProjectError> {
 376        client.authenticate_and_connect(true, &cx).await?;
 377
 378        let response = client
 379            .request(proto::JoinProject {
 380                project_id: remote_id,
 381            })
 382            .await?;
 383
 384        let response = match response.variant.ok_or_else(|| anyhow!("missing variant"))? {
 385            proto::join_project_response::Variant::Accept(response) => response,
 386            proto::join_project_response::Variant::Decline(decline) => {
 387                match proto::join_project_response::decline::Reason::from_i32(decline.reason) {
 388                    Some(proto::join_project_response::decline::Reason::Declined) => {
 389                        Err(JoinProjectError::HostDeclined)?
 390                    }
 391                    Some(proto::join_project_response::decline::Reason::Closed) => {
 392                        Err(JoinProjectError::HostClosedProject)?
 393                    }
 394                    Some(proto::join_project_response::decline::Reason::WentOffline) => {
 395                        Err(JoinProjectError::HostWentOffline)?
 396                    }
 397                    None => Err(anyhow!("missing decline reason"))?,
 398                }
 399            }
 400        };
 401
 402        let replica_id = response.replica_id as ReplicaId;
 403
 404        let mut worktrees = Vec::new();
 405        for worktree in response.worktrees {
 406            let (worktree, load_task) = cx
 407                .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
 408            worktrees.push(worktree);
 409            load_task.detach();
 410        }
 411
 412        let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
 413        let this = cx.add_model(|cx: &mut ModelContext<Self>| {
 414            let mut this = Self {
 415                worktrees: Vec::new(),
 416                loading_buffers: Default::default(),
 417                opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
 418                shared_buffers: Default::default(),
 419                loading_local_worktrees: Default::default(),
 420                active_entry: None,
 421                collaborators: Default::default(),
 422                languages,
 423                user_store: user_store.clone(),
 424                fs,
 425                next_entry_id: Default::default(),
 426                subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
 427                client: client.clone(),
 428                client_state: ProjectClientState::Remote {
 429                    sharing_has_stopped: false,
 430                    remote_id,
 431                    replica_id,
 432                    _detect_unshare_task: cx.spawn_weak(move |this, mut cx| {
 433                        async move {
 434                            let mut status = client.status();
 435                            let is_connected =
 436                                status.next().await.map_or(false, |s| s.is_connected());
 437                            // Even if we're initially connected, any future change of the status means we momentarily disconnected.
 438                            if !is_connected || status.next().await.is_some() {
 439                                if let Some(this) = this.upgrade(&cx) {
 440                                    this.update(&mut cx, |this, cx| this.removed_from_project(cx))
 441                                }
 442                            }
 443                            Ok(())
 444                        }
 445                        .log_err()
 446                    }),
 447                },
 448                language_servers: Default::default(),
 449                started_language_servers: Default::default(),
 450                language_server_settings: Default::default(),
 451                language_server_statuses: response
 452                    .language_servers
 453                    .into_iter()
 454                    .map(|server| {
 455                        (
 456                            server.id as usize,
 457                            LanguageServerStatus {
 458                                name: server.name,
 459                                pending_work: Default::default(),
 460                                pending_diagnostic_updates: 0,
 461                            },
 462                        )
 463                    })
 464                    .collect(),
 465                last_workspace_edits_by_language_server: Default::default(),
 466                next_language_server_id: 0,
 467                opened_buffers: Default::default(),
 468                buffer_snapshots: Default::default(),
 469                nonce: StdRng::from_entropy().gen(),
 470            };
 471            for worktree in worktrees {
 472                this.add_worktree(&worktree, cx);
 473            }
 474            this
 475        });
 476
 477        let user_ids = response
 478            .collaborators
 479            .iter()
 480            .map(|peer| peer.user_id)
 481            .collect();
 482        user_store
 483            .update(cx, |user_store, cx| user_store.get_users(user_ids, cx))
 484            .await?;
 485        let mut collaborators = HashMap::default();
 486        for message in response.collaborators {
 487            let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
 488            collaborators.insert(collaborator.peer_id, collaborator);
 489        }
 490
 491        this.update(cx, |this, _| {
 492            this.collaborators = collaborators;
 493        });
 494
 495        Ok(this)
 496    }
 497
 498    #[cfg(any(test, feature = "test-support"))]
 499    pub async fn test(
 500        fs: Arc<dyn Fs>,
 501        root_paths: impl IntoIterator<Item = &Path>,
 502        cx: &mut gpui::TestAppContext,
 503    ) -> ModelHandle<Project> {
 504        let languages = Arc::new(LanguageRegistry::test());
 505        let http_client = client::test::FakeHttpClient::with_404_response();
 506        let client = client::Client::new(http_client.clone());
 507        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 508        let project = cx.update(|cx| Project::local(client, user_store, languages, fs, cx));
 509        for path in root_paths {
 510            let (tree, _) = project
 511                .update(cx, |project, cx| {
 512                    project.find_or_create_local_worktree(path, true, cx)
 513                })
 514                .await
 515                .unwrap();
 516            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 517                .await;
 518        }
 519        project
 520    }
 521
 522    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 523        self.opened_buffers
 524            .get(&remote_id)
 525            .and_then(|buffer| buffer.upgrade(cx))
 526    }
 527
 528    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 529        &self.languages
 530    }
 531
 532    pub fn client(&self) -> Arc<Client> {
 533        self.client.clone()
 534    }
 535
 536    pub fn user_store(&self) -> ModelHandle<UserStore> {
 537        self.user_store.clone()
 538    }
 539
 540    #[cfg(any(test, feature = "test-support"))]
 541    pub fn check_invariants(&self, cx: &AppContext) {
 542        if self.is_local() {
 543            let mut worktree_root_paths = HashMap::default();
 544            for worktree in self.worktrees(cx) {
 545                let worktree = worktree.read(cx);
 546                let abs_path = worktree.as_local().unwrap().abs_path().clone();
 547                let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
 548                assert_eq!(
 549                    prev_worktree_id,
 550                    None,
 551                    "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
 552                    abs_path,
 553                    worktree.id(),
 554                    prev_worktree_id
 555                )
 556            }
 557        } else {
 558            let replica_id = self.replica_id();
 559            for buffer in self.opened_buffers.values() {
 560                if let Some(buffer) = buffer.upgrade(cx) {
 561                    let buffer = buffer.read(cx);
 562                    assert_eq!(
 563                        buffer.deferred_ops_len(),
 564                        0,
 565                        "replica {}, buffer {} has deferred operations",
 566                        replica_id,
 567                        buffer.remote_id()
 568                    );
 569                }
 570            }
 571        }
 572    }
 573
 574    #[cfg(any(test, feature = "test-support"))]
 575    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 576        let path = path.into();
 577        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 578            self.opened_buffers.iter().any(|(_, buffer)| {
 579                if let Some(buffer) = buffer.upgrade(cx) {
 580                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 581                        if file.worktree == worktree && file.path() == &path.path {
 582                            return true;
 583                        }
 584                    }
 585                }
 586                false
 587            })
 588        } else {
 589            false
 590        }
 591    }
 592
 593    pub fn fs(&self) -> &Arc<dyn Fs> {
 594        &self.fs
 595    }
 596
 597    fn unregister(&mut self, cx: &mut ModelContext<Self>) {
 598        self.unshared(cx);
 599        for worktree in &self.worktrees {
 600            if let Some(worktree) = worktree.upgrade(cx) {
 601                worktree.update(cx, |worktree, _| {
 602                    worktree.as_local_mut().unwrap().unregister();
 603                });
 604            }
 605        }
 606
 607        if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
 608            *remote_id_tx.borrow_mut() = None;
 609        }
 610
 611        self.subscriptions.clear();
 612    }
 613
 614    fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 615        self.unregister(cx);
 616
 617        let response = self.client.request(proto::RegisterProject {});
 618        cx.spawn(|this, mut cx| async move {
 619            let remote_id = response.await?.project_id;
 620
 621            let mut registrations = Vec::new();
 622            this.update(&mut cx, |this, cx| {
 623                if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
 624                    *remote_id_tx.borrow_mut() = Some(remote_id);
 625                }
 626
 627                cx.emit(Event::RemoteIdChanged(Some(remote_id)));
 628
 629                this.subscriptions
 630                    .push(this.client.add_model_for_remote_entity(remote_id, cx));
 631
 632                for worktree in &this.worktrees {
 633                    if let Some(worktree) = worktree.upgrade(cx) {
 634                        registrations.push(worktree.update(cx, |worktree, cx| {
 635                            let worktree = worktree.as_local_mut().unwrap();
 636                            worktree.register(remote_id, cx)
 637                        }));
 638                    }
 639                }
 640            });
 641
 642            futures::future::try_join_all(registrations).await?;
 643            Ok(())
 644        })
 645    }
 646
 647    pub fn remote_id(&self) -> Option<u64> {
 648        match &self.client_state {
 649            ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
 650            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 651        }
 652    }
 653
 654    pub fn next_remote_id(&self) -> impl Future<Output = u64> {
 655        let mut id = None;
 656        let mut watch = None;
 657        match &self.client_state {
 658            ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
 659            ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
 660        }
 661
 662        async move {
 663            if let Some(id) = id {
 664                return id;
 665            }
 666            let mut watch = watch.unwrap();
 667            loop {
 668                let id = *watch.borrow();
 669                if let Some(id) = id {
 670                    return id;
 671                }
 672                watch.next().await;
 673            }
 674        }
 675    }
 676
 677    pub fn replica_id(&self) -> ReplicaId {
 678        match &self.client_state {
 679            ProjectClientState::Local { .. } => 0,
 680            ProjectClientState::Remote { replica_id, .. } => *replica_id,
 681        }
 682    }
 683
 684    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
 685        &self.collaborators
 686    }
 687
 688    pub fn worktrees<'a>(
 689        &'a self,
 690        cx: &'a AppContext,
 691    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 692        self.worktrees
 693            .iter()
 694            .filter_map(move |worktree| worktree.upgrade(cx))
 695    }
 696
 697    pub fn visible_worktrees<'a>(
 698        &'a self,
 699        cx: &'a AppContext,
 700    ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
 701        self.worktrees.iter().filter_map(|worktree| {
 702            worktree.upgrade(cx).and_then(|worktree| {
 703                if worktree.read(cx).is_visible() {
 704                    Some(worktree)
 705                } else {
 706                    None
 707                }
 708            })
 709        })
 710    }
 711
 712    pub fn worktree_for_id(
 713        &self,
 714        id: WorktreeId,
 715        cx: &AppContext,
 716    ) -> Option<ModelHandle<Worktree>> {
 717        self.worktrees(cx)
 718            .find(|worktree| worktree.read(cx).id() == id)
 719    }
 720
 721    pub fn worktree_for_entry(
 722        &self,
 723        entry_id: ProjectEntryId,
 724        cx: &AppContext,
 725    ) -> Option<ModelHandle<Worktree>> {
 726        self.worktrees(cx)
 727            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 728    }
 729
 730    pub fn worktree_id_for_entry(
 731        &self,
 732        entry_id: ProjectEntryId,
 733        cx: &AppContext,
 734    ) -> Option<WorktreeId> {
 735        self.worktree_for_entry(entry_id, cx)
 736            .map(|worktree| worktree.read(cx).id())
 737    }
 738
 739    pub fn create_entry(
 740        &mut self,
 741        project_path: impl Into<ProjectPath>,
 742        is_directory: bool,
 743        cx: &mut ModelContext<Self>,
 744    ) -> Option<Task<Result<Entry>>> {
 745        let project_path = project_path.into();
 746        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 747        if self.is_local() {
 748            Some(worktree.update(cx, |worktree, cx| {
 749                worktree
 750                    .as_local_mut()
 751                    .unwrap()
 752                    .create_entry(project_path.path, is_directory, cx)
 753            }))
 754        } else {
 755            let client = self.client.clone();
 756            let project_id = self.remote_id().unwrap();
 757            Some(cx.spawn_weak(|_, mut cx| async move {
 758                let response = client
 759                    .request(proto::CreateProjectEntry {
 760                        worktree_id: project_path.worktree_id.to_proto(),
 761                        project_id,
 762                        path: project_path.path.as_os_str().as_bytes().to_vec(),
 763                        is_directory,
 764                    })
 765                    .await?;
 766                let entry = response
 767                    .entry
 768                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 769                worktree
 770                    .update(&mut cx, |worktree, cx| {
 771                        worktree.as_remote().unwrap().insert_entry(
 772                            entry,
 773                            response.worktree_scan_id as usize,
 774                            cx,
 775                        )
 776                    })
 777                    .await
 778            }))
 779        }
 780    }
 781
 782    pub fn rename_entry(
 783        &mut self,
 784        entry_id: ProjectEntryId,
 785        new_path: impl Into<Arc<Path>>,
 786        cx: &mut ModelContext<Self>,
 787    ) -> Option<Task<Result<Entry>>> {
 788        let worktree = self.worktree_for_entry(entry_id, cx)?;
 789        let new_path = new_path.into();
 790        if self.is_local() {
 791            worktree.update(cx, |worktree, cx| {
 792                worktree
 793                    .as_local_mut()
 794                    .unwrap()
 795                    .rename_entry(entry_id, new_path, cx)
 796            })
 797        } else {
 798            let client = self.client.clone();
 799            let project_id = self.remote_id().unwrap();
 800
 801            Some(cx.spawn_weak(|_, mut cx| async move {
 802                let response = client
 803                    .request(proto::RenameProjectEntry {
 804                        project_id,
 805                        entry_id: entry_id.to_proto(),
 806                        new_path: new_path.as_os_str().as_bytes().to_vec(),
 807                    })
 808                    .await?;
 809                let entry = response
 810                    .entry
 811                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 812                worktree
 813                    .update(&mut cx, |worktree, cx| {
 814                        worktree.as_remote().unwrap().insert_entry(
 815                            entry,
 816                            response.worktree_scan_id as usize,
 817                            cx,
 818                        )
 819                    })
 820                    .await
 821            }))
 822        }
 823    }
 824
 825    pub fn delete_entry(
 826        &mut self,
 827        entry_id: ProjectEntryId,
 828        cx: &mut ModelContext<Self>,
 829    ) -> Option<Task<Result<()>>> {
 830        let worktree = self.worktree_for_entry(entry_id, cx)?;
 831        if self.is_local() {
 832            worktree.update(cx, |worktree, cx| {
 833                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
 834            })
 835        } else {
 836            let client = self.client.clone();
 837            let project_id = self.remote_id().unwrap();
 838            Some(cx.spawn_weak(|_, mut cx| async move {
 839                let response = client
 840                    .request(proto::DeleteProjectEntry {
 841                        project_id,
 842                        entry_id: entry_id.to_proto(),
 843                    })
 844                    .await?;
 845                worktree
 846                    .update(&mut cx, move |worktree, cx| {
 847                        worktree.as_remote().unwrap().delete_entry(
 848                            entry_id,
 849                            response.worktree_scan_id as usize,
 850                            cx,
 851                        )
 852                    })
 853                    .await
 854            }))
 855        }
 856    }
 857
 858    fn share(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 859        let project_id;
 860        if let ProjectClientState::Local {
 861            remote_id_rx,
 862            is_shared,
 863            ..
 864        } = &mut self.client_state
 865        {
 866            if *is_shared {
 867                return Task::ready(Ok(()));
 868            }
 869            *is_shared = true;
 870            if let Some(id) = *remote_id_rx.borrow() {
 871                project_id = id;
 872            } else {
 873                return Task::ready(Err(anyhow!("project hasn't been registered")));
 874            }
 875        } else {
 876            return Task::ready(Err(anyhow!("can't share a remote project")));
 877        };
 878
 879        for open_buffer in self.opened_buffers.values_mut() {
 880            match open_buffer {
 881                OpenBuffer::Strong(_) => {}
 882                OpenBuffer::Weak(buffer) => {
 883                    if let Some(buffer) = buffer.upgrade(cx) {
 884                        *open_buffer = OpenBuffer::Strong(buffer);
 885                    }
 886                }
 887                OpenBuffer::Loading(_) => unreachable!(),
 888            }
 889        }
 890
 891        for worktree_handle in self.worktrees.iter_mut() {
 892            match worktree_handle {
 893                WorktreeHandle::Strong(_) => {}
 894                WorktreeHandle::Weak(worktree) => {
 895                    if let Some(worktree) = worktree.upgrade(cx) {
 896                        *worktree_handle = WorktreeHandle::Strong(worktree);
 897                    }
 898                }
 899            }
 900        }
 901
 902        let mut tasks = Vec::new();
 903        for worktree in self.worktrees(cx).collect::<Vec<_>>() {
 904            worktree.update(cx, |worktree, cx| {
 905                let worktree = worktree.as_local_mut().unwrap();
 906                tasks.push(worktree.share(project_id, cx));
 907            });
 908        }
 909
 910        cx.spawn(|this, mut cx| async move {
 911            for task in tasks {
 912                task.await?;
 913            }
 914            this.update(&mut cx, |_, cx| cx.notify());
 915            Ok(())
 916        })
 917    }
 918
 919    fn unshared(&mut self, cx: &mut ModelContext<Self>) {
 920        if let ProjectClientState::Local { is_shared, .. } = &mut self.client_state {
 921            if !*is_shared {
 922                return;
 923            }
 924
 925            *is_shared = false;
 926            self.collaborators.clear();
 927            self.shared_buffers.clear();
 928            for worktree_handle in self.worktrees.iter_mut() {
 929                if let WorktreeHandle::Strong(worktree) = worktree_handle {
 930                    let is_visible = worktree.update(cx, |worktree, _| {
 931                        worktree.as_local_mut().unwrap().unshare();
 932                        worktree.is_visible()
 933                    });
 934                    if !is_visible {
 935                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 936                    }
 937                }
 938            }
 939
 940            for open_buffer in self.opened_buffers.values_mut() {
 941                match open_buffer {
 942                    OpenBuffer::Strong(buffer) => {
 943                        *open_buffer = OpenBuffer::Weak(buffer.downgrade());
 944                    }
 945                    _ => {}
 946                }
 947            }
 948
 949            cx.notify();
 950        } else {
 951            log::error!("attempted to unshare a remote project");
 952        }
 953    }
 954
 955    pub fn respond_to_join_request(
 956        &mut self,
 957        requester_id: u64,
 958        allow: bool,
 959        cx: &mut ModelContext<Self>,
 960    ) {
 961        if let Some(project_id) = self.remote_id() {
 962            let share = self.share(cx);
 963            let client = self.client.clone();
 964            cx.foreground()
 965                .spawn(async move {
 966                    share.await?;
 967                    client.send(proto::RespondToJoinProjectRequest {
 968                        requester_id,
 969                        project_id,
 970                        allow,
 971                    })
 972                })
 973                .detach_and_log_err(cx);
 974        }
 975    }
 976
 977    fn removed_from_project(&mut self, cx: &mut ModelContext<Self>) {
 978        if let ProjectClientState::Remote {
 979            sharing_has_stopped,
 980            ..
 981        } = &mut self.client_state
 982        {
 983            *sharing_has_stopped = true;
 984            self.collaborators.clear();
 985            cx.notify();
 986        }
 987    }
 988
 989    pub fn is_read_only(&self) -> bool {
 990        match &self.client_state {
 991            ProjectClientState::Local { .. } => false,
 992            ProjectClientState::Remote {
 993                sharing_has_stopped,
 994                ..
 995            } => *sharing_has_stopped,
 996        }
 997    }
 998
 999    pub fn is_local(&self) -> bool {
1000        match &self.client_state {
1001            ProjectClientState::Local { .. } => true,
1002            ProjectClientState::Remote { .. } => false,
1003        }
1004    }
1005
1006    pub fn is_remote(&self) -> bool {
1007        !self.is_local()
1008    }
1009
1010    pub fn create_buffer(
1011        &mut self,
1012        text: &str,
1013        language: Option<Arc<Language>>,
1014        cx: &mut ModelContext<Self>,
1015    ) -> Result<ModelHandle<Buffer>> {
1016        if self.is_remote() {
1017            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1018        }
1019
1020        let buffer = cx.add_model(|cx| {
1021            Buffer::new(self.replica_id(), text, cx)
1022                .with_language(language.unwrap_or(language::PLAIN_TEXT.clone()), cx)
1023        });
1024        self.register_buffer(&buffer, cx)?;
1025        Ok(buffer)
1026    }
1027
1028    pub fn open_path(
1029        &mut self,
1030        path: impl Into<ProjectPath>,
1031        cx: &mut ModelContext<Self>,
1032    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1033        let task = self.open_buffer(path, cx);
1034        cx.spawn_weak(|_, cx| async move {
1035            let buffer = task.await?;
1036            let project_entry_id = buffer
1037                .read_with(&cx, |buffer, cx| {
1038                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1039                })
1040                .ok_or_else(|| anyhow!("no project entry"))?;
1041            Ok((project_entry_id, buffer.into()))
1042        })
1043    }
1044
1045    pub fn open_local_buffer(
1046        &mut self,
1047        abs_path: impl AsRef<Path>,
1048        cx: &mut ModelContext<Self>,
1049    ) -> Task<Result<ModelHandle<Buffer>>> {
1050        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1051            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1052        } else {
1053            Task::ready(Err(anyhow!("no such path")))
1054        }
1055    }
1056
1057    pub fn open_buffer(
1058        &mut self,
1059        path: impl Into<ProjectPath>,
1060        cx: &mut ModelContext<Self>,
1061    ) -> Task<Result<ModelHandle<Buffer>>> {
1062        let project_path = path.into();
1063        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1064            worktree
1065        } else {
1066            return Task::ready(Err(anyhow!("no such worktree")));
1067        };
1068
1069        // If there is already a buffer for the given path, then return it.
1070        let existing_buffer = self.get_open_buffer(&project_path, cx);
1071        if let Some(existing_buffer) = existing_buffer {
1072            return Task::ready(Ok(existing_buffer));
1073        }
1074
1075        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1076            // If the given path is already being loaded, then wait for that existing
1077            // task to complete and return the same buffer.
1078            hash_map::Entry::Occupied(e) => e.get().clone(),
1079
1080            // Otherwise, record the fact that this path is now being loaded.
1081            hash_map::Entry::Vacant(entry) => {
1082                let (mut tx, rx) = postage::watch::channel();
1083                entry.insert(rx.clone());
1084
1085                let load_buffer = if worktree.read(cx).is_local() {
1086                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1087                } else {
1088                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1089                };
1090
1091                cx.spawn(move |this, mut cx| async move {
1092                    let load_result = load_buffer.await;
1093                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1094                        // Record the fact that the buffer is no longer loading.
1095                        this.loading_buffers.remove(&project_path);
1096                        let buffer = load_result.map_err(Arc::new)?;
1097                        Ok(buffer)
1098                    }));
1099                })
1100                .detach();
1101                rx
1102            }
1103        };
1104
1105        cx.foreground().spawn(async move {
1106            loop {
1107                if let Some(result) = loading_watch.borrow().as_ref() {
1108                    match result {
1109                        Ok(buffer) => return Ok(buffer.clone()),
1110                        Err(error) => return Err(anyhow!("{}", error)),
1111                    }
1112                }
1113                loading_watch.next().await;
1114            }
1115        })
1116    }
1117
1118    fn open_local_buffer_internal(
1119        &mut self,
1120        path: &Arc<Path>,
1121        worktree: &ModelHandle<Worktree>,
1122        cx: &mut ModelContext<Self>,
1123    ) -> Task<Result<ModelHandle<Buffer>>> {
1124        let load_buffer = worktree.update(cx, |worktree, cx| {
1125            let worktree = worktree.as_local_mut().unwrap();
1126            worktree.load_buffer(path, cx)
1127        });
1128        cx.spawn(|this, mut cx| async move {
1129            let buffer = load_buffer.await?;
1130            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1131            Ok(buffer)
1132        })
1133    }
1134
1135    fn open_remote_buffer_internal(
1136        &mut self,
1137        path: &Arc<Path>,
1138        worktree: &ModelHandle<Worktree>,
1139        cx: &mut ModelContext<Self>,
1140    ) -> Task<Result<ModelHandle<Buffer>>> {
1141        let rpc = self.client.clone();
1142        let project_id = self.remote_id().unwrap();
1143        let remote_worktree_id = worktree.read(cx).id();
1144        let path = path.clone();
1145        let path_string = path.to_string_lossy().to_string();
1146        cx.spawn(|this, mut cx| async move {
1147            let response = rpc
1148                .request(proto::OpenBufferByPath {
1149                    project_id,
1150                    worktree_id: remote_worktree_id.to_proto(),
1151                    path: path_string,
1152                })
1153                .await?;
1154            let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
1155            this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1156                .await
1157        })
1158    }
1159
1160    fn open_local_buffer_via_lsp(
1161        &mut self,
1162        abs_path: lsp::Url,
1163        lsp_adapter: Arc<dyn LspAdapter>,
1164        lsp_server: Arc<LanguageServer>,
1165        cx: &mut ModelContext<Self>,
1166    ) -> Task<Result<ModelHandle<Buffer>>> {
1167        cx.spawn(|this, mut cx| async move {
1168            let abs_path = abs_path
1169                .to_file_path()
1170                .map_err(|_| anyhow!("can't convert URI to path"))?;
1171            let (worktree, relative_path) = if let Some(result) =
1172                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1173            {
1174                result
1175            } else {
1176                let worktree = this
1177                    .update(&mut cx, |this, cx| {
1178                        this.create_local_worktree(&abs_path, false, cx)
1179                    })
1180                    .await?;
1181                this.update(&mut cx, |this, cx| {
1182                    this.language_servers.insert(
1183                        (worktree.read(cx).id(), lsp_adapter.name()),
1184                        (lsp_adapter, lsp_server),
1185                    );
1186                });
1187                (worktree, PathBuf::new())
1188            };
1189
1190            let project_path = ProjectPath {
1191                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1192                path: relative_path.into(),
1193            };
1194            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1195                .await
1196        })
1197    }
1198
1199    pub fn open_buffer_by_id(
1200        &mut self,
1201        id: u64,
1202        cx: &mut ModelContext<Self>,
1203    ) -> Task<Result<ModelHandle<Buffer>>> {
1204        if let Some(buffer) = self.buffer_for_id(id, cx) {
1205            Task::ready(Ok(buffer))
1206        } else if self.is_local() {
1207            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1208        } else if let Some(project_id) = self.remote_id() {
1209            let request = self
1210                .client
1211                .request(proto::OpenBufferById { project_id, id });
1212            cx.spawn(|this, mut cx| async move {
1213                let buffer = request
1214                    .await?
1215                    .buffer
1216                    .ok_or_else(|| anyhow!("invalid buffer"))?;
1217                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1218                    .await
1219            })
1220        } else {
1221            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1222        }
1223    }
1224
1225    pub fn save_buffer_as(
1226        &mut self,
1227        buffer: ModelHandle<Buffer>,
1228        abs_path: PathBuf,
1229        cx: &mut ModelContext<Project>,
1230    ) -> Task<Result<()>> {
1231        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1232        let old_path =
1233            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1234        cx.spawn(|this, mut cx| async move {
1235            if let Some(old_path) = old_path {
1236                this.update(&mut cx, |this, cx| {
1237                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1238                });
1239            }
1240            let (worktree, path) = worktree_task.await?;
1241            worktree
1242                .update(&mut cx, |worktree, cx| {
1243                    worktree
1244                        .as_local_mut()
1245                        .unwrap()
1246                        .save_buffer_as(buffer.clone(), path, cx)
1247                })
1248                .await?;
1249            this.update(&mut cx, |this, cx| {
1250                this.assign_language_to_buffer(&buffer, cx);
1251                this.register_buffer_with_language_server(&buffer, cx);
1252            });
1253            Ok(())
1254        })
1255    }
1256
1257    pub fn get_open_buffer(
1258        &mut self,
1259        path: &ProjectPath,
1260        cx: &mut ModelContext<Self>,
1261    ) -> Option<ModelHandle<Buffer>> {
1262        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1263        self.opened_buffers.values().find_map(|buffer| {
1264            let buffer = buffer.upgrade(cx)?;
1265            let file = File::from_dyn(buffer.read(cx).file())?;
1266            if file.worktree == worktree && file.path() == &path.path {
1267                Some(buffer)
1268            } else {
1269                None
1270            }
1271        })
1272    }
1273
1274    fn register_buffer(
1275        &mut self,
1276        buffer: &ModelHandle<Buffer>,
1277        cx: &mut ModelContext<Self>,
1278    ) -> Result<()> {
1279        let remote_id = buffer.read(cx).remote_id();
1280        let open_buffer = if self.is_remote() || self.is_shared() {
1281            OpenBuffer::Strong(buffer.clone())
1282        } else {
1283            OpenBuffer::Weak(buffer.downgrade())
1284        };
1285
1286        match self.opened_buffers.insert(remote_id, open_buffer) {
1287            None => {}
1288            Some(OpenBuffer::Loading(operations)) => {
1289                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1290            }
1291            Some(OpenBuffer::Weak(existing_handle)) => {
1292                if existing_handle.upgrade(cx).is_some() {
1293                    Err(anyhow!(
1294                        "already registered buffer with remote id {}",
1295                        remote_id
1296                    ))?
1297                }
1298            }
1299            Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1300                "already registered buffer with remote id {}",
1301                remote_id
1302            ))?,
1303        }
1304        cx.subscribe(buffer, |this, buffer, event, cx| {
1305            this.on_buffer_event(buffer, event, cx);
1306        })
1307        .detach();
1308
1309        self.assign_language_to_buffer(buffer, cx);
1310        self.register_buffer_with_language_server(buffer, cx);
1311        cx.observe_release(buffer, |this, buffer, cx| {
1312            if let Some(file) = File::from_dyn(buffer.file()) {
1313                if file.is_local() {
1314                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1315                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1316                        server
1317                            .notify::<lsp::notification::DidCloseTextDocument>(
1318                                lsp::DidCloseTextDocumentParams {
1319                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1320                                },
1321                            )
1322                            .log_err();
1323                    }
1324                }
1325            }
1326        })
1327        .detach();
1328
1329        Ok(())
1330    }
1331
1332    fn register_buffer_with_language_server(
1333        &mut self,
1334        buffer_handle: &ModelHandle<Buffer>,
1335        cx: &mut ModelContext<Self>,
1336    ) {
1337        let buffer = buffer_handle.read(cx);
1338        let buffer_id = buffer.remote_id();
1339        if let Some(file) = File::from_dyn(buffer.file()) {
1340            if file.is_local() {
1341                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1342                let initial_snapshot = buffer.text_snapshot();
1343
1344                let mut language_server = None;
1345                let mut language_id = None;
1346                if let Some(language) = buffer.language() {
1347                    let worktree_id = file.worktree_id(cx);
1348                    if let Some(adapter) = language.lsp_adapter() {
1349                        language_id = adapter.id_for_language(language.name().as_ref());
1350                        language_server = self
1351                            .language_servers
1352                            .get(&(worktree_id, adapter.name()))
1353                            .cloned();
1354                    }
1355                }
1356
1357                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1358                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1359                        self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1360                            .log_err();
1361                    }
1362                }
1363
1364                if let Some((_, server)) = language_server {
1365                    server
1366                        .notify::<lsp::notification::DidOpenTextDocument>(
1367                            lsp::DidOpenTextDocumentParams {
1368                                text_document: lsp::TextDocumentItem::new(
1369                                    uri,
1370                                    language_id.unwrap_or_default(),
1371                                    0,
1372                                    initial_snapshot.text(),
1373                                ),
1374                            }
1375                            .clone(),
1376                        )
1377                        .log_err();
1378                    buffer_handle.update(cx, |buffer, cx| {
1379                        buffer.set_completion_triggers(
1380                            server
1381                                .capabilities()
1382                                .completion_provider
1383                                .as_ref()
1384                                .and_then(|provider| provider.trigger_characters.clone())
1385                                .unwrap_or(Vec::new()),
1386                            cx,
1387                        )
1388                    });
1389                    self.buffer_snapshots
1390                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1391                }
1392            }
1393        }
1394    }
1395
1396    fn unregister_buffer_from_language_server(
1397        &mut self,
1398        buffer: &ModelHandle<Buffer>,
1399        old_path: PathBuf,
1400        cx: &mut ModelContext<Self>,
1401    ) {
1402        buffer.update(cx, |buffer, cx| {
1403            buffer.update_diagnostics(Default::default(), cx);
1404            self.buffer_snapshots.remove(&buffer.remote_id());
1405            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1406                language_server
1407                    .notify::<lsp::notification::DidCloseTextDocument>(
1408                        lsp::DidCloseTextDocumentParams {
1409                            text_document: lsp::TextDocumentIdentifier::new(
1410                                lsp::Url::from_file_path(old_path).unwrap(),
1411                            ),
1412                        },
1413                    )
1414                    .log_err();
1415            }
1416        });
1417    }
1418
1419    fn on_buffer_event(
1420        &mut self,
1421        buffer: ModelHandle<Buffer>,
1422        event: &BufferEvent,
1423        cx: &mut ModelContext<Self>,
1424    ) -> Option<()> {
1425        match event {
1426            BufferEvent::Operation(operation) => {
1427                let project_id = self.remote_id()?;
1428                let request = self.client.request(proto::UpdateBuffer {
1429                    project_id,
1430                    buffer_id: buffer.read(cx).remote_id(),
1431                    operations: vec![language::proto::serialize_operation(&operation)],
1432                });
1433                cx.background().spawn(request).detach_and_log_err(cx);
1434            }
1435            BufferEvent::Edited { .. } => {
1436                let (_, language_server) = self
1437                    .language_server_for_buffer(buffer.read(cx), cx)?
1438                    .clone();
1439                let buffer = buffer.read(cx);
1440                let file = File::from_dyn(buffer.file())?;
1441                let abs_path = file.as_local()?.abs_path(cx);
1442                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1443                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1444                let (version, prev_snapshot) = buffer_snapshots.last()?;
1445                let next_snapshot = buffer.text_snapshot();
1446                let next_version = version + 1;
1447
1448                let content_changes = buffer
1449                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1450                    .map(|edit| {
1451                        let edit_start = edit.new.start.0;
1452                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1453                        let new_text = next_snapshot
1454                            .text_for_range(edit.new.start.1..edit.new.end.1)
1455                            .collect();
1456                        lsp::TextDocumentContentChangeEvent {
1457                            range: Some(lsp::Range::new(
1458                                point_to_lsp(edit_start),
1459                                point_to_lsp(edit_end),
1460                            )),
1461                            range_length: None,
1462                            text: new_text,
1463                        }
1464                    })
1465                    .collect();
1466
1467                buffer_snapshots.push((next_version, next_snapshot));
1468
1469                language_server
1470                    .notify::<lsp::notification::DidChangeTextDocument>(
1471                        lsp::DidChangeTextDocumentParams {
1472                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1473                                uri,
1474                                next_version,
1475                            ),
1476                            content_changes,
1477                        },
1478                    )
1479                    .log_err();
1480            }
1481            BufferEvent::Saved => {
1482                let file = File::from_dyn(buffer.read(cx).file())?;
1483                let worktree_id = file.worktree_id(cx);
1484                let abs_path = file.as_local()?.abs_path(cx);
1485                let text_document = lsp::TextDocumentIdentifier {
1486                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1487                };
1488
1489                for (_, server) in self.language_servers_for_worktree(worktree_id) {
1490                    server
1491                        .notify::<lsp::notification::DidSaveTextDocument>(
1492                            lsp::DidSaveTextDocumentParams {
1493                                text_document: text_document.clone(),
1494                                text: None,
1495                            },
1496                        )
1497                        .log_err();
1498                }
1499            }
1500            _ => {}
1501        }
1502
1503        None
1504    }
1505
1506    fn language_servers_for_worktree(
1507        &self,
1508        worktree_id: WorktreeId,
1509    ) -> impl Iterator<Item = &(Arc<dyn LspAdapter>, Arc<LanguageServer>)> {
1510        self.language_servers.iter().filter_map(
1511            move |((language_server_worktree_id, _), server)| {
1512                if *language_server_worktree_id == worktree_id {
1513                    Some(server)
1514                } else {
1515                    None
1516                }
1517            },
1518        )
1519    }
1520
1521    fn assign_language_to_buffer(
1522        &mut self,
1523        buffer: &ModelHandle<Buffer>,
1524        cx: &mut ModelContext<Self>,
1525    ) -> Option<()> {
1526        // If the buffer has a language, set it and start the language server if we haven't already.
1527        let full_path = buffer.read(cx).file()?.full_path(cx);
1528        let language = self.languages.select_language(&full_path)?;
1529        buffer.update(cx, |buffer, cx| {
1530            buffer.set_language(Some(language.clone()), cx);
1531        });
1532
1533        let file = File::from_dyn(buffer.read(cx).file())?;
1534        let worktree = file.worktree.read(cx).as_local()?;
1535        let worktree_id = worktree.id();
1536        let worktree_abs_path = worktree.abs_path().clone();
1537        self.start_language_server(worktree_id, worktree_abs_path, language, cx);
1538
1539        None
1540    }
1541
1542    fn start_language_server(
1543        &mut self,
1544        worktree_id: WorktreeId,
1545        worktree_path: Arc<Path>,
1546        language: Arc<Language>,
1547        cx: &mut ModelContext<Self>,
1548    ) {
1549        let adapter = if let Some(adapter) = language.lsp_adapter() {
1550            adapter
1551        } else {
1552            return;
1553        };
1554        let key = (worktree_id, adapter.name());
1555        self.started_language_servers
1556            .entry(key.clone())
1557            .or_insert_with(|| {
1558                let server_id = post_inc(&mut self.next_language_server_id);
1559                let language_server = self.languages.start_language_server(
1560                    server_id,
1561                    language.clone(),
1562                    worktree_path,
1563                    self.client.http_client(),
1564                    cx,
1565                );
1566                cx.spawn_weak(|this, mut cx| async move {
1567                    let language_server = language_server?.await.log_err()?;
1568                    let language_server = language_server
1569                        .initialize(adapter.initialization_options())
1570                        .await
1571                        .log_err()?;
1572                    let this = this.upgrade(&cx)?;
1573                    let disk_based_diagnostics_progress_token =
1574                        adapter.disk_based_diagnostics_progress_token();
1575
1576                    language_server
1577                        .on_notification::<lsp::notification::PublishDiagnostics, _>({
1578                            let this = this.downgrade();
1579                            let adapter = adapter.clone();
1580                            move |params, mut cx| {
1581                                if let Some(this) = this.upgrade(&cx) {
1582                                    this.update(&mut cx, |this, cx| {
1583                                        this.on_lsp_diagnostics_published(
1584                                            server_id,
1585                                            params,
1586                                            &adapter,
1587                                            disk_based_diagnostics_progress_token,
1588                                            cx,
1589                                        );
1590                                    });
1591                                }
1592                            }
1593                        })
1594                        .detach();
1595
1596                    language_server
1597                        .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1598                            let settings = this
1599                                .read_with(&cx, |this, _| this.language_server_settings.clone());
1600                            move |params, _| {
1601                                let settings = settings.lock().clone();
1602                                async move {
1603                                    Ok(params
1604                                        .items
1605                                        .into_iter()
1606                                        .map(|item| {
1607                                            if let Some(section) = &item.section {
1608                                                settings
1609                                                    .get(section)
1610                                                    .cloned()
1611                                                    .unwrap_or(serde_json::Value::Null)
1612                                            } else {
1613                                                settings.clone()
1614                                            }
1615                                        })
1616                                        .collect())
1617                                }
1618                            }
1619                        })
1620                        .detach();
1621
1622                    language_server
1623                        .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
1624                            let this = this.downgrade();
1625                            let adapter = adapter.clone();
1626                            let language_server = language_server.clone();
1627                            move |params, cx| {
1628                                Self::on_lsp_workspace_edit(
1629                                    this,
1630                                    params,
1631                                    server_id,
1632                                    adapter.clone(),
1633                                    language_server.clone(),
1634                                    cx,
1635                                )
1636                            }
1637                        })
1638                        .detach();
1639
1640                    language_server
1641                        .on_notification::<lsp::notification::Progress, _>({
1642                            let this = this.downgrade();
1643                            move |params, mut cx| {
1644                                if let Some(this) = this.upgrade(&cx) {
1645                                    this.update(&mut cx, |this, cx| {
1646                                        this.on_lsp_progress(
1647                                            params,
1648                                            server_id,
1649                                            disk_based_diagnostics_progress_token,
1650                                            cx,
1651                                        );
1652                                    });
1653                                }
1654                            }
1655                        })
1656                        .detach();
1657
1658                    this.update(&mut cx, |this, cx| {
1659                        this.language_servers
1660                            .insert(key.clone(), (adapter.clone(), language_server.clone()));
1661                        this.language_server_statuses.insert(
1662                            server_id,
1663                            LanguageServerStatus {
1664                                name: language_server.name().to_string(),
1665                                pending_work: Default::default(),
1666                                pending_diagnostic_updates: 0,
1667                            },
1668                        );
1669                        language_server
1670                            .notify::<lsp::notification::DidChangeConfiguration>(
1671                                lsp::DidChangeConfigurationParams {
1672                                    settings: this.language_server_settings.lock().clone(),
1673                                },
1674                            )
1675                            .ok();
1676
1677                        if let Some(project_id) = this.remote_id() {
1678                            this.client
1679                                .send(proto::StartLanguageServer {
1680                                    project_id,
1681                                    server: Some(proto::LanguageServer {
1682                                        id: server_id as u64,
1683                                        name: language_server.name().to_string(),
1684                                    }),
1685                                })
1686                                .log_err();
1687                        }
1688
1689                        // Tell the language server about every open buffer in the worktree that matches the language.
1690                        for buffer in this.opened_buffers.values() {
1691                            if let Some(buffer_handle) = buffer.upgrade(cx) {
1692                                let buffer = buffer_handle.read(cx);
1693                                let file = if let Some(file) = File::from_dyn(buffer.file()) {
1694                                    file
1695                                } else {
1696                                    continue;
1697                                };
1698                                let language = if let Some(language) = buffer.language() {
1699                                    language
1700                                } else {
1701                                    continue;
1702                                };
1703                                if file.worktree.read(cx).id() != key.0
1704                                    || language.lsp_adapter().map(|a| a.name())
1705                                        != Some(key.1.clone())
1706                                {
1707                                    continue;
1708                                }
1709
1710                                let file = file.as_local()?;
1711                                let versions = this
1712                                    .buffer_snapshots
1713                                    .entry(buffer.remote_id())
1714                                    .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
1715                                let (version, initial_snapshot) = versions.last().unwrap();
1716                                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1717                                let language_id = adapter.id_for_language(language.name().as_ref());
1718                                language_server
1719                                    .notify::<lsp::notification::DidOpenTextDocument>(
1720                                        lsp::DidOpenTextDocumentParams {
1721                                            text_document: lsp::TextDocumentItem::new(
1722                                                uri,
1723                                                language_id.unwrap_or_default(),
1724                                                *version,
1725                                                initial_snapshot.text(),
1726                                            ),
1727                                        },
1728                                    )
1729                                    .log_err()?;
1730                                buffer_handle.update(cx, |buffer, cx| {
1731                                    buffer.set_completion_triggers(
1732                                        language_server
1733                                            .capabilities()
1734                                            .completion_provider
1735                                            .as_ref()
1736                                            .and_then(|provider| {
1737                                                provider.trigger_characters.clone()
1738                                            })
1739                                            .unwrap_or(Vec::new()),
1740                                        cx,
1741                                    )
1742                                });
1743                            }
1744                        }
1745
1746                        cx.notify();
1747                        Some(())
1748                    });
1749
1750                    Some(language_server)
1751                })
1752            });
1753    }
1754
1755    pub fn restart_language_servers_for_buffers(
1756        &mut self,
1757        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
1758        cx: &mut ModelContext<Self>,
1759    ) -> Option<()> {
1760        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
1761            .into_iter()
1762            .filter_map(|buffer| {
1763                let file = File::from_dyn(buffer.read(cx).file())?;
1764                let worktree = file.worktree.read(cx).as_local()?;
1765                let worktree_id = worktree.id();
1766                let worktree_abs_path = worktree.abs_path().clone();
1767                let full_path = file.full_path(cx);
1768                Some((worktree_id, worktree_abs_path, full_path))
1769            })
1770            .collect();
1771        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
1772            let language = self.languages.select_language(&full_path)?;
1773            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
1774        }
1775
1776        None
1777    }
1778
1779    fn restart_language_server(
1780        &mut self,
1781        worktree_id: WorktreeId,
1782        worktree_path: Arc<Path>,
1783        language: Arc<Language>,
1784        cx: &mut ModelContext<Self>,
1785    ) {
1786        let adapter = if let Some(adapter) = language.lsp_adapter() {
1787            adapter
1788        } else {
1789            return;
1790        };
1791        let key = (worktree_id, adapter.name());
1792        let server_to_shutdown = self.language_servers.remove(&key);
1793        self.started_language_servers.remove(&key);
1794        server_to_shutdown
1795            .as_ref()
1796            .map(|(_, server)| self.language_server_statuses.remove(&server.server_id()));
1797        cx.spawn_weak(|this, mut cx| async move {
1798            if let Some(this) = this.upgrade(&cx) {
1799                if let Some((_, server_to_shutdown)) = server_to_shutdown {
1800                    if let Some(shutdown_task) = server_to_shutdown.shutdown() {
1801                        shutdown_task.await;
1802                    }
1803                }
1804
1805                this.update(&mut cx, |this, cx| {
1806                    this.start_language_server(worktree_id, worktree_path, language, cx);
1807                });
1808            }
1809        })
1810        .detach();
1811    }
1812
1813    fn on_lsp_diagnostics_published(
1814        &mut self,
1815        server_id: usize,
1816        mut params: lsp::PublishDiagnosticsParams,
1817        adapter: &Arc<dyn LspAdapter>,
1818        disk_based_diagnostics_progress_token: Option<&str>,
1819        cx: &mut ModelContext<Self>,
1820    ) {
1821        adapter.process_diagnostics(&mut params);
1822        if disk_based_diagnostics_progress_token.is_none() {
1823            self.disk_based_diagnostics_started(cx);
1824            self.broadcast_language_server_update(
1825                server_id,
1826                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
1827                    proto::LspDiskBasedDiagnosticsUpdating {},
1828                ),
1829            );
1830        }
1831        self.update_diagnostics(params, adapter.disk_based_diagnostic_sources(), cx)
1832            .log_err();
1833        if disk_based_diagnostics_progress_token.is_none() {
1834            self.disk_based_diagnostics_finished(cx);
1835            self.broadcast_language_server_update(
1836                server_id,
1837                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1838                    proto::LspDiskBasedDiagnosticsUpdated {},
1839                ),
1840            );
1841        }
1842    }
1843
1844    fn on_lsp_progress(
1845        &mut self,
1846        progress: lsp::ProgressParams,
1847        server_id: usize,
1848        disk_based_diagnostics_progress_token: Option<&str>,
1849        cx: &mut ModelContext<Self>,
1850    ) {
1851        let token = match progress.token {
1852            lsp::NumberOrString::String(token) => token,
1853            lsp::NumberOrString::Number(token) => {
1854                log::info!("skipping numeric progress token {}", token);
1855                return;
1856            }
1857        };
1858        let progress = match progress.value {
1859            lsp::ProgressParamsValue::WorkDone(value) => value,
1860        };
1861        let language_server_status =
1862            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
1863                status
1864            } else {
1865                return;
1866            };
1867        match progress {
1868            lsp::WorkDoneProgress::Begin(_) => {
1869                if Some(token.as_str()) == disk_based_diagnostics_progress_token {
1870                    language_server_status.pending_diagnostic_updates += 1;
1871                    if language_server_status.pending_diagnostic_updates == 1 {
1872                        self.disk_based_diagnostics_started(cx);
1873                        self.broadcast_language_server_update(
1874                            server_id,
1875                            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
1876                                proto::LspDiskBasedDiagnosticsUpdating {},
1877                            ),
1878                        );
1879                    }
1880                } else {
1881                    self.on_lsp_work_start(server_id, token.clone(), cx);
1882                    self.broadcast_language_server_update(
1883                        server_id,
1884                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
1885                            token,
1886                        }),
1887                    );
1888                }
1889            }
1890            lsp::WorkDoneProgress::Report(report) => {
1891                if Some(token.as_str()) != disk_based_diagnostics_progress_token {
1892                    self.on_lsp_work_progress(
1893                        server_id,
1894                        token.clone(),
1895                        LanguageServerProgress {
1896                            message: report.message.clone(),
1897                            percentage: report.percentage.map(|p| p as usize),
1898                            last_update_at: Instant::now(),
1899                        },
1900                        cx,
1901                    );
1902                    self.broadcast_language_server_update(
1903                        server_id,
1904                        proto::update_language_server::Variant::WorkProgress(
1905                            proto::LspWorkProgress {
1906                                token,
1907                                message: report.message,
1908                                percentage: report.percentage.map(|p| p as u32),
1909                            },
1910                        ),
1911                    );
1912                }
1913            }
1914            lsp::WorkDoneProgress::End(_) => {
1915                if Some(token.as_str()) == disk_based_diagnostics_progress_token {
1916                    language_server_status.pending_diagnostic_updates -= 1;
1917                    if language_server_status.pending_diagnostic_updates == 0 {
1918                        self.disk_based_diagnostics_finished(cx);
1919                        self.broadcast_language_server_update(
1920                            server_id,
1921                            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1922                                proto::LspDiskBasedDiagnosticsUpdated {},
1923                            ),
1924                        );
1925                    }
1926                } else {
1927                    self.on_lsp_work_end(server_id, token.clone(), cx);
1928                    self.broadcast_language_server_update(
1929                        server_id,
1930                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
1931                            token,
1932                        }),
1933                    );
1934                }
1935            }
1936        }
1937    }
1938
1939    fn on_lsp_work_start(
1940        &mut self,
1941        language_server_id: usize,
1942        token: String,
1943        cx: &mut ModelContext<Self>,
1944    ) {
1945        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1946            status.pending_work.insert(
1947                token,
1948                LanguageServerProgress {
1949                    message: None,
1950                    percentage: None,
1951                    last_update_at: Instant::now(),
1952                },
1953            );
1954            cx.notify();
1955        }
1956    }
1957
1958    fn on_lsp_work_progress(
1959        &mut self,
1960        language_server_id: usize,
1961        token: String,
1962        progress: LanguageServerProgress,
1963        cx: &mut ModelContext<Self>,
1964    ) {
1965        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1966            status.pending_work.insert(token, progress);
1967            cx.notify();
1968        }
1969    }
1970
1971    fn on_lsp_work_end(
1972        &mut self,
1973        language_server_id: usize,
1974        token: String,
1975        cx: &mut ModelContext<Self>,
1976    ) {
1977        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
1978            status.pending_work.remove(&token);
1979            cx.notify();
1980        }
1981    }
1982
1983    async fn on_lsp_workspace_edit(
1984        this: WeakModelHandle<Self>,
1985        params: lsp::ApplyWorkspaceEditParams,
1986        server_id: usize,
1987        adapter: Arc<dyn LspAdapter>,
1988        language_server: Arc<LanguageServer>,
1989        mut cx: AsyncAppContext,
1990    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
1991        let this = this
1992            .upgrade(&cx)
1993            .ok_or_else(|| anyhow!("project project closed"))?;
1994        let transaction = Self::deserialize_workspace_edit(
1995            this.clone(),
1996            params.edit,
1997            true,
1998            adapter.clone(),
1999            language_server.clone(),
2000            &mut cx,
2001        )
2002        .await
2003        .log_err();
2004        this.update(&mut cx, |this, _| {
2005            if let Some(transaction) = transaction {
2006                this.last_workspace_edits_by_language_server
2007                    .insert(server_id, transaction);
2008            }
2009        });
2010        Ok(lsp::ApplyWorkspaceEditResponse {
2011            applied: true,
2012            failed_change: None,
2013            failure_reason: None,
2014        })
2015    }
2016
2017    fn broadcast_language_server_update(
2018        &self,
2019        language_server_id: usize,
2020        event: proto::update_language_server::Variant,
2021    ) {
2022        if let Some(project_id) = self.remote_id() {
2023            self.client
2024                .send(proto::UpdateLanguageServer {
2025                    project_id,
2026                    language_server_id: language_server_id as u64,
2027                    variant: Some(event),
2028                })
2029                .log_err();
2030        }
2031    }
2032
2033    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2034        for (_, server) in self.language_servers.values() {
2035            server
2036                .notify::<lsp::notification::DidChangeConfiguration>(
2037                    lsp::DidChangeConfigurationParams {
2038                        settings: settings.clone(),
2039                    },
2040                )
2041                .ok();
2042        }
2043        *self.language_server_settings.lock() = settings;
2044    }
2045
2046    pub fn language_server_statuses(
2047        &self,
2048    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2049        self.language_server_statuses.values()
2050    }
2051
2052    pub fn update_diagnostics(
2053        &mut self,
2054        params: lsp::PublishDiagnosticsParams,
2055        disk_based_sources: &[&str],
2056        cx: &mut ModelContext<Self>,
2057    ) -> Result<()> {
2058        let abs_path = params
2059            .uri
2060            .to_file_path()
2061            .map_err(|_| anyhow!("URI is not a file"))?;
2062        let mut next_group_id = 0;
2063        let mut diagnostics = Vec::default();
2064        let mut primary_diagnostic_group_ids = HashMap::default();
2065        let mut sources_by_group_id = HashMap::default();
2066        let mut supporting_diagnostics = HashMap::default();
2067        for diagnostic in &params.diagnostics {
2068            let source = diagnostic.source.as_ref();
2069            let code = diagnostic.code.as_ref().map(|code| match code {
2070                lsp::NumberOrString::Number(code) => code.to_string(),
2071                lsp::NumberOrString::String(code) => code.clone(),
2072            });
2073            let range = range_from_lsp(diagnostic.range);
2074            let is_supporting = diagnostic
2075                .related_information
2076                .as_ref()
2077                .map_or(false, |infos| {
2078                    infos.iter().any(|info| {
2079                        primary_diagnostic_group_ids.contains_key(&(
2080                            source,
2081                            code.clone(),
2082                            range_from_lsp(info.location.range),
2083                        ))
2084                    })
2085                });
2086
2087            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2088                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2089            });
2090
2091            if is_supporting {
2092                supporting_diagnostics.insert(
2093                    (source, code.clone(), range),
2094                    (diagnostic.severity, is_unnecessary),
2095                );
2096            } else {
2097                let group_id = post_inc(&mut next_group_id);
2098                let is_disk_based = source.map_or(false, |source| {
2099                    disk_based_sources.contains(&source.as_str())
2100                });
2101
2102                sources_by_group_id.insert(group_id, source);
2103                primary_diagnostic_group_ids
2104                    .insert((source, code.clone(), range.clone()), group_id);
2105
2106                diagnostics.push(DiagnosticEntry {
2107                    range,
2108                    diagnostic: Diagnostic {
2109                        code: code.clone(),
2110                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2111                        message: diagnostic.message.clone(),
2112                        group_id,
2113                        is_primary: true,
2114                        is_valid: true,
2115                        is_disk_based,
2116                        is_unnecessary,
2117                    },
2118                });
2119                if let Some(infos) = &diagnostic.related_information {
2120                    for info in infos {
2121                        if info.location.uri == params.uri && !info.message.is_empty() {
2122                            let range = range_from_lsp(info.location.range);
2123                            diagnostics.push(DiagnosticEntry {
2124                                range,
2125                                diagnostic: Diagnostic {
2126                                    code: code.clone(),
2127                                    severity: DiagnosticSeverity::INFORMATION,
2128                                    message: info.message.clone(),
2129                                    group_id,
2130                                    is_primary: false,
2131                                    is_valid: true,
2132                                    is_disk_based,
2133                                    is_unnecessary: false,
2134                                },
2135                            });
2136                        }
2137                    }
2138                }
2139            }
2140        }
2141
2142        for entry in &mut diagnostics {
2143            let diagnostic = &mut entry.diagnostic;
2144            if !diagnostic.is_primary {
2145                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2146                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2147                    source,
2148                    diagnostic.code.clone(),
2149                    entry.range.clone(),
2150                )) {
2151                    if let Some(severity) = severity {
2152                        diagnostic.severity = severity;
2153                    }
2154                    diagnostic.is_unnecessary = is_unnecessary;
2155                }
2156            }
2157        }
2158
2159        self.update_diagnostic_entries(abs_path, params.version, diagnostics, cx)?;
2160        Ok(())
2161    }
2162
2163    pub fn update_diagnostic_entries(
2164        &mut self,
2165        abs_path: PathBuf,
2166        version: Option<i32>,
2167        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2168        cx: &mut ModelContext<Project>,
2169    ) -> Result<(), anyhow::Error> {
2170        let (worktree, relative_path) = self
2171            .find_local_worktree(&abs_path, cx)
2172            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2173        if !worktree.read(cx).is_visible() {
2174            return Ok(());
2175        }
2176
2177        let project_path = ProjectPath {
2178            worktree_id: worktree.read(cx).id(),
2179            path: relative_path.into(),
2180        };
2181        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2182            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2183        }
2184
2185        let updated = worktree.update(cx, |worktree, cx| {
2186            worktree
2187                .as_local_mut()
2188                .ok_or_else(|| anyhow!("not a local worktree"))?
2189                .update_diagnostics(project_path.path.clone(), diagnostics, cx)
2190        })?;
2191        if updated {
2192            cx.emit(Event::DiagnosticsUpdated(project_path));
2193        }
2194        Ok(())
2195    }
2196
2197    fn update_buffer_diagnostics(
2198        &mut self,
2199        buffer: &ModelHandle<Buffer>,
2200        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2201        version: Option<i32>,
2202        cx: &mut ModelContext<Self>,
2203    ) -> Result<()> {
2204        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2205            Ordering::Equal
2206                .then_with(|| b.is_primary.cmp(&a.is_primary))
2207                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2208                .then_with(|| a.severity.cmp(&b.severity))
2209                .then_with(|| a.message.cmp(&b.message))
2210        }
2211
2212        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2213
2214        diagnostics.sort_unstable_by(|a, b| {
2215            Ordering::Equal
2216                .then_with(|| a.range.start.cmp(&b.range.start))
2217                .then_with(|| b.range.end.cmp(&a.range.end))
2218                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2219        });
2220
2221        let mut sanitized_diagnostics = Vec::new();
2222        let edits_since_save = Patch::new(
2223            snapshot
2224                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2225                .collect(),
2226        );
2227        for entry in diagnostics {
2228            let start;
2229            let end;
2230            if entry.diagnostic.is_disk_based {
2231                // Some diagnostics are based on files on disk instead of buffers'
2232                // current contents. Adjust these diagnostics' ranges to reflect
2233                // any unsaved edits.
2234                start = edits_since_save.old_to_new(entry.range.start);
2235                end = edits_since_save.old_to_new(entry.range.end);
2236            } else {
2237                start = entry.range.start;
2238                end = entry.range.end;
2239            }
2240
2241            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2242                ..snapshot.clip_point_utf16(end, Bias::Right);
2243
2244            // Expand empty ranges by one character
2245            if range.start == range.end {
2246                range.end.column += 1;
2247                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2248                if range.start == range.end && range.end.column > 0 {
2249                    range.start.column -= 1;
2250                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2251                }
2252            }
2253
2254            sanitized_diagnostics.push(DiagnosticEntry {
2255                range,
2256                diagnostic: entry.diagnostic,
2257            });
2258        }
2259        drop(edits_since_save);
2260
2261        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2262        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2263        Ok(())
2264    }
2265
2266    pub fn reload_buffers(
2267        &self,
2268        buffers: HashSet<ModelHandle<Buffer>>,
2269        push_to_history: bool,
2270        cx: &mut ModelContext<Self>,
2271    ) -> Task<Result<ProjectTransaction>> {
2272        let mut local_buffers = Vec::new();
2273        let mut remote_buffers = None;
2274        for buffer_handle in buffers {
2275            let buffer = buffer_handle.read(cx);
2276            if buffer.is_dirty() {
2277                if let Some(file) = File::from_dyn(buffer.file()) {
2278                    if file.is_local() {
2279                        local_buffers.push(buffer_handle);
2280                    } else {
2281                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2282                    }
2283                }
2284            }
2285        }
2286
2287        let remote_buffers = self.remote_id().zip(remote_buffers);
2288        let client = self.client.clone();
2289
2290        cx.spawn(|this, mut cx| async move {
2291            let mut project_transaction = ProjectTransaction::default();
2292
2293            if let Some((project_id, remote_buffers)) = remote_buffers {
2294                let response = client
2295                    .request(proto::ReloadBuffers {
2296                        project_id,
2297                        buffer_ids: remote_buffers
2298                            .iter()
2299                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2300                            .collect(),
2301                    })
2302                    .await?
2303                    .transaction
2304                    .ok_or_else(|| anyhow!("missing transaction"))?;
2305                project_transaction = this
2306                    .update(&mut cx, |this, cx| {
2307                        this.deserialize_project_transaction(response, push_to_history, cx)
2308                    })
2309                    .await?;
2310            }
2311
2312            for buffer in local_buffers {
2313                let transaction = buffer
2314                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2315                    .await?;
2316                buffer.update(&mut cx, |buffer, cx| {
2317                    if let Some(transaction) = transaction {
2318                        if !push_to_history {
2319                            buffer.forget_transaction(transaction.id);
2320                        }
2321                        project_transaction.0.insert(cx.handle(), transaction);
2322                    }
2323                });
2324            }
2325
2326            Ok(project_transaction)
2327        })
2328    }
2329
2330    pub fn format(
2331        &self,
2332        buffers: HashSet<ModelHandle<Buffer>>,
2333        push_to_history: bool,
2334        cx: &mut ModelContext<Project>,
2335    ) -> Task<Result<ProjectTransaction>> {
2336        let mut local_buffers = Vec::new();
2337        let mut remote_buffers = None;
2338        for buffer_handle in buffers {
2339            let buffer = buffer_handle.read(cx);
2340            if let Some(file) = File::from_dyn(buffer.file()) {
2341                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2342                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2343                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2344                    }
2345                } else {
2346                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2347                }
2348            } else {
2349                return Task::ready(Ok(Default::default()));
2350            }
2351        }
2352
2353        let remote_buffers = self.remote_id().zip(remote_buffers);
2354        let client = self.client.clone();
2355
2356        cx.spawn(|this, mut cx| async move {
2357            let mut project_transaction = ProjectTransaction::default();
2358
2359            if let Some((project_id, remote_buffers)) = remote_buffers {
2360                let response = client
2361                    .request(proto::FormatBuffers {
2362                        project_id,
2363                        buffer_ids: remote_buffers
2364                            .iter()
2365                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2366                            .collect(),
2367                    })
2368                    .await?
2369                    .transaction
2370                    .ok_or_else(|| anyhow!("missing transaction"))?;
2371                project_transaction = this
2372                    .update(&mut cx, |this, cx| {
2373                        this.deserialize_project_transaction(response, push_to_history, cx)
2374                    })
2375                    .await?;
2376            }
2377
2378            for (buffer, buffer_abs_path, language_server) in local_buffers {
2379                let text_document = lsp::TextDocumentIdentifier::new(
2380                    lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
2381                );
2382                let capabilities = &language_server.capabilities();
2383                let tab_size = cx.update(|cx| {
2384                    let language_name = buffer.read(cx).language().map(|language| language.name());
2385                    cx.global::<Settings>().tab_size(language_name.as_deref())
2386                });
2387                let lsp_edits = if capabilities
2388                    .document_formatting_provider
2389                    .as_ref()
2390                    .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2391                {
2392                    language_server
2393                        .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2394                            text_document,
2395                            options: lsp::FormattingOptions {
2396                                tab_size,
2397                                insert_spaces: true,
2398                                insert_final_newline: Some(true),
2399                                ..Default::default()
2400                            },
2401                            work_done_progress_params: Default::default(),
2402                        })
2403                        .await?
2404                } else if capabilities
2405                    .document_range_formatting_provider
2406                    .as_ref()
2407                    .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2408                {
2409                    let buffer_start = lsp::Position::new(0, 0);
2410                    let buffer_end =
2411                        buffer.read_with(&cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2412                    language_server
2413                        .request::<lsp::request::RangeFormatting>(
2414                            lsp::DocumentRangeFormattingParams {
2415                                text_document,
2416                                range: lsp::Range::new(buffer_start, buffer_end),
2417                                options: lsp::FormattingOptions {
2418                                    tab_size: 4,
2419                                    insert_spaces: true,
2420                                    insert_final_newline: Some(true),
2421                                    ..Default::default()
2422                                },
2423                                work_done_progress_params: Default::default(),
2424                            },
2425                        )
2426                        .await?
2427                } else {
2428                    continue;
2429                };
2430
2431                if let Some(lsp_edits) = lsp_edits {
2432                    let edits = this
2433                        .update(&mut cx, |this, cx| {
2434                            this.edits_from_lsp(&buffer, lsp_edits, None, cx)
2435                        })
2436                        .await?;
2437                    buffer.update(&mut cx, |buffer, cx| {
2438                        buffer.finalize_last_transaction();
2439                        buffer.start_transaction();
2440                        for (range, text) in edits {
2441                            buffer.edit([(range, text)], cx);
2442                        }
2443                        if buffer.end_transaction(cx).is_some() {
2444                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
2445                            if !push_to_history {
2446                                buffer.forget_transaction(transaction.id);
2447                            }
2448                            project_transaction.0.insert(cx.handle(), transaction);
2449                        }
2450                    });
2451                }
2452            }
2453
2454            Ok(project_transaction)
2455        })
2456    }
2457
2458    pub fn definition<T: ToPointUtf16>(
2459        &self,
2460        buffer: &ModelHandle<Buffer>,
2461        position: T,
2462        cx: &mut ModelContext<Self>,
2463    ) -> Task<Result<Vec<Location>>> {
2464        let position = position.to_point_utf16(buffer.read(cx));
2465        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
2466    }
2467
2468    pub fn references<T: ToPointUtf16>(
2469        &self,
2470        buffer: &ModelHandle<Buffer>,
2471        position: T,
2472        cx: &mut ModelContext<Self>,
2473    ) -> Task<Result<Vec<Location>>> {
2474        let position = position.to_point_utf16(buffer.read(cx));
2475        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
2476    }
2477
2478    pub fn document_highlights<T: ToPointUtf16>(
2479        &self,
2480        buffer: &ModelHandle<Buffer>,
2481        position: T,
2482        cx: &mut ModelContext<Self>,
2483    ) -> Task<Result<Vec<DocumentHighlight>>> {
2484        let position = position.to_point_utf16(buffer.read(cx));
2485
2486        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
2487    }
2488
2489    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
2490        if self.is_local() {
2491            let mut requests = Vec::new();
2492            for ((worktree_id, _), (lsp_adapter, language_server)) in self.language_servers.iter() {
2493                let worktree_id = *worktree_id;
2494                if let Some(worktree) = self
2495                    .worktree_for_id(worktree_id, cx)
2496                    .and_then(|worktree| worktree.read(cx).as_local())
2497                {
2498                    let lsp_adapter = lsp_adapter.clone();
2499                    let worktree_abs_path = worktree.abs_path().clone();
2500                    requests.push(
2501                        language_server
2502                            .request::<lsp::request::WorkspaceSymbol>(lsp::WorkspaceSymbolParams {
2503                                query: query.to_string(),
2504                                ..Default::default()
2505                            })
2506                            .log_err()
2507                            .map(move |response| {
2508                                (
2509                                    lsp_adapter,
2510                                    worktree_id,
2511                                    worktree_abs_path,
2512                                    response.unwrap_or_default(),
2513                                )
2514                            }),
2515                    );
2516                }
2517            }
2518
2519            cx.spawn_weak(|this, cx| async move {
2520                let responses = futures::future::join_all(requests).await;
2521                let this = if let Some(this) = this.upgrade(&cx) {
2522                    this
2523                } else {
2524                    return Ok(Default::default());
2525                };
2526                this.read_with(&cx, |this, cx| {
2527                    let mut symbols = Vec::new();
2528                    for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
2529                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
2530                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
2531                            let mut worktree_id = source_worktree_id;
2532                            let path;
2533                            if let Some((worktree, rel_path)) =
2534                                this.find_local_worktree(&abs_path, cx)
2535                            {
2536                                worktree_id = worktree.read(cx).id();
2537                                path = rel_path;
2538                            } else {
2539                                path = relativize_path(&worktree_abs_path, &abs_path);
2540                            }
2541
2542                            let label = this
2543                                .languages
2544                                .select_language(&path)
2545                                .and_then(|language| {
2546                                    language.label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
2547                                })
2548                                .unwrap_or_else(|| CodeLabel::plain(lsp_symbol.name.clone(), None));
2549                            let signature = this.symbol_signature(worktree_id, &path);
2550
2551                            Some(Symbol {
2552                                source_worktree_id,
2553                                worktree_id,
2554                                language_server_name: adapter.name(),
2555                                name: lsp_symbol.name,
2556                                kind: lsp_symbol.kind,
2557                                label,
2558                                path,
2559                                range: range_from_lsp(lsp_symbol.location.range),
2560                                signature,
2561                            })
2562                        }));
2563                    }
2564                    Ok(symbols)
2565                })
2566            })
2567        } else if let Some(project_id) = self.remote_id() {
2568            let request = self.client.request(proto::GetProjectSymbols {
2569                project_id,
2570                query: query.to_string(),
2571            });
2572            cx.spawn_weak(|this, cx| async move {
2573                let response = request.await?;
2574                let mut symbols = Vec::new();
2575                if let Some(this) = this.upgrade(&cx) {
2576                    this.read_with(&cx, |this, _| {
2577                        symbols.extend(
2578                            response
2579                                .symbols
2580                                .into_iter()
2581                                .filter_map(|symbol| this.deserialize_symbol(symbol).log_err()),
2582                        );
2583                    })
2584                }
2585                Ok(symbols)
2586            })
2587        } else {
2588            Task::ready(Ok(Default::default()))
2589        }
2590    }
2591
2592    pub fn open_buffer_for_symbol(
2593        &mut self,
2594        symbol: &Symbol,
2595        cx: &mut ModelContext<Self>,
2596    ) -> Task<Result<ModelHandle<Buffer>>> {
2597        if self.is_local() {
2598            let (lsp_adapter, language_server) = if let Some(server) = self.language_servers.get(&(
2599                symbol.source_worktree_id,
2600                symbol.language_server_name.clone(),
2601            )) {
2602                server.clone()
2603            } else {
2604                return Task::ready(Err(anyhow!(
2605                    "language server for worktree and language not found"
2606                )));
2607            };
2608
2609            let worktree_abs_path = if let Some(worktree_abs_path) = self
2610                .worktree_for_id(symbol.worktree_id, cx)
2611                .and_then(|worktree| worktree.read(cx).as_local())
2612                .map(|local_worktree| local_worktree.abs_path())
2613            {
2614                worktree_abs_path
2615            } else {
2616                return Task::ready(Err(anyhow!("worktree not found for symbol")));
2617            };
2618            let symbol_abs_path = worktree_abs_path.join(&symbol.path);
2619            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
2620                uri
2621            } else {
2622                return Task::ready(Err(anyhow!("invalid symbol path")));
2623            };
2624
2625            self.open_local_buffer_via_lsp(symbol_uri, lsp_adapter, language_server, cx)
2626        } else if let Some(project_id) = self.remote_id() {
2627            let request = self.client.request(proto::OpenBufferForSymbol {
2628                project_id,
2629                symbol: Some(serialize_symbol(symbol)),
2630            });
2631            cx.spawn(|this, mut cx| async move {
2632                let response = request.await?;
2633                let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
2634                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
2635                    .await
2636            })
2637        } else {
2638            Task::ready(Err(anyhow!("project does not have a remote id")))
2639        }
2640    }
2641
2642    pub fn completions<T: ToPointUtf16>(
2643        &self,
2644        source_buffer_handle: &ModelHandle<Buffer>,
2645        position: T,
2646        cx: &mut ModelContext<Self>,
2647    ) -> Task<Result<Vec<Completion>>> {
2648        let source_buffer_handle = source_buffer_handle.clone();
2649        let source_buffer = source_buffer_handle.read(cx);
2650        let buffer_id = source_buffer.remote_id();
2651        let language = source_buffer.language().cloned();
2652        let worktree;
2653        let buffer_abs_path;
2654        if let Some(file) = File::from_dyn(source_buffer.file()) {
2655            worktree = file.worktree.clone();
2656            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
2657        } else {
2658            return Task::ready(Ok(Default::default()));
2659        };
2660
2661        let position = position.to_point_utf16(source_buffer);
2662        let anchor = source_buffer.anchor_after(position);
2663
2664        if worktree.read(cx).as_local().is_some() {
2665            let buffer_abs_path = buffer_abs_path.unwrap();
2666            let (_, lang_server) =
2667                if let Some(server) = self.language_server_for_buffer(source_buffer, cx) {
2668                    server.clone()
2669                } else {
2670                    return Task::ready(Ok(Default::default()));
2671                };
2672
2673            cx.spawn(|_, cx| async move {
2674                let completions = lang_server
2675                    .request::<lsp::request::Completion>(lsp::CompletionParams {
2676                        text_document_position: lsp::TextDocumentPositionParams::new(
2677                            lsp::TextDocumentIdentifier::new(
2678                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
2679                            ),
2680                            point_to_lsp(position),
2681                        ),
2682                        context: Default::default(),
2683                        work_done_progress_params: Default::default(),
2684                        partial_result_params: Default::default(),
2685                    })
2686                    .await
2687                    .context("lsp completion request failed")?;
2688
2689                let completions = if let Some(completions) = completions {
2690                    match completions {
2691                        lsp::CompletionResponse::Array(completions) => completions,
2692                        lsp::CompletionResponse::List(list) => list.items,
2693                    }
2694                } else {
2695                    Default::default()
2696                };
2697
2698                source_buffer_handle.read_with(&cx, |this, _| {
2699                    let snapshot = this.snapshot();
2700                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
2701                    let mut range_for_token = None;
2702                    Ok(completions
2703                        .into_iter()
2704                        .filter_map(|lsp_completion| {
2705                            let (old_range, new_text) = match lsp_completion.text_edit.as_ref() {
2706                                // If the language server provides a range to overwrite, then
2707                                // check that the range is valid.
2708                                Some(lsp::CompletionTextEdit::Edit(edit)) => {
2709                                    let range = range_from_lsp(edit.range);
2710                                    let start = snapshot.clip_point_utf16(range.start, Bias::Left);
2711                                    let end = snapshot.clip_point_utf16(range.end, Bias::Left);
2712                                    if start != range.start || end != range.end {
2713                                        log::info!("completion out of expected range");
2714                                        return None;
2715                                    }
2716                                    (
2717                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
2718                                        edit.new_text.clone(),
2719                                    )
2720                                }
2721                                // If the language server does not provide a range, then infer
2722                                // the range based on the syntax tree.
2723                                None => {
2724                                    if position != clipped_position {
2725                                        log::info!("completion out of expected range");
2726                                        return None;
2727                                    }
2728                                    let Range { start, end } = range_for_token
2729                                        .get_or_insert_with(|| {
2730                                            let offset = position.to_offset(&snapshot);
2731                                            snapshot
2732                                                .range_for_word_token_at(offset)
2733                                                .unwrap_or_else(|| offset..offset)
2734                                        })
2735                                        .clone();
2736                                    let text = lsp_completion
2737                                        .insert_text
2738                                        .as_ref()
2739                                        .unwrap_or(&lsp_completion.label)
2740                                        .clone();
2741                                    (
2742                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
2743                                        text.clone(),
2744                                    )
2745                                }
2746                                Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
2747                                    log::info!("unsupported insert/replace completion");
2748                                    return None;
2749                                }
2750                            };
2751
2752                            Some(Completion {
2753                                old_range,
2754                                new_text,
2755                                label: language
2756                                    .as_ref()
2757                                    .and_then(|l| l.label_for_completion(&lsp_completion))
2758                                    .unwrap_or_else(|| {
2759                                        CodeLabel::plain(
2760                                            lsp_completion.label.clone(),
2761                                            lsp_completion.filter_text.as_deref(),
2762                                        )
2763                                    }),
2764                                lsp_completion,
2765                            })
2766                        })
2767                        .collect())
2768                })
2769            })
2770        } else if let Some(project_id) = self.remote_id() {
2771            let rpc = self.client.clone();
2772            let message = proto::GetCompletions {
2773                project_id,
2774                buffer_id,
2775                position: Some(language::proto::serialize_anchor(&anchor)),
2776                version: serialize_version(&source_buffer.version()),
2777            };
2778            cx.spawn_weak(|_, mut cx| async move {
2779                let response = rpc.request(message).await?;
2780
2781                source_buffer_handle
2782                    .update(&mut cx, |buffer, _| {
2783                        buffer.wait_for_version(deserialize_version(response.version))
2784                    })
2785                    .await;
2786
2787                response
2788                    .completions
2789                    .into_iter()
2790                    .map(|completion| {
2791                        language::proto::deserialize_completion(completion, language.as_ref())
2792                    })
2793                    .collect()
2794            })
2795        } else {
2796            Task::ready(Ok(Default::default()))
2797        }
2798    }
2799
2800    pub fn apply_additional_edits_for_completion(
2801        &self,
2802        buffer_handle: ModelHandle<Buffer>,
2803        completion: Completion,
2804        push_to_history: bool,
2805        cx: &mut ModelContext<Self>,
2806    ) -> Task<Result<Option<Transaction>>> {
2807        let buffer = buffer_handle.read(cx);
2808        let buffer_id = buffer.remote_id();
2809
2810        if self.is_local() {
2811            let (_, lang_server) = if let Some(server) = self.language_server_for_buffer(buffer, cx)
2812            {
2813                server.clone()
2814            } else {
2815                return Task::ready(Ok(Default::default()));
2816            };
2817
2818            cx.spawn(|this, mut cx| async move {
2819                let resolved_completion = lang_server
2820                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
2821                    .await?;
2822                if let Some(edits) = resolved_completion.additional_text_edits {
2823                    let edits = this
2824                        .update(&mut cx, |this, cx| {
2825                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
2826                        })
2827                        .await?;
2828                    buffer_handle.update(&mut cx, |buffer, cx| {
2829                        buffer.finalize_last_transaction();
2830                        buffer.start_transaction();
2831                        for (range, text) in edits {
2832                            buffer.edit([(range, text)], cx);
2833                        }
2834                        let transaction = if buffer.end_transaction(cx).is_some() {
2835                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
2836                            if !push_to_history {
2837                                buffer.forget_transaction(transaction.id);
2838                            }
2839                            Some(transaction)
2840                        } else {
2841                            None
2842                        };
2843                        Ok(transaction)
2844                    })
2845                } else {
2846                    Ok(None)
2847                }
2848            })
2849        } else if let Some(project_id) = self.remote_id() {
2850            let client = self.client.clone();
2851            cx.spawn(|_, mut cx| async move {
2852                let response = client
2853                    .request(proto::ApplyCompletionAdditionalEdits {
2854                        project_id,
2855                        buffer_id,
2856                        completion: Some(language::proto::serialize_completion(&completion)),
2857                    })
2858                    .await?;
2859
2860                if let Some(transaction) = response.transaction {
2861                    let transaction = language::proto::deserialize_transaction(transaction)?;
2862                    buffer_handle
2863                        .update(&mut cx, |buffer, _| {
2864                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
2865                        })
2866                        .await;
2867                    if push_to_history {
2868                        buffer_handle.update(&mut cx, |buffer, _| {
2869                            buffer.push_transaction(transaction.clone(), Instant::now());
2870                        });
2871                    }
2872                    Ok(Some(transaction))
2873                } else {
2874                    Ok(None)
2875                }
2876            })
2877        } else {
2878            Task::ready(Err(anyhow!("project does not have a remote id")))
2879        }
2880    }
2881
2882    pub fn code_actions<T: Clone + ToOffset>(
2883        &self,
2884        buffer_handle: &ModelHandle<Buffer>,
2885        range: Range<T>,
2886        cx: &mut ModelContext<Self>,
2887    ) -> Task<Result<Vec<CodeAction>>> {
2888        let buffer_handle = buffer_handle.clone();
2889        let buffer = buffer_handle.read(cx);
2890        let snapshot = buffer.snapshot();
2891        let relevant_diagnostics = snapshot
2892            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
2893            .map(|entry| entry.to_lsp_diagnostic_stub())
2894            .collect();
2895        let buffer_id = buffer.remote_id();
2896        let worktree;
2897        let buffer_abs_path;
2898        if let Some(file) = File::from_dyn(buffer.file()) {
2899            worktree = file.worktree.clone();
2900            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
2901        } else {
2902            return Task::ready(Ok(Default::default()));
2903        };
2904        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
2905
2906        if worktree.read(cx).as_local().is_some() {
2907            let buffer_abs_path = buffer_abs_path.unwrap();
2908            let (_, lang_server) = if let Some(server) = self.language_server_for_buffer(buffer, cx)
2909            {
2910                server.clone()
2911            } else {
2912                return Task::ready(Ok(Default::default()));
2913            };
2914
2915            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
2916            cx.foreground().spawn(async move {
2917                if !lang_server.capabilities().code_action_provider.is_some() {
2918                    return Ok(Default::default());
2919                }
2920
2921                Ok(lang_server
2922                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
2923                        text_document: lsp::TextDocumentIdentifier::new(
2924                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
2925                        ),
2926                        range: lsp_range,
2927                        work_done_progress_params: Default::default(),
2928                        partial_result_params: Default::default(),
2929                        context: lsp::CodeActionContext {
2930                            diagnostics: relevant_diagnostics,
2931                            only: Some(vec![
2932                                lsp::CodeActionKind::QUICKFIX,
2933                                lsp::CodeActionKind::REFACTOR,
2934                                lsp::CodeActionKind::REFACTOR_EXTRACT,
2935                                lsp::CodeActionKind::SOURCE,
2936                            ]),
2937                        },
2938                    })
2939                    .await?
2940                    .unwrap_or_default()
2941                    .into_iter()
2942                    .filter_map(|entry| {
2943                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
2944                            Some(CodeAction {
2945                                range: range.clone(),
2946                                lsp_action,
2947                            })
2948                        } else {
2949                            None
2950                        }
2951                    })
2952                    .collect())
2953            })
2954        } else if let Some(project_id) = self.remote_id() {
2955            let rpc = self.client.clone();
2956            let version = buffer.version();
2957            cx.spawn_weak(|_, mut cx| async move {
2958                let response = rpc
2959                    .request(proto::GetCodeActions {
2960                        project_id,
2961                        buffer_id,
2962                        start: Some(language::proto::serialize_anchor(&range.start)),
2963                        end: Some(language::proto::serialize_anchor(&range.end)),
2964                        version: serialize_version(&version),
2965                    })
2966                    .await?;
2967
2968                buffer_handle
2969                    .update(&mut cx, |buffer, _| {
2970                        buffer.wait_for_version(deserialize_version(response.version))
2971                    })
2972                    .await;
2973
2974                response
2975                    .actions
2976                    .into_iter()
2977                    .map(language::proto::deserialize_code_action)
2978                    .collect()
2979            })
2980        } else {
2981            Task::ready(Ok(Default::default()))
2982        }
2983    }
2984
2985    pub fn apply_code_action(
2986        &self,
2987        buffer_handle: ModelHandle<Buffer>,
2988        mut action: CodeAction,
2989        push_to_history: bool,
2990        cx: &mut ModelContext<Self>,
2991    ) -> Task<Result<ProjectTransaction>> {
2992        if self.is_local() {
2993            let buffer = buffer_handle.read(cx);
2994            let (lsp_adapter, lang_server) =
2995                if let Some(server) = self.language_server_for_buffer(buffer, cx) {
2996                    server.clone()
2997                } else {
2998                    return Task::ready(Ok(Default::default()));
2999                };
3000            let range = action.range.to_point_utf16(buffer);
3001
3002            cx.spawn(|this, mut cx| async move {
3003                if let Some(lsp_range) = action
3004                    .lsp_action
3005                    .data
3006                    .as_mut()
3007                    .and_then(|d| d.get_mut("codeActionParams"))
3008                    .and_then(|d| d.get_mut("range"))
3009                {
3010                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3011                    action.lsp_action = lang_server
3012                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3013                        .await?;
3014                } else {
3015                    let actions = this
3016                        .update(&mut cx, |this, cx| {
3017                            this.code_actions(&buffer_handle, action.range, cx)
3018                        })
3019                        .await?;
3020                    action.lsp_action = actions
3021                        .into_iter()
3022                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3023                        .ok_or_else(|| anyhow!("code action is outdated"))?
3024                        .lsp_action;
3025                }
3026
3027                if let Some(edit) = action.lsp_action.edit {
3028                    Self::deserialize_workspace_edit(
3029                        this,
3030                        edit,
3031                        push_to_history,
3032                        lsp_adapter,
3033                        lang_server,
3034                        &mut cx,
3035                    )
3036                    .await
3037                } else if let Some(command) = action.lsp_action.command {
3038                    this.update(&mut cx, |this, _| {
3039                        this.last_workspace_edits_by_language_server
3040                            .remove(&lang_server.server_id());
3041                    });
3042                    lang_server
3043                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3044                            command: command.command,
3045                            arguments: command.arguments.unwrap_or_default(),
3046                            ..Default::default()
3047                        })
3048                        .await?;
3049                    Ok(this.update(&mut cx, |this, _| {
3050                        this.last_workspace_edits_by_language_server
3051                            .remove(&lang_server.server_id())
3052                            .unwrap_or_default()
3053                    }))
3054                } else {
3055                    Ok(ProjectTransaction::default())
3056                }
3057            })
3058        } else if let Some(project_id) = self.remote_id() {
3059            let client = self.client.clone();
3060            let request = proto::ApplyCodeAction {
3061                project_id,
3062                buffer_id: buffer_handle.read(cx).remote_id(),
3063                action: Some(language::proto::serialize_code_action(&action)),
3064            };
3065            cx.spawn(|this, mut cx| async move {
3066                let response = client
3067                    .request(request)
3068                    .await?
3069                    .transaction
3070                    .ok_or_else(|| anyhow!("missing transaction"))?;
3071                this.update(&mut cx, |this, cx| {
3072                    this.deserialize_project_transaction(response, push_to_history, cx)
3073                })
3074                .await
3075            })
3076        } else {
3077            Task::ready(Err(anyhow!("project does not have a remote id")))
3078        }
3079    }
3080
3081    async fn deserialize_workspace_edit(
3082        this: ModelHandle<Self>,
3083        edit: lsp::WorkspaceEdit,
3084        push_to_history: bool,
3085        lsp_adapter: Arc<dyn LspAdapter>,
3086        language_server: Arc<LanguageServer>,
3087        cx: &mut AsyncAppContext,
3088    ) -> Result<ProjectTransaction> {
3089        let fs = this.read_with(cx, |this, _| this.fs.clone());
3090        let mut operations = Vec::new();
3091        if let Some(document_changes) = edit.document_changes {
3092            match document_changes {
3093                lsp::DocumentChanges::Edits(edits) => {
3094                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3095                }
3096                lsp::DocumentChanges::Operations(ops) => operations = ops,
3097            }
3098        } else if let Some(changes) = edit.changes {
3099            operations.extend(changes.into_iter().map(|(uri, edits)| {
3100                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3101                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3102                        uri,
3103                        version: None,
3104                    },
3105                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3106                })
3107            }));
3108        }
3109
3110        let mut project_transaction = ProjectTransaction::default();
3111        for operation in operations {
3112            match operation {
3113                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3114                    let abs_path = op
3115                        .uri
3116                        .to_file_path()
3117                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3118
3119                    if let Some(parent_path) = abs_path.parent() {
3120                        fs.create_dir(parent_path).await?;
3121                    }
3122                    if abs_path.ends_with("/") {
3123                        fs.create_dir(&abs_path).await?;
3124                    } else {
3125                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3126                            .await?;
3127                    }
3128                }
3129                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3130                    let source_abs_path = op
3131                        .old_uri
3132                        .to_file_path()
3133                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3134                    let target_abs_path = op
3135                        .new_uri
3136                        .to_file_path()
3137                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3138                    fs.rename(
3139                        &source_abs_path,
3140                        &target_abs_path,
3141                        op.options.map(Into::into).unwrap_or_default(),
3142                    )
3143                    .await?;
3144                }
3145                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3146                    let abs_path = op
3147                        .uri
3148                        .to_file_path()
3149                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3150                    let options = op.options.map(Into::into).unwrap_or_default();
3151                    if abs_path.ends_with("/") {
3152                        fs.remove_dir(&abs_path, options).await?;
3153                    } else {
3154                        fs.remove_file(&abs_path, options).await?;
3155                    }
3156                }
3157                lsp::DocumentChangeOperation::Edit(op) => {
3158                    let buffer_to_edit = this
3159                        .update(cx, |this, cx| {
3160                            this.open_local_buffer_via_lsp(
3161                                op.text_document.uri,
3162                                lsp_adapter.clone(),
3163                                language_server.clone(),
3164                                cx,
3165                            )
3166                        })
3167                        .await?;
3168
3169                    let edits = this
3170                        .update(cx, |this, cx| {
3171                            let edits = op.edits.into_iter().map(|edit| match edit {
3172                                lsp::OneOf::Left(edit) => edit,
3173                                lsp::OneOf::Right(edit) => edit.text_edit,
3174                            });
3175                            this.edits_from_lsp(
3176                                &buffer_to_edit,
3177                                edits,
3178                                op.text_document.version,
3179                                cx,
3180                            )
3181                        })
3182                        .await?;
3183
3184                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3185                        buffer.finalize_last_transaction();
3186                        buffer.start_transaction();
3187                        for (range, text) in edits {
3188                            buffer.edit([(range, text)], cx);
3189                        }
3190                        let transaction = if buffer.end_transaction(cx).is_some() {
3191                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3192                            if !push_to_history {
3193                                buffer.forget_transaction(transaction.id);
3194                            }
3195                            Some(transaction)
3196                        } else {
3197                            None
3198                        };
3199
3200                        transaction
3201                    });
3202                    if let Some(transaction) = transaction {
3203                        project_transaction.0.insert(buffer_to_edit, transaction);
3204                    }
3205                }
3206            }
3207        }
3208
3209        Ok(project_transaction)
3210    }
3211
3212    pub fn prepare_rename<T: ToPointUtf16>(
3213        &self,
3214        buffer: ModelHandle<Buffer>,
3215        position: T,
3216        cx: &mut ModelContext<Self>,
3217    ) -> Task<Result<Option<Range<Anchor>>>> {
3218        let position = position.to_point_utf16(buffer.read(cx));
3219        self.request_lsp(buffer, PrepareRename { position }, cx)
3220    }
3221
3222    pub fn perform_rename<T: ToPointUtf16>(
3223        &self,
3224        buffer: ModelHandle<Buffer>,
3225        position: T,
3226        new_name: String,
3227        push_to_history: bool,
3228        cx: &mut ModelContext<Self>,
3229    ) -> Task<Result<ProjectTransaction>> {
3230        let position = position.to_point_utf16(buffer.read(cx));
3231        self.request_lsp(
3232            buffer,
3233            PerformRename {
3234                position,
3235                new_name,
3236                push_to_history,
3237            },
3238            cx,
3239        )
3240    }
3241
3242    pub fn search(
3243        &self,
3244        query: SearchQuery,
3245        cx: &mut ModelContext<Self>,
3246    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3247        if self.is_local() {
3248            let snapshots = self
3249                .visible_worktrees(cx)
3250                .filter_map(|tree| {
3251                    let tree = tree.read(cx).as_local()?;
3252                    Some(tree.snapshot())
3253                })
3254                .collect::<Vec<_>>();
3255
3256            let background = cx.background().clone();
3257            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3258            if path_count == 0 {
3259                return Task::ready(Ok(Default::default()));
3260            }
3261            let workers = background.num_cpus().min(path_count);
3262            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3263            cx.background()
3264                .spawn({
3265                    let fs = self.fs.clone();
3266                    let background = cx.background().clone();
3267                    let query = query.clone();
3268                    async move {
3269                        let fs = &fs;
3270                        let query = &query;
3271                        let matching_paths_tx = &matching_paths_tx;
3272                        let paths_per_worker = (path_count + workers - 1) / workers;
3273                        let snapshots = &snapshots;
3274                        background
3275                            .scoped(|scope| {
3276                                for worker_ix in 0..workers {
3277                                    let worker_start_ix = worker_ix * paths_per_worker;
3278                                    let worker_end_ix = worker_start_ix + paths_per_worker;
3279                                    scope.spawn(async move {
3280                                        let mut snapshot_start_ix = 0;
3281                                        let mut abs_path = PathBuf::new();
3282                                        for snapshot in snapshots {
3283                                            let snapshot_end_ix =
3284                                                snapshot_start_ix + snapshot.visible_file_count();
3285                                            if worker_end_ix <= snapshot_start_ix {
3286                                                break;
3287                                            } else if worker_start_ix > snapshot_end_ix {
3288                                                snapshot_start_ix = snapshot_end_ix;
3289                                                continue;
3290                                            } else {
3291                                                let start_in_snapshot = worker_start_ix
3292                                                    .saturating_sub(snapshot_start_ix);
3293                                                let end_in_snapshot =
3294                                                    cmp::min(worker_end_ix, snapshot_end_ix)
3295                                                        - snapshot_start_ix;
3296
3297                                                for entry in snapshot
3298                                                    .files(false, start_in_snapshot)
3299                                                    .take(end_in_snapshot - start_in_snapshot)
3300                                                {
3301                                                    if matching_paths_tx.is_closed() {
3302                                                        break;
3303                                                    }
3304
3305                                                    abs_path.clear();
3306                                                    abs_path.push(&snapshot.abs_path());
3307                                                    abs_path.push(&entry.path);
3308                                                    let matches = if let Some(file) =
3309                                                        fs.open_sync(&abs_path).await.log_err()
3310                                                    {
3311                                                        query.detect(file).unwrap_or(false)
3312                                                    } else {
3313                                                        false
3314                                                    };
3315
3316                                                    if matches {
3317                                                        let project_path =
3318                                                            (snapshot.id(), entry.path.clone());
3319                                                        if matching_paths_tx
3320                                                            .send(project_path)
3321                                                            .await
3322                                                            .is_err()
3323                                                        {
3324                                                            break;
3325                                                        }
3326                                                    }
3327                                                }
3328
3329                                                snapshot_start_ix = snapshot_end_ix;
3330                                            }
3331                                        }
3332                                    });
3333                                }
3334                            })
3335                            .await;
3336                    }
3337                })
3338                .detach();
3339
3340            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
3341            let open_buffers = self
3342                .opened_buffers
3343                .values()
3344                .filter_map(|b| b.upgrade(cx))
3345                .collect::<HashSet<_>>();
3346            cx.spawn(|this, cx| async move {
3347                for buffer in &open_buffers {
3348                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3349                    buffers_tx.send((buffer.clone(), snapshot)).await?;
3350                }
3351
3352                let open_buffers = Rc::new(RefCell::new(open_buffers));
3353                while let Some(project_path) = matching_paths_rx.next().await {
3354                    if buffers_tx.is_closed() {
3355                        break;
3356                    }
3357
3358                    let this = this.clone();
3359                    let open_buffers = open_buffers.clone();
3360                    let buffers_tx = buffers_tx.clone();
3361                    cx.spawn(|mut cx| async move {
3362                        if let Some(buffer) = this
3363                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
3364                            .await
3365                            .log_err()
3366                        {
3367                            if open_buffers.borrow_mut().insert(buffer.clone()) {
3368                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3369                                buffers_tx.send((buffer, snapshot)).await?;
3370                            }
3371                        }
3372
3373                        Ok::<_, anyhow::Error>(())
3374                    })
3375                    .detach();
3376                }
3377
3378                Ok::<_, anyhow::Error>(())
3379            })
3380            .detach_and_log_err(cx);
3381
3382            let background = cx.background().clone();
3383            cx.background().spawn(async move {
3384                let query = &query;
3385                let mut matched_buffers = Vec::new();
3386                for _ in 0..workers {
3387                    matched_buffers.push(HashMap::default());
3388                }
3389                background
3390                    .scoped(|scope| {
3391                        for worker_matched_buffers in matched_buffers.iter_mut() {
3392                            let mut buffers_rx = buffers_rx.clone();
3393                            scope.spawn(async move {
3394                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
3395                                    let buffer_matches = query
3396                                        .search(snapshot.as_rope())
3397                                        .await
3398                                        .iter()
3399                                        .map(|range| {
3400                                            snapshot.anchor_before(range.start)
3401                                                ..snapshot.anchor_after(range.end)
3402                                        })
3403                                        .collect::<Vec<_>>();
3404                                    if !buffer_matches.is_empty() {
3405                                        worker_matched_buffers
3406                                            .insert(buffer.clone(), buffer_matches);
3407                                    }
3408                                }
3409                            });
3410                        }
3411                    })
3412                    .await;
3413                Ok(matched_buffers.into_iter().flatten().collect())
3414            })
3415        } else if let Some(project_id) = self.remote_id() {
3416            let request = self.client.request(query.to_proto(project_id));
3417            cx.spawn(|this, mut cx| async move {
3418                let response = request.await?;
3419                let mut result = HashMap::default();
3420                for location in response.locations {
3421                    let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
3422                    let target_buffer = this
3423                        .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3424                        .await?;
3425                    let start = location
3426                        .start
3427                        .and_then(deserialize_anchor)
3428                        .ok_or_else(|| anyhow!("missing target start"))?;
3429                    let end = location
3430                        .end
3431                        .and_then(deserialize_anchor)
3432                        .ok_or_else(|| anyhow!("missing target end"))?;
3433                    result
3434                        .entry(target_buffer)
3435                        .or_insert(Vec::new())
3436                        .push(start..end)
3437                }
3438                Ok(result)
3439            })
3440        } else {
3441            Task::ready(Ok(Default::default()))
3442        }
3443    }
3444
3445    fn request_lsp<R: LspCommand>(
3446        &self,
3447        buffer_handle: ModelHandle<Buffer>,
3448        request: R,
3449        cx: &mut ModelContext<Self>,
3450    ) -> Task<Result<R::Response>>
3451    where
3452        <R::LspRequest as lsp::request::Request>::Result: Send,
3453    {
3454        let buffer = buffer_handle.read(cx);
3455        if self.is_local() {
3456            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
3457            if let Some((file, (_, language_server))) =
3458                file.zip(self.language_server_for_buffer(buffer, cx).cloned())
3459            {
3460                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
3461                return cx.spawn(|this, cx| async move {
3462                    if !request.check_capabilities(&language_server.capabilities()) {
3463                        return Ok(Default::default());
3464                    }
3465
3466                    let response = language_server
3467                        .request::<R::LspRequest>(lsp_params)
3468                        .await
3469                        .context("lsp request failed")?;
3470                    request
3471                        .response_from_lsp(response, this, buffer_handle, cx)
3472                        .await
3473                });
3474            }
3475        } else if let Some(project_id) = self.remote_id() {
3476            let rpc = self.client.clone();
3477            let message = request.to_proto(project_id, buffer);
3478            return cx.spawn(|this, cx| async move {
3479                let response = rpc.request(message).await?;
3480                request
3481                    .response_from_proto(response, this, buffer_handle, cx)
3482                    .await
3483            });
3484        }
3485        Task::ready(Ok(Default::default()))
3486    }
3487
3488    pub fn find_or_create_local_worktree(
3489        &mut self,
3490        abs_path: impl AsRef<Path>,
3491        visible: bool,
3492        cx: &mut ModelContext<Self>,
3493    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
3494        let abs_path = abs_path.as_ref();
3495        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
3496            Task::ready(Ok((tree.clone(), relative_path.into())))
3497        } else {
3498            let worktree = self.create_local_worktree(abs_path, visible, cx);
3499            cx.foreground()
3500                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
3501        }
3502    }
3503
3504    pub fn find_local_worktree(
3505        &self,
3506        abs_path: &Path,
3507        cx: &AppContext,
3508    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
3509        for tree in self.worktrees(cx) {
3510            if let Some(relative_path) = tree
3511                .read(cx)
3512                .as_local()
3513                .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
3514            {
3515                return Some((tree.clone(), relative_path.into()));
3516            }
3517        }
3518        None
3519    }
3520
3521    pub fn is_shared(&self) -> bool {
3522        match &self.client_state {
3523            ProjectClientState::Local { is_shared, .. } => *is_shared,
3524            ProjectClientState::Remote { .. } => false,
3525        }
3526    }
3527
3528    fn create_local_worktree(
3529        &mut self,
3530        abs_path: impl AsRef<Path>,
3531        visible: bool,
3532        cx: &mut ModelContext<Self>,
3533    ) -> Task<Result<ModelHandle<Worktree>>> {
3534        let fs = self.fs.clone();
3535        let client = self.client.clone();
3536        let next_entry_id = self.next_entry_id.clone();
3537        let path: Arc<Path> = abs_path.as_ref().into();
3538        let task = self
3539            .loading_local_worktrees
3540            .entry(path.clone())
3541            .or_insert_with(|| {
3542                cx.spawn(|project, mut cx| {
3543                    async move {
3544                        let worktree = Worktree::local(
3545                            client.clone(),
3546                            path.clone(),
3547                            visible,
3548                            fs,
3549                            next_entry_id,
3550                            &mut cx,
3551                        )
3552                        .await;
3553                        project.update(&mut cx, |project, _| {
3554                            project.loading_local_worktrees.remove(&path);
3555                        });
3556                        let worktree = worktree?;
3557
3558                        let remote_project_id = project.update(&mut cx, |project, cx| {
3559                            project.add_worktree(&worktree, cx);
3560                            project.remote_id()
3561                        });
3562
3563                        if let Some(project_id) = remote_project_id {
3564                            // Because sharing is async, we may have *unshared* the project by the time it completes,
3565                            // in which case we need to register the worktree instead.
3566                            loop {
3567                                if project.read_with(&cx, |project, _| project.is_shared()) {
3568                                    if worktree
3569                                        .update(&mut cx, |worktree, cx| {
3570                                            worktree.as_local_mut().unwrap().share(project_id, cx)
3571                                        })
3572                                        .await
3573                                        .is_ok()
3574                                    {
3575                                        break;
3576                                    }
3577                                } else {
3578                                    worktree
3579                                        .update(&mut cx, |worktree, cx| {
3580                                            worktree
3581                                                .as_local_mut()
3582                                                .unwrap()
3583                                                .register(project_id, cx)
3584                                        })
3585                                        .await?;
3586                                    break;
3587                                }
3588                            }
3589                        }
3590
3591                        Ok(worktree)
3592                    }
3593                    .map_err(|err| Arc::new(err))
3594                })
3595                .shared()
3596            })
3597            .clone();
3598        cx.foreground().spawn(async move {
3599            match task.await {
3600                Ok(worktree) => Ok(worktree),
3601                Err(err) => Err(anyhow!("{}", err)),
3602            }
3603        })
3604    }
3605
3606    pub fn remove_worktree(&mut self, id: WorktreeId, cx: &mut ModelContext<Self>) {
3607        self.worktrees.retain(|worktree| {
3608            worktree
3609                .upgrade(cx)
3610                .map_or(false, |w| w.read(cx).id() != id)
3611        });
3612        cx.notify();
3613    }
3614
3615    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
3616        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
3617        if worktree.read(cx).is_local() {
3618            cx.subscribe(&worktree, |this, worktree, _, cx| {
3619                this.update_local_worktree_buffers(worktree, cx);
3620            })
3621            .detach();
3622        }
3623
3624        let push_strong_handle = {
3625            let worktree = worktree.read(cx);
3626            self.is_shared() || worktree.is_visible() || worktree.is_remote()
3627        };
3628        if push_strong_handle {
3629            self.worktrees
3630                .push(WorktreeHandle::Strong(worktree.clone()));
3631        } else {
3632            cx.observe_release(&worktree, |this, _, cx| {
3633                this.worktrees
3634                    .retain(|worktree| worktree.upgrade(cx).is_some());
3635                cx.notify();
3636            })
3637            .detach();
3638            self.worktrees
3639                .push(WorktreeHandle::Weak(worktree.downgrade()));
3640        }
3641        cx.emit(Event::WorktreeAdded);
3642        cx.notify();
3643    }
3644
3645    fn update_local_worktree_buffers(
3646        &mut self,
3647        worktree_handle: ModelHandle<Worktree>,
3648        cx: &mut ModelContext<Self>,
3649    ) {
3650        let snapshot = worktree_handle.read(cx).snapshot();
3651        let mut buffers_to_delete = Vec::new();
3652        let mut renamed_buffers = Vec::new();
3653        for (buffer_id, buffer) in &self.opened_buffers {
3654            if let Some(buffer) = buffer.upgrade(cx) {
3655                buffer.update(cx, |buffer, cx| {
3656                    if let Some(old_file) = File::from_dyn(buffer.file()) {
3657                        if old_file.worktree != worktree_handle {
3658                            return;
3659                        }
3660
3661                        let new_file = if let Some(entry) = old_file
3662                            .entry_id
3663                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
3664                        {
3665                            File {
3666                                is_local: true,
3667                                entry_id: Some(entry.id),
3668                                mtime: entry.mtime,
3669                                path: entry.path.clone(),
3670                                worktree: worktree_handle.clone(),
3671                            }
3672                        } else if let Some(entry) =
3673                            snapshot.entry_for_path(old_file.path().as_ref())
3674                        {
3675                            File {
3676                                is_local: true,
3677                                entry_id: Some(entry.id),
3678                                mtime: entry.mtime,
3679                                path: entry.path.clone(),
3680                                worktree: worktree_handle.clone(),
3681                            }
3682                        } else {
3683                            File {
3684                                is_local: true,
3685                                entry_id: None,
3686                                path: old_file.path().clone(),
3687                                mtime: old_file.mtime(),
3688                                worktree: worktree_handle.clone(),
3689                            }
3690                        };
3691
3692                        let old_path = old_file.abs_path(cx);
3693                        if new_file.abs_path(cx) != old_path {
3694                            renamed_buffers.push((cx.handle(), old_path));
3695                        }
3696
3697                        if let Some(project_id) = self.remote_id() {
3698                            self.client
3699                                .send(proto::UpdateBufferFile {
3700                                    project_id,
3701                                    buffer_id: *buffer_id as u64,
3702                                    file: Some(new_file.to_proto()),
3703                                })
3704                                .log_err();
3705                        }
3706                        buffer.file_updated(Box::new(new_file), cx).detach();
3707                    }
3708                });
3709            } else {
3710                buffers_to_delete.push(*buffer_id);
3711            }
3712        }
3713
3714        for buffer_id in buffers_to_delete {
3715            self.opened_buffers.remove(&buffer_id);
3716        }
3717
3718        for (buffer, old_path) in renamed_buffers {
3719            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
3720            self.assign_language_to_buffer(&buffer, cx);
3721            self.register_buffer_with_language_server(&buffer, cx);
3722        }
3723    }
3724
3725    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
3726        let new_active_entry = entry.and_then(|project_path| {
3727            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3728            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3729            Some(entry.id)
3730        });
3731        if new_active_entry != self.active_entry {
3732            self.active_entry = new_active_entry;
3733            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3734        }
3735    }
3736
3737    pub fn is_running_disk_based_diagnostics(&self) -> bool {
3738        self.language_server_statuses
3739            .values()
3740            .any(|status| status.pending_diagnostic_updates > 0)
3741    }
3742
3743    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
3744        let mut summary = DiagnosticSummary::default();
3745        for (_, path_summary) in self.diagnostic_summaries(cx) {
3746            summary.error_count += path_summary.error_count;
3747            summary.warning_count += path_summary.warning_count;
3748        }
3749        summary
3750    }
3751
3752    pub fn diagnostic_summaries<'a>(
3753        &'a self,
3754        cx: &'a AppContext,
3755    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
3756        self.worktrees(cx).flat_map(move |worktree| {
3757            let worktree = worktree.read(cx);
3758            let worktree_id = worktree.id();
3759            worktree
3760                .diagnostic_summaries()
3761                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
3762        })
3763    }
3764
3765    pub fn disk_based_diagnostics_started(&mut self, cx: &mut ModelContext<Self>) {
3766        if self
3767            .language_server_statuses
3768            .values()
3769            .map(|status| status.pending_diagnostic_updates)
3770            .sum::<isize>()
3771            == 1
3772        {
3773            cx.emit(Event::DiskBasedDiagnosticsStarted);
3774        }
3775    }
3776
3777    pub fn disk_based_diagnostics_finished(&mut self, cx: &mut ModelContext<Self>) {
3778        cx.emit(Event::DiskBasedDiagnosticsUpdated);
3779        if self
3780            .language_server_statuses
3781            .values()
3782            .map(|status| status.pending_diagnostic_updates)
3783            .sum::<isize>()
3784            == 0
3785        {
3786            cx.emit(Event::DiskBasedDiagnosticsFinished);
3787        }
3788    }
3789
3790    pub fn active_entry(&self) -> Option<ProjectEntryId> {
3791        self.active_entry
3792    }
3793
3794    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
3795        self.worktree_for_id(path.worktree_id, cx)?
3796            .read(cx)
3797            .entry_for_path(&path.path)
3798            .map(|entry| entry.id)
3799    }
3800
3801    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
3802        let worktree = self.worktree_for_entry(entry_id, cx)?;
3803        let worktree = worktree.read(cx);
3804        let worktree_id = worktree.id();
3805        let path = worktree.entry_for_id(entry_id)?.path.clone();
3806        Some(ProjectPath { worktree_id, path })
3807    }
3808
3809    // RPC message handlers
3810
3811    async fn handle_request_join_project(
3812        this: ModelHandle<Self>,
3813        message: TypedEnvelope<proto::RequestJoinProject>,
3814        _: Arc<Client>,
3815        mut cx: AsyncAppContext,
3816    ) -> Result<()> {
3817        let user_id = message.payload.requester_id;
3818        if this.read_with(&cx, |project, _| {
3819            project.collaborators.values().any(|c| c.user.id == user_id)
3820        }) {
3821            this.update(&mut cx, |this, cx| {
3822                this.respond_to_join_request(user_id, true, cx)
3823            });
3824        } else {
3825            let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
3826            let user = user_store
3827                .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
3828                .await?;
3829            this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
3830        }
3831        Ok(())
3832    }
3833
3834    async fn handle_unregister_project(
3835        this: ModelHandle<Self>,
3836        _: TypedEnvelope<proto::UnregisterProject>,
3837        _: Arc<Client>,
3838        mut cx: AsyncAppContext,
3839    ) -> Result<()> {
3840        this.update(&mut cx, |this, cx| this.removed_from_project(cx));
3841        Ok(())
3842    }
3843
3844    async fn handle_project_unshared(
3845        this: ModelHandle<Self>,
3846        _: TypedEnvelope<proto::ProjectUnshared>,
3847        _: Arc<Client>,
3848        mut cx: AsyncAppContext,
3849    ) -> Result<()> {
3850        this.update(&mut cx, |this, cx| this.unshared(cx));
3851        Ok(())
3852    }
3853
3854    async fn handle_add_collaborator(
3855        this: ModelHandle<Self>,
3856        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
3857        _: Arc<Client>,
3858        mut cx: AsyncAppContext,
3859    ) -> Result<()> {
3860        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
3861        let collaborator = envelope
3862            .payload
3863            .collaborator
3864            .take()
3865            .ok_or_else(|| anyhow!("empty collaborator"))?;
3866
3867        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
3868        this.update(&mut cx, |this, cx| {
3869            this.collaborators
3870                .insert(collaborator.peer_id, collaborator);
3871            cx.notify();
3872        });
3873
3874        Ok(())
3875    }
3876
3877    async fn handle_remove_collaborator(
3878        this: ModelHandle<Self>,
3879        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
3880        _: Arc<Client>,
3881        mut cx: AsyncAppContext,
3882    ) -> Result<()> {
3883        this.update(&mut cx, |this, cx| {
3884            let peer_id = PeerId(envelope.payload.peer_id);
3885            let replica_id = this
3886                .collaborators
3887                .remove(&peer_id)
3888                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
3889                .replica_id;
3890            for (_, buffer) in &this.opened_buffers {
3891                if let Some(buffer) = buffer.upgrade(cx) {
3892                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
3893                }
3894            }
3895
3896            cx.emit(Event::CollaboratorLeft(peer_id));
3897            cx.notify();
3898            Ok(())
3899        })
3900    }
3901
3902    async fn handle_join_project_request_cancelled(
3903        this: ModelHandle<Self>,
3904        envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
3905        _: Arc<Client>,
3906        mut cx: AsyncAppContext,
3907    ) -> Result<()> {
3908        let user = this
3909            .update(&mut cx, |this, cx| {
3910                this.user_store.update(cx, |user_store, cx| {
3911                    user_store.fetch_user(envelope.payload.requester_id, cx)
3912                })
3913            })
3914            .await?;
3915
3916        this.update(&mut cx, |_, cx| {
3917            cx.emit(Event::ContactCancelledJoinRequest(user));
3918        });
3919
3920        Ok(())
3921    }
3922
3923    async fn handle_register_worktree(
3924        this: ModelHandle<Self>,
3925        envelope: TypedEnvelope<proto::RegisterWorktree>,
3926        client: Arc<Client>,
3927        mut cx: AsyncAppContext,
3928    ) -> Result<()> {
3929        this.update(&mut cx, |this, cx| {
3930            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
3931            let replica_id = this.replica_id();
3932            let worktree = proto::Worktree {
3933                id: envelope.payload.worktree_id,
3934                root_name: envelope.payload.root_name,
3935                entries: Default::default(),
3936                diagnostic_summaries: Default::default(),
3937                visible: envelope.payload.visible,
3938                scan_id: 0,
3939            };
3940            let (worktree, load_task) =
3941                Worktree::remote(remote_id, replica_id, worktree, client, cx);
3942            this.add_worktree(&worktree, cx);
3943            load_task.detach();
3944            Ok(())
3945        })
3946    }
3947
3948    async fn handle_unregister_worktree(
3949        this: ModelHandle<Self>,
3950        envelope: TypedEnvelope<proto::UnregisterWorktree>,
3951        _: Arc<Client>,
3952        mut cx: AsyncAppContext,
3953    ) -> Result<()> {
3954        this.update(&mut cx, |this, cx| {
3955            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3956            this.remove_worktree(worktree_id, cx);
3957            Ok(())
3958        })
3959    }
3960
3961    async fn handle_update_worktree(
3962        this: ModelHandle<Self>,
3963        envelope: TypedEnvelope<proto::UpdateWorktree>,
3964        _: Arc<Client>,
3965        mut cx: AsyncAppContext,
3966    ) -> Result<()> {
3967        this.update(&mut cx, |this, cx| {
3968            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3969            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
3970                worktree.update(cx, |worktree, _| {
3971                    let worktree = worktree.as_remote_mut().unwrap();
3972                    worktree.update_from_remote(envelope)
3973                })?;
3974            }
3975            Ok(())
3976        })
3977    }
3978
3979    async fn handle_create_project_entry(
3980        this: ModelHandle<Self>,
3981        envelope: TypedEnvelope<proto::CreateProjectEntry>,
3982        _: Arc<Client>,
3983        mut cx: AsyncAppContext,
3984    ) -> Result<proto::ProjectEntryResponse> {
3985        let worktree = this.update(&mut cx, |this, cx| {
3986            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
3987            this.worktree_for_id(worktree_id, cx)
3988                .ok_or_else(|| anyhow!("worktree not found"))
3989        })?;
3990        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
3991        let entry = worktree
3992            .update(&mut cx, |worktree, cx| {
3993                let worktree = worktree.as_local_mut().unwrap();
3994                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
3995                worktree.create_entry(path, envelope.payload.is_directory, cx)
3996            })
3997            .await?;
3998        Ok(proto::ProjectEntryResponse {
3999            entry: Some((&entry).into()),
4000            worktree_scan_id: worktree_scan_id as u64,
4001        })
4002    }
4003
4004    async fn handle_rename_project_entry(
4005        this: ModelHandle<Self>,
4006        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4007        _: Arc<Client>,
4008        mut cx: AsyncAppContext,
4009    ) -> Result<proto::ProjectEntryResponse> {
4010        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4011        let worktree = this.read_with(&cx, |this, cx| {
4012            this.worktree_for_entry(entry_id, cx)
4013                .ok_or_else(|| anyhow!("worktree not found"))
4014        })?;
4015        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4016        let entry = worktree
4017            .update(&mut cx, |worktree, cx| {
4018                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4019                worktree
4020                    .as_local_mut()
4021                    .unwrap()
4022                    .rename_entry(entry_id, new_path, cx)
4023                    .ok_or_else(|| anyhow!("invalid entry"))
4024            })?
4025            .await?;
4026        Ok(proto::ProjectEntryResponse {
4027            entry: Some((&entry).into()),
4028            worktree_scan_id: worktree_scan_id as u64,
4029        })
4030    }
4031
4032    async fn handle_delete_project_entry(
4033        this: ModelHandle<Self>,
4034        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4035        _: Arc<Client>,
4036        mut cx: AsyncAppContext,
4037    ) -> Result<proto::ProjectEntryResponse> {
4038        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4039        let worktree = this.read_with(&cx, |this, cx| {
4040            this.worktree_for_entry(entry_id, cx)
4041                .ok_or_else(|| anyhow!("worktree not found"))
4042        })?;
4043        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4044        worktree
4045            .update(&mut cx, |worktree, cx| {
4046                worktree
4047                    .as_local_mut()
4048                    .unwrap()
4049                    .delete_entry(entry_id, cx)
4050                    .ok_or_else(|| anyhow!("invalid entry"))
4051            })?
4052            .await?;
4053        Ok(proto::ProjectEntryResponse {
4054            entry: None,
4055            worktree_scan_id: worktree_scan_id as u64,
4056        })
4057    }
4058
4059    async fn handle_update_diagnostic_summary(
4060        this: ModelHandle<Self>,
4061        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4062        _: Arc<Client>,
4063        mut cx: AsyncAppContext,
4064    ) -> Result<()> {
4065        this.update(&mut cx, |this, cx| {
4066            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4067            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4068                if let Some(summary) = envelope.payload.summary {
4069                    let project_path = ProjectPath {
4070                        worktree_id,
4071                        path: Path::new(&summary.path).into(),
4072                    };
4073                    worktree.update(cx, |worktree, _| {
4074                        worktree
4075                            .as_remote_mut()
4076                            .unwrap()
4077                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4078                    });
4079                    cx.emit(Event::DiagnosticsUpdated(project_path));
4080                }
4081            }
4082            Ok(())
4083        })
4084    }
4085
4086    async fn handle_start_language_server(
4087        this: ModelHandle<Self>,
4088        envelope: TypedEnvelope<proto::StartLanguageServer>,
4089        _: Arc<Client>,
4090        mut cx: AsyncAppContext,
4091    ) -> Result<()> {
4092        let server = envelope
4093            .payload
4094            .server
4095            .ok_or_else(|| anyhow!("invalid server"))?;
4096        this.update(&mut cx, |this, cx| {
4097            this.language_server_statuses.insert(
4098                server.id as usize,
4099                LanguageServerStatus {
4100                    name: server.name,
4101                    pending_work: Default::default(),
4102                    pending_diagnostic_updates: 0,
4103                },
4104            );
4105            cx.notify();
4106        });
4107        Ok(())
4108    }
4109
4110    async fn handle_update_language_server(
4111        this: ModelHandle<Self>,
4112        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4113        _: Arc<Client>,
4114        mut cx: AsyncAppContext,
4115    ) -> Result<()> {
4116        let language_server_id = envelope.payload.language_server_id as usize;
4117        match envelope
4118            .payload
4119            .variant
4120            .ok_or_else(|| anyhow!("invalid variant"))?
4121        {
4122            proto::update_language_server::Variant::WorkStart(payload) => {
4123                this.update(&mut cx, |this, cx| {
4124                    this.on_lsp_work_start(language_server_id, payload.token, cx);
4125                })
4126            }
4127            proto::update_language_server::Variant::WorkProgress(payload) => {
4128                this.update(&mut cx, |this, cx| {
4129                    this.on_lsp_work_progress(
4130                        language_server_id,
4131                        payload.token,
4132                        LanguageServerProgress {
4133                            message: payload.message,
4134                            percentage: payload.percentage.map(|p| p as usize),
4135                            last_update_at: Instant::now(),
4136                        },
4137                        cx,
4138                    );
4139                })
4140            }
4141            proto::update_language_server::Variant::WorkEnd(payload) => {
4142                this.update(&mut cx, |this, cx| {
4143                    this.on_lsp_work_end(language_server_id, payload.token, cx);
4144                })
4145            }
4146            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4147                this.update(&mut cx, |this, cx| {
4148                    this.disk_based_diagnostics_started(cx);
4149                })
4150            }
4151            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4152                this.update(&mut cx, |this, cx| this.disk_based_diagnostics_finished(cx));
4153            }
4154        }
4155
4156        Ok(())
4157    }
4158
4159    async fn handle_update_buffer(
4160        this: ModelHandle<Self>,
4161        envelope: TypedEnvelope<proto::UpdateBuffer>,
4162        _: Arc<Client>,
4163        mut cx: AsyncAppContext,
4164    ) -> Result<()> {
4165        this.update(&mut cx, |this, cx| {
4166            let payload = envelope.payload.clone();
4167            let buffer_id = payload.buffer_id;
4168            let ops = payload
4169                .operations
4170                .into_iter()
4171                .map(|op| language::proto::deserialize_operation(op))
4172                .collect::<Result<Vec<_>, _>>()?;
4173            let is_remote = this.is_remote();
4174            match this.opened_buffers.entry(buffer_id) {
4175                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
4176                    OpenBuffer::Strong(buffer) => {
4177                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
4178                    }
4179                    OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
4180                    OpenBuffer::Weak(_) => {}
4181                },
4182                hash_map::Entry::Vacant(e) => {
4183                    assert!(
4184                        is_remote,
4185                        "received buffer update from {:?}",
4186                        envelope.original_sender_id
4187                    );
4188                    e.insert(OpenBuffer::Loading(ops));
4189                }
4190            }
4191            Ok(())
4192        })
4193    }
4194
4195    async fn handle_update_buffer_file(
4196        this: ModelHandle<Self>,
4197        envelope: TypedEnvelope<proto::UpdateBufferFile>,
4198        _: Arc<Client>,
4199        mut cx: AsyncAppContext,
4200    ) -> Result<()> {
4201        this.update(&mut cx, |this, cx| {
4202            let payload = envelope.payload.clone();
4203            let buffer_id = payload.buffer_id;
4204            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
4205            let worktree = this
4206                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
4207                .ok_or_else(|| anyhow!("no such worktree"))?;
4208            let file = File::from_proto(file, worktree.clone(), cx)?;
4209            let buffer = this
4210                .opened_buffers
4211                .get_mut(&buffer_id)
4212                .and_then(|b| b.upgrade(cx))
4213                .ok_or_else(|| anyhow!("no such buffer"))?;
4214            buffer.update(cx, |buffer, cx| {
4215                buffer.file_updated(Box::new(file), cx).detach();
4216            });
4217            Ok(())
4218        })
4219    }
4220
4221    async fn handle_save_buffer(
4222        this: ModelHandle<Self>,
4223        envelope: TypedEnvelope<proto::SaveBuffer>,
4224        _: Arc<Client>,
4225        mut cx: AsyncAppContext,
4226    ) -> Result<proto::BufferSaved> {
4227        let buffer_id = envelope.payload.buffer_id;
4228        let requested_version = deserialize_version(envelope.payload.version);
4229
4230        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
4231            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
4232            let buffer = this
4233                .opened_buffers
4234                .get(&buffer_id)
4235                .and_then(|buffer| buffer.upgrade(cx))
4236                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
4237            Ok::<_, anyhow::Error>((project_id, buffer))
4238        })?;
4239        buffer
4240            .update(&mut cx, |buffer, _| {
4241                buffer.wait_for_version(requested_version)
4242            })
4243            .await;
4244
4245        let (saved_version, mtime) = buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
4246        Ok(proto::BufferSaved {
4247            project_id,
4248            buffer_id,
4249            version: serialize_version(&saved_version),
4250            mtime: Some(mtime.into()),
4251        })
4252    }
4253
4254    async fn handle_reload_buffers(
4255        this: ModelHandle<Self>,
4256        envelope: TypedEnvelope<proto::ReloadBuffers>,
4257        _: Arc<Client>,
4258        mut cx: AsyncAppContext,
4259    ) -> Result<proto::ReloadBuffersResponse> {
4260        let sender_id = envelope.original_sender_id()?;
4261        let reload = this.update(&mut cx, |this, cx| {
4262            let mut buffers = HashSet::default();
4263            for buffer_id in &envelope.payload.buffer_ids {
4264                buffers.insert(
4265                    this.opened_buffers
4266                        .get(buffer_id)
4267                        .and_then(|buffer| buffer.upgrade(cx))
4268                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
4269                );
4270            }
4271            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
4272        })?;
4273
4274        let project_transaction = reload.await?;
4275        let project_transaction = this.update(&mut cx, |this, cx| {
4276            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4277        });
4278        Ok(proto::ReloadBuffersResponse {
4279            transaction: Some(project_transaction),
4280        })
4281    }
4282
4283    async fn handle_format_buffers(
4284        this: ModelHandle<Self>,
4285        envelope: TypedEnvelope<proto::FormatBuffers>,
4286        _: Arc<Client>,
4287        mut cx: AsyncAppContext,
4288    ) -> Result<proto::FormatBuffersResponse> {
4289        let sender_id = envelope.original_sender_id()?;
4290        let format = this.update(&mut cx, |this, cx| {
4291            let mut buffers = HashSet::default();
4292            for buffer_id in &envelope.payload.buffer_ids {
4293                buffers.insert(
4294                    this.opened_buffers
4295                        .get(buffer_id)
4296                        .and_then(|buffer| buffer.upgrade(cx))
4297                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
4298                );
4299            }
4300            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
4301        })?;
4302
4303        let project_transaction = format.await?;
4304        let project_transaction = this.update(&mut cx, |this, cx| {
4305            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4306        });
4307        Ok(proto::FormatBuffersResponse {
4308            transaction: Some(project_transaction),
4309        })
4310    }
4311
4312    async fn handle_get_completions(
4313        this: ModelHandle<Self>,
4314        envelope: TypedEnvelope<proto::GetCompletions>,
4315        _: Arc<Client>,
4316        mut cx: AsyncAppContext,
4317    ) -> Result<proto::GetCompletionsResponse> {
4318        let position = envelope
4319            .payload
4320            .position
4321            .and_then(language::proto::deserialize_anchor)
4322            .ok_or_else(|| anyhow!("invalid position"))?;
4323        let version = deserialize_version(envelope.payload.version);
4324        let buffer = this.read_with(&cx, |this, cx| {
4325            this.opened_buffers
4326                .get(&envelope.payload.buffer_id)
4327                .and_then(|buffer| buffer.upgrade(cx))
4328                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
4329        })?;
4330        buffer
4331            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
4332            .await;
4333        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
4334        let completions = this
4335            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
4336            .await?;
4337
4338        Ok(proto::GetCompletionsResponse {
4339            completions: completions
4340                .iter()
4341                .map(language::proto::serialize_completion)
4342                .collect(),
4343            version: serialize_version(&version),
4344        })
4345    }
4346
4347    async fn handle_apply_additional_edits_for_completion(
4348        this: ModelHandle<Self>,
4349        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
4350        _: Arc<Client>,
4351        mut cx: AsyncAppContext,
4352    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
4353        let apply_additional_edits = this.update(&mut cx, |this, cx| {
4354            let buffer = this
4355                .opened_buffers
4356                .get(&envelope.payload.buffer_id)
4357                .and_then(|buffer| buffer.upgrade(cx))
4358                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
4359            let language = buffer.read(cx).language();
4360            let completion = language::proto::deserialize_completion(
4361                envelope
4362                    .payload
4363                    .completion
4364                    .ok_or_else(|| anyhow!("invalid completion"))?,
4365                language,
4366            )?;
4367            Ok::<_, anyhow::Error>(
4368                this.apply_additional_edits_for_completion(buffer, completion, false, cx),
4369            )
4370        })?;
4371
4372        Ok(proto::ApplyCompletionAdditionalEditsResponse {
4373            transaction: apply_additional_edits
4374                .await?
4375                .as_ref()
4376                .map(language::proto::serialize_transaction),
4377        })
4378    }
4379
4380    async fn handle_get_code_actions(
4381        this: ModelHandle<Self>,
4382        envelope: TypedEnvelope<proto::GetCodeActions>,
4383        _: Arc<Client>,
4384        mut cx: AsyncAppContext,
4385    ) -> Result<proto::GetCodeActionsResponse> {
4386        let start = envelope
4387            .payload
4388            .start
4389            .and_then(language::proto::deserialize_anchor)
4390            .ok_or_else(|| anyhow!("invalid start"))?;
4391        let end = envelope
4392            .payload
4393            .end
4394            .and_then(language::proto::deserialize_anchor)
4395            .ok_or_else(|| anyhow!("invalid end"))?;
4396        let buffer = this.update(&mut cx, |this, cx| {
4397            this.opened_buffers
4398                .get(&envelope.payload.buffer_id)
4399                .and_then(|buffer| buffer.upgrade(cx))
4400                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
4401        })?;
4402        buffer
4403            .update(&mut cx, |buffer, _| {
4404                buffer.wait_for_version(deserialize_version(envelope.payload.version))
4405            })
4406            .await;
4407
4408        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
4409        let code_actions = this.update(&mut cx, |this, cx| {
4410            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
4411        })?;
4412
4413        Ok(proto::GetCodeActionsResponse {
4414            actions: code_actions
4415                .await?
4416                .iter()
4417                .map(language::proto::serialize_code_action)
4418                .collect(),
4419            version: serialize_version(&version),
4420        })
4421    }
4422
4423    async fn handle_apply_code_action(
4424        this: ModelHandle<Self>,
4425        envelope: TypedEnvelope<proto::ApplyCodeAction>,
4426        _: Arc<Client>,
4427        mut cx: AsyncAppContext,
4428    ) -> Result<proto::ApplyCodeActionResponse> {
4429        let sender_id = envelope.original_sender_id()?;
4430        let action = language::proto::deserialize_code_action(
4431            envelope
4432                .payload
4433                .action
4434                .ok_or_else(|| anyhow!("invalid action"))?,
4435        )?;
4436        let apply_code_action = this.update(&mut cx, |this, cx| {
4437            let buffer = this
4438                .opened_buffers
4439                .get(&envelope.payload.buffer_id)
4440                .and_then(|buffer| buffer.upgrade(cx))
4441                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
4442            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
4443        })?;
4444
4445        let project_transaction = apply_code_action.await?;
4446        let project_transaction = this.update(&mut cx, |this, cx| {
4447            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
4448        });
4449        Ok(proto::ApplyCodeActionResponse {
4450            transaction: Some(project_transaction),
4451        })
4452    }
4453
4454    async fn handle_lsp_command<T: LspCommand>(
4455        this: ModelHandle<Self>,
4456        envelope: TypedEnvelope<T::ProtoRequest>,
4457        _: Arc<Client>,
4458        mut cx: AsyncAppContext,
4459    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
4460    where
4461        <T::LspRequest as lsp::request::Request>::Result: Send,
4462    {
4463        let sender_id = envelope.original_sender_id()?;
4464        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
4465        let buffer_handle = this.read_with(&cx, |this, _| {
4466            this.opened_buffers
4467                .get(&buffer_id)
4468                .and_then(|buffer| buffer.upgrade(&cx))
4469                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
4470        })?;
4471        let request = T::from_proto(
4472            envelope.payload,
4473            this.clone(),
4474            buffer_handle.clone(),
4475            cx.clone(),
4476        )
4477        .await?;
4478        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
4479        let response = this
4480            .update(&mut cx, |this, cx| {
4481                this.request_lsp(buffer_handle, request, cx)
4482            })
4483            .await?;
4484        this.update(&mut cx, |this, cx| {
4485            Ok(T::response_to_proto(
4486                response,
4487                this,
4488                sender_id,
4489                &buffer_version,
4490                cx,
4491            ))
4492        })
4493    }
4494
4495    async fn handle_get_project_symbols(
4496        this: ModelHandle<Self>,
4497        envelope: TypedEnvelope<proto::GetProjectSymbols>,
4498        _: Arc<Client>,
4499        mut cx: AsyncAppContext,
4500    ) -> Result<proto::GetProjectSymbolsResponse> {
4501        let symbols = this
4502            .update(&mut cx, |this, cx| {
4503                this.symbols(&envelope.payload.query, cx)
4504            })
4505            .await?;
4506
4507        Ok(proto::GetProjectSymbolsResponse {
4508            symbols: symbols.iter().map(serialize_symbol).collect(),
4509        })
4510    }
4511
4512    async fn handle_search_project(
4513        this: ModelHandle<Self>,
4514        envelope: TypedEnvelope<proto::SearchProject>,
4515        _: Arc<Client>,
4516        mut cx: AsyncAppContext,
4517    ) -> Result<proto::SearchProjectResponse> {
4518        let peer_id = envelope.original_sender_id()?;
4519        let query = SearchQuery::from_proto(envelope.payload)?;
4520        let result = this
4521            .update(&mut cx, |this, cx| this.search(query, cx))
4522            .await?;
4523
4524        this.update(&mut cx, |this, cx| {
4525            let mut locations = Vec::new();
4526            for (buffer, ranges) in result {
4527                for range in ranges {
4528                    let start = serialize_anchor(&range.start);
4529                    let end = serialize_anchor(&range.end);
4530                    let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
4531                    locations.push(proto::Location {
4532                        buffer: Some(buffer),
4533                        start: Some(start),
4534                        end: Some(end),
4535                    });
4536                }
4537            }
4538            Ok(proto::SearchProjectResponse { locations })
4539        })
4540    }
4541
4542    async fn handle_open_buffer_for_symbol(
4543        this: ModelHandle<Self>,
4544        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
4545        _: Arc<Client>,
4546        mut cx: AsyncAppContext,
4547    ) -> Result<proto::OpenBufferForSymbolResponse> {
4548        let peer_id = envelope.original_sender_id()?;
4549        let symbol = envelope
4550            .payload
4551            .symbol
4552            .ok_or_else(|| anyhow!("invalid symbol"))?;
4553        let symbol = this.read_with(&cx, |this, _| {
4554            let symbol = this.deserialize_symbol(symbol)?;
4555            let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
4556            if signature == symbol.signature {
4557                Ok(symbol)
4558            } else {
4559                Err(anyhow!("invalid symbol signature"))
4560            }
4561        })?;
4562        let buffer = this
4563            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
4564            .await?;
4565
4566        Ok(proto::OpenBufferForSymbolResponse {
4567            buffer: Some(this.update(&mut cx, |this, cx| {
4568                this.serialize_buffer_for_peer(&buffer, peer_id, cx)
4569            })),
4570        })
4571    }
4572
4573    fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
4574        let mut hasher = Sha256::new();
4575        hasher.update(worktree_id.to_proto().to_be_bytes());
4576        hasher.update(path.to_string_lossy().as_bytes());
4577        hasher.update(self.nonce.to_be_bytes());
4578        hasher.finalize().as_slice().try_into().unwrap()
4579    }
4580
4581    async fn handle_open_buffer_by_id(
4582        this: ModelHandle<Self>,
4583        envelope: TypedEnvelope<proto::OpenBufferById>,
4584        _: Arc<Client>,
4585        mut cx: AsyncAppContext,
4586    ) -> Result<proto::OpenBufferResponse> {
4587        let peer_id = envelope.original_sender_id()?;
4588        let buffer = this
4589            .update(&mut cx, |this, cx| {
4590                this.open_buffer_by_id(envelope.payload.id, cx)
4591            })
4592            .await?;
4593        this.update(&mut cx, |this, cx| {
4594            Ok(proto::OpenBufferResponse {
4595                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
4596            })
4597        })
4598    }
4599
4600    async fn handle_open_buffer_by_path(
4601        this: ModelHandle<Self>,
4602        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4603        _: Arc<Client>,
4604        mut cx: AsyncAppContext,
4605    ) -> Result<proto::OpenBufferResponse> {
4606        let peer_id = envelope.original_sender_id()?;
4607        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4608        let open_buffer = this.update(&mut cx, |this, cx| {
4609            this.open_buffer(
4610                ProjectPath {
4611                    worktree_id,
4612                    path: PathBuf::from(envelope.payload.path).into(),
4613                },
4614                cx,
4615            )
4616        });
4617
4618        let buffer = open_buffer.await?;
4619        this.update(&mut cx, |this, cx| {
4620            Ok(proto::OpenBufferResponse {
4621                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
4622            })
4623        })
4624    }
4625
4626    fn serialize_project_transaction_for_peer(
4627        &mut self,
4628        project_transaction: ProjectTransaction,
4629        peer_id: PeerId,
4630        cx: &AppContext,
4631    ) -> proto::ProjectTransaction {
4632        let mut serialized_transaction = proto::ProjectTransaction {
4633            buffers: Default::default(),
4634            transactions: Default::default(),
4635        };
4636        for (buffer, transaction) in project_transaction.0 {
4637            serialized_transaction
4638                .buffers
4639                .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
4640            serialized_transaction
4641                .transactions
4642                .push(language::proto::serialize_transaction(&transaction));
4643        }
4644        serialized_transaction
4645    }
4646
4647    fn deserialize_project_transaction(
4648        &mut self,
4649        message: proto::ProjectTransaction,
4650        push_to_history: bool,
4651        cx: &mut ModelContext<Self>,
4652    ) -> Task<Result<ProjectTransaction>> {
4653        cx.spawn(|this, mut cx| async move {
4654            let mut project_transaction = ProjectTransaction::default();
4655            for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
4656                let buffer = this
4657                    .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
4658                    .await?;
4659                let transaction = language::proto::deserialize_transaction(transaction)?;
4660                project_transaction.0.insert(buffer, transaction);
4661            }
4662
4663            for (buffer, transaction) in &project_transaction.0 {
4664                buffer
4665                    .update(&mut cx, |buffer, _| {
4666                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4667                    })
4668                    .await;
4669
4670                if push_to_history {
4671                    buffer.update(&mut cx, |buffer, _| {
4672                        buffer.push_transaction(transaction.clone(), Instant::now());
4673                    });
4674                }
4675            }
4676
4677            Ok(project_transaction)
4678        })
4679    }
4680
4681    fn serialize_buffer_for_peer(
4682        &mut self,
4683        buffer: &ModelHandle<Buffer>,
4684        peer_id: PeerId,
4685        cx: &AppContext,
4686    ) -> proto::Buffer {
4687        let buffer_id = buffer.read(cx).remote_id();
4688        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
4689        if shared_buffers.insert(buffer_id) {
4690            proto::Buffer {
4691                variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
4692            }
4693        } else {
4694            proto::Buffer {
4695                variant: Some(proto::buffer::Variant::Id(buffer_id)),
4696            }
4697        }
4698    }
4699
4700    fn deserialize_buffer(
4701        &mut self,
4702        buffer: proto::Buffer,
4703        cx: &mut ModelContext<Self>,
4704    ) -> Task<Result<ModelHandle<Buffer>>> {
4705        let replica_id = self.replica_id();
4706
4707        let opened_buffer_tx = self.opened_buffer.0.clone();
4708        let mut opened_buffer_rx = self.opened_buffer.1.clone();
4709        cx.spawn(|this, mut cx| async move {
4710            match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
4711                proto::buffer::Variant::Id(id) => {
4712                    let buffer = loop {
4713                        let buffer = this.read_with(&cx, |this, cx| {
4714                            this.opened_buffers
4715                                .get(&id)
4716                                .and_then(|buffer| buffer.upgrade(cx))
4717                        });
4718                        if let Some(buffer) = buffer {
4719                            break buffer;
4720                        }
4721                        opened_buffer_rx
4722                            .next()
4723                            .await
4724                            .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
4725                    };
4726                    Ok(buffer)
4727                }
4728                proto::buffer::Variant::State(mut buffer) => {
4729                    let mut buffer_worktree = None;
4730                    let mut buffer_file = None;
4731                    if let Some(file) = buffer.file.take() {
4732                        this.read_with(&cx, |this, cx| {
4733                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
4734                            let worktree =
4735                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
4736                                    anyhow!("no worktree found for id {}", file.worktree_id)
4737                                })?;
4738                            buffer_file =
4739                                Some(Box::new(File::from_proto(file, worktree.clone(), cx)?)
4740                                    as Box<dyn language::File>);
4741                            buffer_worktree = Some(worktree);
4742                            Ok::<_, anyhow::Error>(())
4743                        })?;
4744                    }
4745
4746                    let buffer = cx.add_model(|cx| {
4747                        Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
4748                    });
4749
4750                    this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
4751
4752                    *opened_buffer_tx.borrow_mut().borrow_mut() = ();
4753                    Ok(buffer)
4754                }
4755            }
4756        })
4757    }
4758
4759    fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
4760        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
4761        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
4762        let start = serialized_symbol
4763            .start
4764            .ok_or_else(|| anyhow!("invalid start"))?;
4765        let end = serialized_symbol
4766            .end
4767            .ok_or_else(|| anyhow!("invalid end"))?;
4768        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
4769        let path = PathBuf::from(serialized_symbol.path);
4770        let language = self.languages.select_language(&path);
4771        Ok(Symbol {
4772            source_worktree_id,
4773            worktree_id,
4774            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
4775            label: language
4776                .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
4777                .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
4778            name: serialized_symbol.name,
4779            path,
4780            range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
4781            kind,
4782            signature: serialized_symbol
4783                .signature
4784                .try_into()
4785                .map_err(|_| anyhow!("invalid signature"))?,
4786        })
4787    }
4788
4789    async fn handle_buffer_saved(
4790        this: ModelHandle<Self>,
4791        envelope: TypedEnvelope<proto::BufferSaved>,
4792        _: Arc<Client>,
4793        mut cx: AsyncAppContext,
4794    ) -> Result<()> {
4795        let version = deserialize_version(envelope.payload.version);
4796        let mtime = envelope
4797            .payload
4798            .mtime
4799            .ok_or_else(|| anyhow!("missing mtime"))?
4800            .into();
4801
4802        this.update(&mut cx, |this, cx| {
4803            let buffer = this
4804                .opened_buffers
4805                .get(&envelope.payload.buffer_id)
4806                .and_then(|buffer| buffer.upgrade(cx));
4807            if let Some(buffer) = buffer {
4808                buffer.update(cx, |buffer, cx| {
4809                    buffer.did_save(version, mtime, None, cx);
4810                });
4811            }
4812            Ok(())
4813        })
4814    }
4815
4816    async fn handle_buffer_reloaded(
4817        this: ModelHandle<Self>,
4818        envelope: TypedEnvelope<proto::BufferReloaded>,
4819        _: Arc<Client>,
4820        mut cx: AsyncAppContext,
4821    ) -> Result<()> {
4822        let payload = envelope.payload.clone();
4823        let version = deserialize_version(payload.version);
4824        let mtime = payload
4825            .mtime
4826            .ok_or_else(|| anyhow!("missing mtime"))?
4827            .into();
4828        this.update(&mut cx, |this, cx| {
4829            let buffer = this
4830                .opened_buffers
4831                .get(&payload.buffer_id)
4832                .and_then(|buffer| buffer.upgrade(cx));
4833            if let Some(buffer) = buffer {
4834                buffer.update(cx, |buffer, cx| {
4835                    buffer.did_reload(version, mtime, cx);
4836                });
4837            }
4838            Ok(())
4839        })
4840    }
4841
4842    pub fn match_paths<'a>(
4843        &self,
4844        query: &'a str,
4845        include_ignored: bool,
4846        smart_case: bool,
4847        max_results: usize,
4848        cancel_flag: &'a AtomicBool,
4849        cx: &AppContext,
4850    ) -> impl 'a + Future<Output = Vec<PathMatch>> {
4851        let worktrees = self
4852            .worktrees(cx)
4853            .filter(|worktree| worktree.read(cx).is_visible())
4854            .collect::<Vec<_>>();
4855        let include_root_name = worktrees.len() > 1;
4856        let candidate_sets = worktrees
4857            .into_iter()
4858            .map(|worktree| CandidateSet {
4859                snapshot: worktree.read(cx).snapshot(),
4860                include_ignored,
4861                include_root_name,
4862            })
4863            .collect::<Vec<_>>();
4864
4865        let background = cx.background().clone();
4866        async move {
4867            fuzzy::match_paths(
4868                candidate_sets.as_slice(),
4869                query,
4870                smart_case,
4871                max_results,
4872                cancel_flag,
4873                background,
4874            )
4875            .await
4876        }
4877    }
4878
4879    fn edits_from_lsp(
4880        &mut self,
4881        buffer: &ModelHandle<Buffer>,
4882        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
4883        version: Option<i32>,
4884        cx: &mut ModelContext<Self>,
4885    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
4886        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
4887        cx.background().spawn(async move {
4888            let snapshot = snapshot?;
4889            let mut lsp_edits = lsp_edits
4890                .into_iter()
4891                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
4892                .peekable();
4893
4894            let mut edits = Vec::new();
4895            while let Some((mut range, mut new_text)) = lsp_edits.next() {
4896                // Combine any LSP edits that are adjacent.
4897                //
4898                // Also, combine LSP edits that are separated from each other by only
4899                // a newline. This is important because for some code actions,
4900                // Rust-analyzer rewrites the entire buffer via a series of edits that
4901                // are separated by unchanged newline characters.
4902                //
4903                // In order for the diffing logic below to work properly, any edits that
4904                // cancel each other out must be combined into one.
4905                while let Some((next_range, next_text)) = lsp_edits.peek() {
4906                    if next_range.start > range.end {
4907                        if next_range.start.row > range.end.row + 1
4908                            || next_range.start.column > 0
4909                            || snapshot.clip_point_utf16(
4910                                PointUtf16::new(range.end.row, u32::MAX),
4911                                Bias::Left,
4912                            ) > range.end
4913                        {
4914                            break;
4915                        }
4916                        new_text.push('\n');
4917                    }
4918                    range.end = next_range.end;
4919                    new_text.push_str(&next_text);
4920                    lsp_edits.next();
4921                }
4922
4923                if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
4924                    || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
4925                {
4926                    return Err(anyhow!("invalid edits received from language server"));
4927                }
4928
4929                // For multiline edits, perform a diff of the old and new text so that
4930                // we can identify the changes more precisely, preserving the locations
4931                // of any anchors positioned in the unchanged regions.
4932                if range.end.row > range.start.row {
4933                    let mut offset = range.start.to_offset(&snapshot);
4934                    let old_text = snapshot.text_for_range(range).collect::<String>();
4935
4936                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
4937                    let mut moved_since_edit = true;
4938                    for change in diff.iter_all_changes() {
4939                        let tag = change.tag();
4940                        let value = change.value();
4941                        match tag {
4942                            ChangeTag::Equal => {
4943                                offset += value.len();
4944                                moved_since_edit = true;
4945                            }
4946                            ChangeTag::Delete => {
4947                                let start = snapshot.anchor_after(offset);
4948                                let end = snapshot.anchor_before(offset + value.len());
4949                                if moved_since_edit {
4950                                    edits.push((start..end, String::new()));
4951                                } else {
4952                                    edits.last_mut().unwrap().0.end = end;
4953                                }
4954                                offset += value.len();
4955                                moved_since_edit = false;
4956                            }
4957                            ChangeTag::Insert => {
4958                                if moved_since_edit {
4959                                    let anchor = snapshot.anchor_after(offset);
4960                                    edits.push((anchor.clone()..anchor, value.to_string()));
4961                                } else {
4962                                    edits.last_mut().unwrap().1.push_str(value);
4963                                }
4964                                moved_since_edit = false;
4965                            }
4966                        }
4967                    }
4968                } else if range.end == range.start {
4969                    let anchor = snapshot.anchor_after(range.start);
4970                    edits.push((anchor.clone()..anchor, new_text));
4971                } else {
4972                    let edit_start = snapshot.anchor_after(range.start);
4973                    let edit_end = snapshot.anchor_before(range.end);
4974                    edits.push((edit_start..edit_end, new_text));
4975                }
4976            }
4977
4978            Ok(edits)
4979        })
4980    }
4981
4982    fn buffer_snapshot_for_lsp_version(
4983        &mut self,
4984        buffer: &ModelHandle<Buffer>,
4985        version: Option<i32>,
4986        cx: &AppContext,
4987    ) -> Result<TextBufferSnapshot> {
4988        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
4989
4990        if let Some(version) = version {
4991            let buffer_id = buffer.read(cx).remote_id();
4992            let snapshots = self
4993                .buffer_snapshots
4994                .get_mut(&buffer_id)
4995                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
4996            let mut found_snapshot = None;
4997            snapshots.retain(|(snapshot_version, snapshot)| {
4998                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
4999                    false
5000                } else {
5001                    if *snapshot_version == version {
5002                        found_snapshot = Some(snapshot.clone());
5003                    }
5004                    true
5005                }
5006            });
5007
5008            found_snapshot.ok_or_else(|| {
5009                anyhow!(
5010                    "snapshot not found for buffer {} at version {}",
5011                    buffer_id,
5012                    version
5013                )
5014            })
5015        } else {
5016            Ok((buffer.read(cx)).text_snapshot())
5017        }
5018    }
5019
5020    fn language_server_for_buffer(
5021        &self,
5022        buffer: &Buffer,
5023        cx: &AppContext,
5024    ) -> Option<&(Arc<dyn LspAdapter>, Arc<LanguageServer>)> {
5025        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5026            let worktree_id = file.worktree_id(cx);
5027            self.language_servers
5028                .get(&(worktree_id, language.lsp_adapter()?.name()))
5029        } else {
5030            None
5031        }
5032    }
5033}
5034
5035impl WorktreeHandle {
5036    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5037        match self {
5038            WorktreeHandle::Strong(handle) => Some(handle.clone()),
5039            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5040        }
5041    }
5042}
5043
5044impl OpenBuffer {
5045    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5046        match self {
5047            OpenBuffer::Strong(handle) => Some(handle.clone()),
5048            OpenBuffer::Weak(handle) => handle.upgrade(cx),
5049            OpenBuffer::Loading(_) => None,
5050        }
5051    }
5052}
5053
5054struct CandidateSet {
5055    snapshot: Snapshot,
5056    include_ignored: bool,
5057    include_root_name: bool,
5058}
5059
5060impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
5061    type Candidates = CandidateSetIter<'a>;
5062
5063    fn id(&self) -> usize {
5064        self.snapshot.id().to_usize()
5065    }
5066
5067    fn len(&self) -> usize {
5068        if self.include_ignored {
5069            self.snapshot.file_count()
5070        } else {
5071            self.snapshot.visible_file_count()
5072        }
5073    }
5074
5075    fn prefix(&self) -> Arc<str> {
5076        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5077            self.snapshot.root_name().into()
5078        } else if self.include_root_name {
5079            format!("{}/", self.snapshot.root_name()).into()
5080        } else {
5081            "".into()
5082        }
5083    }
5084
5085    fn candidates(&'a self, start: usize) -> Self::Candidates {
5086        CandidateSetIter {
5087            traversal: self.snapshot.files(self.include_ignored, start),
5088        }
5089    }
5090}
5091
5092struct CandidateSetIter<'a> {
5093    traversal: Traversal<'a>,
5094}
5095
5096impl<'a> Iterator for CandidateSetIter<'a> {
5097    type Item = PathMatchCandidate<'a>;
5098
5099    fn next(&mut self) -> Option<Self::Item> {
5100        self.traversal.next().map(|entry| {
5101            if let EntryKind::File(char_bag) = entry.kind {
5102                PathMatchCandidate {
5103                    path: &entry.path,
5104                    char_bag,
5105                }
5106            } else {
5107                unreachable!()
5108            }
5109        })
5110    }
5111}
5112
5113impl Entity for Project {
5114    type Event = Event;
5115
5116    fn release(&mut self, _: &mut gpui::MutableAppContext) {
5117        match &self.client_state {
5118            ProjectClientState::Local { remote_id_rx, .. } => {
5119                if let Some(project_id) = *remote_id_rx.borrow() {
5120                    self.client
5121                        .send(proto::UnregisterProject { project_id })
5122                        .log_err();
5123                }
5124            }
5125            ProjectClientState::Remote { remote_id, .. } => {
5126                self.client
5127                    .send(proto::LeaveProject {
5128                        project_id: *remote_id,
5129                    })
5130                    .log_err();
5131            }
5132        }
5133    }
5134
5135    fn app_will_quit(
5136        &mut self,
5137        _: &mut MutableAppContext,
5138    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
5139        let shutdown_futures = self
5140            .language_servers
5141            .drain()
5142            .filter_map(|(_, (_, server))| server.shutdown())
5143            .collect::<Vec<_>>();
5144        Some(
5145            async move {
5146                futures::future::join_all(shutdown_futures).await;
5147            }
5148            .boxed(),
5149        )
5150    }
5151}
5152
5153impl Collaborator {
5154    fn from_proto(
5155        message: proto::Collaborator,
5156        user_store: &ModelHandle<UserStore>,
5157        cx: &mut AsyncAppContext,
5158    ) -> impl Future<Output = Result<Self>> {
5159        let user = user_store.update(cx, |user_store, cx| {
5160            user_store.fetch_user(message.user_id, cx)
5161        });
5162
5163        async move {
5164            Ok(Self {
5165                peer_id: PeerId(message.peer_id),
5166                user: user.await?,
5167                replica_id: message.replica_id as ReplicaId,
5168            })
5169        }
5170    }
5171}
5172
5173impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5174    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5175        Self {
5176            worktree_id,
5177            path: path.as_ref().into(),
5178        }
5179    }
5180}
5181
5182impl From<lsp::CreateFileOptions> for fs::CreateOptions {
5183    fn from(options: lsp::CreateFileOptions) -> Self {
5184        Self {
5185            overwrite: options.overwrite.unwrap_or(false),
5186            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5187        }
5188    }
5189}
5190
5191impl From<lsp::RenameFileOptions> for fs::RenameOptions {
5192    fn from(options: lsp::RenameFileOptions) -> Self {
5193        Self {
5194            overwrite: options.overwrite.unwrap_or(false),
5195            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5196        }
5197    }
5198}
5199
5200impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
5201    fn from(options: lsp::DeleteFileOptions) -> Self {
5202        Self {
5203            recursive: options.recursive.unwrap_or(false),
5204            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5205        }
5206    }
5207}
5208
5209fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
5210    proto::Symbol {
5211        source_worktree_id: symbol.source_worktree_id.to_proto(),
5212        worktree_id: symbol.worktree_id.to_proto(),
5213        language_server_name: symbol.language_server_name.0.to_string(),
5214        name: symbol.name.clone(),
5215        kind: unsafe { mem::transmute(symbol.kind) },
5216        path: symbol.path.to_string_lossy().to_string(),
5217        start: Some(proto::Point {
5218            row: symbol.range.start.row,
5219            column: symbol.range.start.column,
5220        }),
5221        end: Some(proto::Point {
5222            row: symbol.range.end.row,
5223            column: symbol.range.end.column,
5224        }),
5225        signature: symbol.signature.to_vec(),
5226    }
5227}
5228
5229fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5230    let mut path_components = path.components();
5231    let mut base_components = base.components();
5232    let mut components: Vec<Component> = Vec::new();
5233    loop {
5234        match (path_components.next(), base_components.next()) {
5235            (None, None) => break,
5236            (Some(a), None) => {
5237                components.push(a);
5238                components.extend(path_components.by_ref());
5239                break;
5240            }
5241            (None, _) => components.push(Component::ParentDir),
5242            (Some(a), Some(b)) if components.is_empty() && a == b => (),
5243            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
5244            (Some(a), Some(_)) => {
5245                components.push(Component::ParentDir);
5246                for _ in base_components {
5247                    components.push(Component::ParentDir);
5248                }
5249                components.push(a);
5250                components.extend(path_components.by_ref());
5251                break;
5252            }
5253        }
5254    }
5255    components.iter().map(|c| c.as_os_str()).collect()
5256}
5257
5258impl Item for Buffer {
5259    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
5260        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5261    }
5262}
5263
5264#[cfg(test)]
5265mod tests {
5266    use crate::worktree::WorktreeHandle;
5267
5268    use super::{Event, *};
5269    use fs::RealFs;
5270    use futures::{future, StreamExt};
5271    use gpui::test::subscribe;
5272    use language::{
5273        tree_sitter_rust, tree_sitter_typescript, Diagnostic, FakeLspAdapter, LanguageConfig,
5274        OffsetRangeExt, Point, ToPoint,
5275    };
5276    use lsp::Url;
5277    use serde_json::json;
5278    use std::{cell::RefCell, os::unix, path::PathBuf, rc::Rc, task::Poll};
5279    use unindent::Unindent as _;
5280    use util::{assert_set_eq, test::temp_tree};
5281
5282    #[gpui::test]
5283    async fn test_populate_and_search(cx: &mut gpui::TestAppContext) {
5284        let dir = temp_tree(json!({
5285            "root": {
5286                "apple": "",
5287                "banana": {
5288                    "carrot": {
5289                        "date": "",
5290                        "endive": "",
5291                    }
5292                },
5293                "fennel": {
5294                    "grape": "",
5295                }
5296            }
5297        }));
5298
5299        let root_link_path = dir.path().join("root_link");
5300        unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
5301        unix::fs::symlink(
5302            &dir.path().join("root/fennel"),
5303            &dir.path().join("root/finnochio"),
5304        )
5305        .unwrap();
5306
5307        let project = Project::test(Arc::new(RealFs), [root_link_path.as_ref()], cx).await;
5308
5309        project.read_with(cx, |project, cx| {
5310            let tree = project.worktrees(cx).next().unwrap().read(cx);
5311            assert_eq!(tree.file_count(), 5);
5312            assert_eq!(
5313                tree.inode_for_path("fennel/grape"),
5314                tree.inode_for_path("finnochio/grape")
5315            );
5316        });
5317
5318        let cancel_flag = Default::default();
5319        let results = project
5320            .read_with(cx, |project, cx| {
5321                project.match_paths("bna", false, false, 10, &cancel_flag, cx)
5322            })
5323            .await;
5324        assert_eq!(
5325            results
5326                .into_iter()
5327                .map(|result| result.path)
5328                .collect::<Vec<Arc<Path>>>(),
5329            vec![
5330                PathBuf::from("banana/carrot/date").into(),
5331                PathBuf::from("banana/carrot/endive").into(),
5332            ]
5333        );
5334    }
5335
5336    #[gpui::test]
5337    async fn test_managing_language_servers(cx: &mut gpui::TestAppContext) {
5338        cx.foreground().forbid_parking();
5339
5340        let mut rust_language = Language::new(
5341            LanguageConfig {
5342                name: "Rust".into(),
5343                path_suffixes: vec!["rs".to_string()],
5344                ..Default::default()
5345            },
5346            Some(tree_sitter_rust::language()),
5347        );
5348        let mut json_language = Language::new(
5349            LanguageConfig {
5350                name: "JSON".into(),
5351                path_suffixes: vec!["json".to_string()],
5352                ..Default::default()
5353            },
5354            None,
5355        );
5356        let mut fake_rust_servers = rust_language.set_fake_lsp_adapter(FakeLspAdapter {
5357            name: "the-rust-language-server",
5358            capabilities: lsp::ServerCapabilities {
5359                completion_provider: Some(lsp::CompletionOptions {
5360                    trigger_characters: Some(vec![".".to_string(), "::".to_string()]),
5361                    ..Default::default()
5362                }),
5363                ..Default::default()
5364            },
5365            ..Default::default()
5366        });
5367        let mut fake_json_servers = json_language.set_fake_lsp_adapter(FakeLspAdapter {
5368            name: "the-json-language-server",
5369            capabilities: lsp::ServerCapabilities {
5370                completion_provider: Some(lsp::CompletionOptions {
5371                    trigger_characters: Some(vec![":".to_string()]),
5372                    ..Default::default()
5373                }),
5374                ..Default::default()
5375            },
5376            ..Default::default()
5377        });
5378
5379        let fs = FakeFs::new(cx.background());
5380        fs.insert_tree(
5381            "/the-root",
5382            json!({
5383                "test.rs": "const A: i32 = 1;",
5384                "test2.rs": "",
5385                "Cargo.toml": "a = 1",
5386                "package.json": "{\"a\": 1}",
5387            }),
5388        )
5389        .await;
5390
5391        let project = Project::test(fs.clone(), ["/the-root".as_ref()], cx).await;
5392        project.update(cx, |project, _| {
5393            project.languages.add(Arc::new(rust_language));
5394            project.languages.add(Arc::new(json_language));
5395        });
5396
5397        // Open a buffer without an associated language server.
5398        let toml_buffer = project
5399            .update(cx, |project, cx| {
5400                project.open_local_buffer("/the-root/Cargo.toml", cx)
5401            })
5402            .await
5403            .unwrap();
5404
5405        // Open a buffer with an associated language server.
5406        let rust_buffer = project
5407            .update(cx, |project, cx| {
5408                project.open_local_buffer("/the-root/test.rs", cx)
5409            })
5410            .await
5411            .unwrap();
5412
5413        // A server is started up, and it is notified about Rust files.
5414        let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
5415        assert_eq!(
5416            fake_rust_server
5417                .receive_notification::<lsp::notification::DidOpenTextDocument>()
5418                .await
5419                .text_document,
5420            lsp::TextDocumentItem {
5421                uri: lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
5422                version: 0,
5423                text: "const A: i32 = 1;".to_string(),
5424                language_id: Default::default()
5425            }
5426        );
5427
5428        // The buffer is configured based on the language server's capabilities.
5429        rust_buffer.read_with(cx, |buffer, _| {
5430            assert_eq!(
5431                buffer.completion_triggers(),
5432                &[".".to_string(), "::".to_string()]
5433            );
5434        });
5435        toml_buffer.read_with(cx, |buffer, _| {
5436            assert!(buffer.completion_triggers().is_empty());
5437        });
5438
5439        // Edit a buffer. The changes are reported to the language server.
5440        rust_buffer.update(cx, |buffer, cx| buffer.edit([(16..16, "2")], cx));
5441        assert_eq!(
5442            fake_rust_server
5443                .receive_notification::<lsp::notification::DidChangeTextDocument>()
5444                .await
5445                .text_document,
5446            lsp::VersionedTextDocumentIdentifier::new(
5447                lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
5448                1
5449            )
5450        );
5451
5452        // Open a third buffer with a different associated language server.
5453        let json_buffer = project
5454            .update(cx, |project, cx| {
5455                project.open_local_buffer("/the-root/package.json", cx)
5456            })
5457            .await
5458            .unwrap();
5459
5460        // A json language server is started up and is only notified about the json buffer.
5461        let mut fake_json_server = fake_json_servers.next().await.unwrap();
5462        assert_eq!(
5463            fake_json_server
5464                .receive_notification::<lsp::notification::DidOpenTextDocument>()
5465                .await
5466                .text_document,
5467            lsp::TextDocumentItem {
5468                uri: lsp::Url::from_file_path("/the-root/package.json").unwrap(),
5469                version: 0,
5470                text: "{\"a\": 1}".to_string(),
5471                language_id: Default::default()
5472            }
5473        );
5474
5475        // This buffer is configured based on the second language server's
5476        // capabilities.
5477        json_buffer.read_with(cx, |buffer, _| {
5478            assert_eq!(buffer.completion_triggers(), &[":".to_string()]);
5479        });
5480
5481        // When opening another buffer whose language server is already running,
5482        // it is also configured based on the existing language server's capabilities.
5483        let rust_buffer2 = project
5484            .update(cx, |project, cx| {
5485                project.open_local_buffer("/the-root/test2.rs", cx)
5486            })
5487            .await
5488            .unwrap();
5489        rust_buffer2.read_with(cx, |buffer, _| {
5490            assert_eq!(
5491                buffer.completion_triggers(),
5492                &[".".to_string(), "::".to_string()]
5493            );
5494        });
5495
5496        // Changes are reported only to servers matching the buffer's language.
5497        toml_buffer.update(cx, |buffer, cx| buffer.edit([(5..5, "23")], cx));
5498        rust_buffer2.update(cx, |buffer, cx| buffer.edit([(0..0, "let x = 1;")], cx));
5499        assert_eq!(
5500            fake_rust_server
5501                .receive_notification::<lsp::notification::DidChangeTextDocument>()
5502                .await
5503                .text_document,
5504            lsp::VersionedTextDocumentIdentifier::new(
5505                lsp::Url::from_file_path("/the-root/test2.rs").unwrap(),
5506                1
5507            )
5508        );
5509
5510        // Save notifications are reported to all servers.
5511        toml_buffer
5512            .update(cx, |buffer, cx| buffer.save(cx))
5513            .await
5514            .unwrap();
5515        assert_eq!(
5516            fake_rust_server
5517                .receive_notification::<lsp::notification::DidSaveTextDocument>()
5518                .await
5519                .text_document,
5520            lsp::TextDocumentIdentifier::new(
5521                lsp::Url::from_file_path("/the-root/Cargo.toml").unwrap()
5522            )
5523        );
5524        assert_eq!(
5525            fake_json_server
5526                .receive_notification::<lsp::notification::DidSaveTextDocument>()
5527                .await
5528                .text_document,
5529            lsp::TextDocumentIdentifier::new(
5530                lsp::Url::from_file_path("/the-root/Cargo.toml").unwrap()
5531            )
5532        );
5533
5534        // Renames are reported only to servers matching the buffer's language.
5535        fs.rename(
5536            Path::new("/the-root/test2.rs"),
5537            Path::new("/the-root/test3.rs"),
5538            Default::default(),
5539        )
5540        .await
5541        .unwrap();
5542        assert_eq!(
5543            fake_rust_server
5544                .receive_notification::<lsp::notification::DidCloseTextDocument>()
5545                .await
5546                .text_document,
5547            lsp::TextDocumentIdentifier::new(
5548                lsp::Url::from_file_path("/the-root/test2.rs").unwrap()
5549            ),
5550        );
5551        assert_eq!(
5552            fake_rust_server
5553                .receive_notification::<lsp::notification::DidOpenTextDocument>()
5554                .await
5555                .text_document,
5556            lsp::TextDocumentItem {
5557                uri: lsp::Url::from_file_path("/the-root/test3.rs").unwrap(),
5558                version: 0,
5559                text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
5560                language_id: Default::default()
5561            },
5562        );
5563
5564        rust_buffer2.update(cx, |buffer, cx| {
5565            buffer.update_diagnostics(
5566                DiagnosticSet::from_sorted_entries(
5567                    vec![DiagnosticEntry {
5568                        diagnostic: Default::default(),
5569                        range: Anchor::MIN..Anchor::MAX,
5570                    }],
5571                    &buffer.snapshot(),
5572                ),
5573                cx,
5574            );
5575            assert_eq!(
5576                buffer
5577                    .snapshot()
5578                    .diagnostics_in_range::<_, usize>(0..buffer.len(), false)
5579                    .count(),
5580                1
5581            );
5582        });
5583
5584        // When the rename changes the extension of the file, the buffer gets closed on the old
5585        // language server and gets opened on the new one.
5586        fs.rename(
5587            Path::new("/the-root/test3.rs"),
5588            Path::new("/the-root/test3.json"),
5589            Default::default(),
5590        )
5591        .await
5592        .unwrap();
5593        assert_eq!(
5594            fake_rust_server
5595                .receive_notification::<lsp::notification::DidCloseTextDocument>()
5596                .await
5597                .text_document,
5598            lsp::TextDocumentIdentifier::new(
5599                lsp::Url::from_file_path("/the-root/test3.rs").unwrap(),
5600            ),
5601        );
5602        assert_eq!(
5603            fake_json_server
5604                .receive_notification::<lsp::notification::DidOpenTextDocument>()
5605                .await
5606                .text_document,
5607            lsp::TextDocumentItem {
5608                uri: lsp::Url::from_file_path("/the-root/test3.json").unwrap(),
5609                version: 0,
5610                text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
5611                language_id: Default::default()
5612            },
5613        );
5614
5615        // We clear the diagnostics, since the language has changed.
5616        rust_buffer2.read_with(cx, |buffer, _| {
5617            assert_eq!(
5618                buffer
5619                    .snapshot()
5620                    .diagnostics_in_range::<_, usize>(0..buffer.len(), false)
5621                    .count(),
5622                0
5623            );
5624        });
5625
5626        // The renamed file's version resets after changing language server.
5627        rust_buffer2.update(cx, |buffer, cx| buffer.edit([(0..0, "// ")], cx));
5628        assert_eq!(
5629            fake_json_server
5630                .receive_notification::<lsp::notification::DidChangeTextDocument>()
5631                .await
5632                .text_document,
5633            lsp::VersionedTextDocumentIdentifier::new(
5634                lsp::Url::from_file_path("/the-root/test3.json").unwrap(),
5635                1
5636            )
5637        );
5638
5639        // Restart language servers
5640        project.update(cx, |project, cx| {
5641            project.restart_language_servers_for_buffers(
5642                vec![rust_buffer.clone(), json_buffer.clone()],
5643                cx,
5644            );
5645        });
5646
5647        let mut rust_shutdown_requests = fake_rust_server
5648            .handle_request::<lsp::request::Shutdown, _, _>(|_, _| future::ready(Ok(())));
5649        let mut json_shutdown_requests = fake_json_server
5650            .handle_request::<lsp::request::Shutdown, _, _>(|_, _| future::ready(Ok(())));
5651        futures::join!(rust_shutdown_requests.next(), json_shutdown_requests.next());
5652
5653        let mut fake_rust_server = fake_rust_servers.next().await.unwrap();
5654        let mut fake_json_server = fake_json_servers.next().await.unwrap();
5655
5656        // Ensure rust document is reopened in new rust language server
5657        assert_eq!(
5658            fake_rust_server
5659                .receive_notification::<lsp::notification::DidOpenTextDocument>()
5660                .await
5661                .text_document,
5662            lsp::TextDocumentItem {
5663                uri: lsp::Url::from_file_path("/the-root/test.rs").unwrap(),
5664                version: 1,
5665                text: rust_buffer.read_with(cx, |buffer, _| buffer.text()),
5666                language_id: Default::default()
5667            }
5668        );
5669
5670        // Ensure json documents are reopened in new json language server
5671        assert_set_eq!(
5672            [
5673                fake_json_server
5674                    .receive_notification::<lsp::notification::DidOpenTextDocument>()
5675                    .await
5676                    .text_document,
5677                fake_json_server
5678                    .receive_notification::<lsp::notification::DidOpenTextDocument>()
5679                    .await
5680                    .text_document,
5681            ],
5682            [
5683                lsp::TextDocumentItem {
5684                    uri: lsp::Url::from_file_path("/the-root/package.json").unwrap(),
5685                    version: 0,
5686                    text: json_buffer.read_with(cx, |buffer, _| buffer.text()),
5687                    language_id: Default::default()
5688                },
5689                lsp::TextDocumentItem {
5690                    uri: lsp::Url::from_file_path("/the-root/test3.json").unwrap(),
5691                    version: 1,
5692                    text: rust_buffer2.read_with(cx, |buffer, _| buffer.text()),
5693                    language_id: Default::default()
5694                }
5695            ]
5696        );
5697
5698        // Close notifications are reported only to servers matching the buffer's language.
5699        cx.update(|_| drop(json_buffer));
5700        let close_message = lsp::DidCloseTextDocumentParams {
5701            text_document: lsp::TextDocumentIdentifier::new(
5702                lsp::Url::from_file_path("/the-root/package.json").unwrap(),
5703            ),
5704        };
5705        assert_eq!(
5706            fake_json_server
5707                .receive_notification::<lsp::notification::DidCloseTextDocument>()
5708                .await,
5709            close_message,
5710        );
5711    }
5712
5713    #[gpui::test]
5714    async fn test_single_file_worktrees_diagnostics(cx: &mut gpui::TestAppContext) {
5715        cx.foreground().forbid_parking();
5716
5717        let fs = FakeFs::new(cx.background());
5718        fs.insert_tree(
5719            "/dir",
5720            json!({
5721                "a.rs": "let a = 1;",
5722                "b.rs": "let b = 2;"
5723            }),
5724        )
5725        .await;
5726
5727        let project = Project::test(fs, ["/dir/a.rs".as_ref(), "/dir/b.rs".as_ref()], cx).await;
5728
5729        let buffer_a = project
5730            .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
5731            .await
5732            .unwrap();
5733        let buffer_b = project
5734            .update(cx, |project, cx| project.open_local_buffer("/dir/b.rs", cx))
5735            .await
5736            .unwrap();
5737
5738        project.update(cx, |project, cx| {
5739            project
5740                .update_diagnostics(
5741                    lsp::PublishDiagnosticsParams {
5742                        uri: Url::from_file_path("/dir/a.rs").unwrap(),
5743                        version: None,
5744                        diagnostics: vec![lsp::Diagnostic {
5745                            range: lsp::Range::new(
5746                                lsp::Position::new(0, 4),
5747                                lsp::Position::new(0, 5),
5748                            ),
5749                            severity: Some(lsp::DiagnosticSeverity::ERROR),
5750                            message: "error 1".to_string(),
5751                            ..Default::default()
5752                        }],
5753                    },
5754                    &[],
5755                    cx,
5756                )
5757                .unwrap();
5758            project
5759                .update_diagnostics(
5760                    lsp::PublishDiagnosticsParams {
5761                        uri: Url::from_file_path("/dir/b.rs").unwrap(),
5762                        version: None,
5763                        diagnostics: vec![lsp::Diagnostic {
5764                            range: lsp::Range::new(
5765                                lsp::Position::new(0, 4),
5766                                lsp::Position::new(0, 5),
5767                            ),
5768                            severity: Some(lsp::DiagnosticSeverity::WARNING),
5769                            message: "error 2".to_string(),
5770                            ..Default::default()
5771                        }],
5772                    },
5773                    &[],
5774                    cx,
5775                )
5776                .unwrap();
5777        });
5778
5779        buffer_a.read_with(cx, |buffer, _| {
5780            let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
5781            assert_eq!(
5782                chunks
5783                    .iter()
5784                    .map(|(s, d)| (s.as_str(), *d))
5785                    .collect::<Vec<_>>(),
5786                &[
5787                    ("let ", None),
5788                    ("a", Some(DiagnosticSeverity::ERROR)),
5789                    (" = 1;", None),
5790                ]
5791            );
5792        });
5793        buffer_b.read_with(cx, |buffer, _| {
5794            let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
5795            assert_eq!(
5796                chunks
5797                    .iter()
5798                    .map(|(s, d)| (s.as_str(), *d))
5799                    .collect::<Vec<_>>(),
5800                &[
5801                    ("let ", None),
5802                    ("b", Some(DiagnosticSeverity::WARNING)),
5803                    (" = 2;", None),
5804                ]
5805            );
5806        });
5807    }
5808
5809    #[gpui::test]
5810    async fn test_disk_based_diagnostics_progress(cx: &mut gpui::TestAppContext) {
5811        cx.foreground().forbid_parking();
5812
5813        let progress_token = "the-progress-token";
5814        let mut language = Language::new(
5815            LanguageConfig {
5816                name: "Rust".into(),
5817                path_suffixes: vec!["rs".to_string()],
5818                ..Default::default()
5819            },
5820            Some(tree_sitter_rust::language()),
5821        );
5822        let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
5823            disk_based_diagnostics_progress_token: Some(progress_token),
5824            disk_based_diagnostics_sources: &["disk"],
5825            ..Default::default()
5826        });
5827
5828        let fs = FakeFs::new(cx.background());
5829        fs.insert_tree(
5830            "/dir",
5831            json!({
5832                "a.rs": "fn a() { A }",
5833                "b.rs": "const y: i32 = 1",
5834            }),
5835        )
5836        .await;
5837
5838        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
5839        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
5840        let worktree_id =
5841            project.read_with(cx, |p, cx| p.worktrees(cx).next().unwrap().read(cx).id());
5842
5843        // Cause worktree to start the fake language server
5844        let _buffer = project
5845            .update(cx, |project, cx| project.open_local_buffer("/dir/b.rs", cx))
5846            .await
5847            .unwrap();
5848
5849        let mut events = subscribe(&project, cx);
5850
5851        let mut fake_server = fake_servers.next().await.unwrap();
5852        fake_server.start_progress(progress_token).await;
5853        assert_eq!(
5854            events.next().await.unwrap(),
5855            Event::DiskBasedDiagnosticsStarted
5856        );
5857
5858        fake_server.start_progress(progress_token).await;
5859        fake_server.end_progress(progress_token).await;
5860        fake_server.start_progress(progress_token).await;
5861
5862        fake_server.notify::<lsp::notification::PublishDiagnostics>(
5863            lsp::PublishDiagnosticsParams {
5864                uri: Url::from_file_path("/dir/a.rs").unwrap(),
5865                version: None,
5866                diagnostics: vec![lsp::Diagnostic {
5867                    range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
5868                    severity: Some(lsp::DiagnosticSeverity::ERROR),
5869                    message: "undefined variable 'A'".to_string(),
5870                    ..Default::default()
5871                }],
5872            },
5873        );
5874        assert_eq!(
5875            events.next().await.unwrap(),
5876            Event::DiagnosticsUpdated((worktree_id, Path::new("a.rs")).into())
5877        );
5878
5879        fake_server.end_progress(progress_token).await;
5880        fake_server.end_progress(progress_token).await;
5881        assert_eq!(
5882            events.next().await.unwrap(),
5883            Event::DiskBasedDiagnosticsUpdated
5884        );
5885        assert_eq!(
5886            events.next().await.unwrap(),
5887            Event::DiskBasedDiagnosticsFinished
5888        );
5889
5890        let buffer = project
5891            .update(cx, |p, cx| p.open_local_buffer("/dir/a.rs", cx))
5892            .await
5893            .unwrap();
5894
5895        buffer.read_with(cx, |buffer, _| {
5896            let snapshot = buffer.snapshot();
5897            let diagnostics = snapshot
5898                .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
5899                .collect::<Vec<_>>();
5900            assert_eq!(
5901                diagnostics,
5902                &[DiagnosticEntry {
5903                    range: Point::new(0, 9)..Point::new(0, 10),
5904                    diagnostic: Diagnostic {
5905                        severity: lsp::DiagnosticSeverity::ERROR,
5906                        message: "undefined variable 'A'".to_string(),
5907                        group_id: 0,
5908                        is_primary: true,
5909                        ..Default::default()
5910                    }
5911                }]
5912            )
5913        });
5914
5915        // Ensure publishing empty diagnostics twice only results in one update event.
5916        fake_server.notify::<lsp::notification::PublishDiagnostics>(
5917            lsp::PublishDiagnosticsParams {
5918                uri: Url::from_file_path("/dir/a.rs").unwrap(),
5919                version: None,
5920                diagnostics: Default::default(),
5921            },
5922        );
5923        assert_eq!(
5924            events.next().await.unwrap(),
5925            Event::DiagnosticsUpdated((worktree_id, Path::new("a.rs")).into())
5926        );
5927
5928        fake_server.notify::<lsp::notification::PublishDiagnostics>(
5929            lsp::PublishDiagnosticsParams {
5930                uri: Url::from_file_path("/dir/a.rs").unwrap(),
5931                version: None,
5932                diagnostics: Default::default(),
5933            },
5934        );
5935        cx.foreground().run_until_parked();
5936        assert_eq!(futures::poll!(events.next()), Poll::Pending);
5937    }
5938
5939    #[gpui::test]
5940    async fn test_restarting_server_with_diagnostics_running(cx: &mut gpui::TestAppContext) {
5941        cx.foreground().forbid_parking();
5942
5943        let progress_token = "the-progress-token";
5944        let mut language = Language::new(
5945            LanguageConfig {
5946                path_suffixes: vec!["rs".to_string()],
5947                ..Default::default()
5948            },
5949            None,
5950        );
5951        let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
5952            disk_based_diagnostics_sources: &["disk"],
5953            disk_based_diagnostics_progress_token: Some(progress_token),
5954            ..Default::default()
5955        });
5956
5957        let fs = FakeFs::new(cx.background());
5958        fs.insert_tree("/dir", json!({ "a.rs": "" })).await;
5959
5960        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
5961        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
5962
5963        let buffer = project
5964            .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
5965            .await
5966            .unwrap();
5967
5968        // Simulate diagnostics starting to update.
5969        let mut fake_server = fake_servers.next().await.unwrap();
5970        fake_server.start_progress(progress_token).await;
5971
5972        // Restart the server before the diagnostics finish updating.
5973        project.update(cx, |project, cx| {
5974            project.restart_language_servers_for_buffers([buffer], cx);
5975        });
5976        let mut events = subscribe(&project, cx);
5977
5978        // Simulate the newly started server sending more diagnostics.
5979        let mut fake_server = fake_servers.next().await.unwrap();
5980        fake_server.start_progress(progress_token).await;
5981        assert_eq!(
5982            events.next().await.unwrap(),
5983            Event::DiskBasedDiagnosticsStarted
5984        );
5985
5986        // All diagnostics are considered done, despite the old server's diagnostic
5987        // task never completing.
5988        fake_server.end_progress(progress_token).await;
5989        assert_eq!(
5990            events.next().await.unwrap(),
5991            Event::DiskBasedDiagnosticsUpdated
5992        );
5993        assert_eq!(
5994            events.next().await.unwrap(),
5995            Event::DiskBasedDiagnosticsFinished
5996        );
5997        project.read_with(cx, |project, _| {
5998            assert!(!project.is_running_disk_based_diagnostics());
5999        });
6000    }
6001
6002    #[gpui::test]
6003    async fn test_transforming_diagnostics(cx: &mut gpui::TestAppContext) {
6004        cx.foreground().forbid_parking();
6005
6006        let mut language = Language::new(
6007            LanguageConfig {
6008                name: "Rust".into(),
6009                path_suffixes: vec!["rs".to_string()],
6010                ..Default::default()
6011            },
6012            Some(tree_sitter_rust::language()),
6013        );
6014        let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
6015            disk_based_diagnostics_sources: &["disk"],
6016            ..Default::default()
6017        });
6018
6019        let text = "
6020            fn a() { A }
6021            fn b() { BB }
6022            fn c() { CCC }
6023        "
6024        .unindent();
6025
6026        let fs = FakeFs::new(cx.background());
6027        fs.insert_tree("/dir", json!({ "a.rs": text })).await;
6028
6029        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6030        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6031
6032        let buffer = project
6033            .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6034            .await
6035            .unwrap();
6036
6037        let mut fake_server = fake_servers.next().await.unwrap();
6038        let open_notification = fake_server
6039            .receive_notification::<lsp::notification::DidOpenTextDocument>()
6040            .await;
6041
6042        // Edit the buffer, moving the content down
6043        buffer.update(cx, |buffer, cx| buffer.edit([(0..0, "\n\n")], cx));
6044        let change_notification_1 = fake_server
6045            .receive_notification::<lsp::notification::DidChangeTextDocument>()
6046            .await;
6047        assert!(
6048            change_notification_1.text_document.version > open_notification.text_document.version
6049        );
6050
6051        // Report some diagnostics for the initial version of the buffer
6052        fake_server.notify::<lsp::notification::PublishDiagnostics>(
6053            lsp::PublishDiagnosticsParams {
6054                uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
6055                version: Some(open_notification.text_document.version),
6056                diagnostics: vec![
6057                    lsp::Diagnostic {
6058                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6059                        severity: Some(DiagnosticSeverity::ERROR),
6060                        message: "undefined variable 'A'".to_string(),
6061                        source: Some("disk".to_string()),
6062                        ..Default::default()
6063                    },
6064                    lsp::Diagnostic {
6065                        range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
6066                        severity: Some(DiagnosticSeverity::ERROR),
6067                        message: "undefined variable 'BB'".to_string(),
6068                        source: Some("disk".to_string()),
6069                        ..Default::default()
6070                    },
6071                    lsp::Diagnostic {
6072                        range: lsp::Range::new(lsp::Position::new(2, 9), lsp::Position::new(2, 12)),
6073                        severity: Some(DiagnosticSeverity::ERROR),
6074                        source: Some("disk".to_string()),
6075                        message: "undefined variable 'CCC'".to_string(),
6076                        ..Default::default()
6077                    },
6078                ],
6079            },
6080        );
6081
6082        // The diagnostics have moved down since they were created.
6083        buffer.next_notification(cx).await;
6084        buffer.read_with(cx, |buffer, _| {
6085            assert_eq!(
6086                buffer
6087                    .snapshot()
6088                    .diagnostics_in_range::<_, Point>(Point::new(3, 0)..Point::new(5, 0), false)
6089                    .collect::<Vec<_>>(),
6090                &[
6091                    DiagnosticEntry {
6092                        range: Point::new(3, 9)..Point::new(3, 11),
6093                        diagnostic: Diagnostic {
6094                            severity: DiagnosticSeverity::ERROR,
6095                            message: "undefined variable 'BB'".to_string(),
6096                            is_disk_based: true,
6097                            group_id: 1,
6098                            is_primary: true,
6099                            ..Default::default()
6100                        },
6101                    },
6102                    DiagnosticEntry {
6103                        range: Point::new(4, 9)..Point::new(4, 12),
6104                        diagnostic: Diagnostic {
6105                            severity: DiagnosticSeverity::ERROR,
6106                            message: "undefined variable 'CCC'".to_string(),
6107                            is_disk_based: true,
6108                            group_id: 2,
6109                            is_primary: true,
6110                            ..Default::default()
6111                        }
6112                    }
6113                ]
6114            );
6115            assert_eq!(
6116                chunks_with_diagnostics(buffer, 0..buffer.len()),
6117                [
6118                    ("\n\nfn a() { ".to_string(), None),
6119                    ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
6120                    (" }\nfn b() { ".to_string(), None),
6121                    ("BB".to_string(), Some(DiagnosticSeverity::ERROR)),
6122                    (" }\nfn c() { ".to_string(), None),
6123                    ("CCC".to_string(), Some(DiagnosticSeverity::ERROR)),
6124                    (" }\n".to_string(), None),
6125                ]
6126            );
6127            assert_eq!(
6128                chunks_with_diagnostics(buffer, Point::new(3, 10)..Point::new(4, 11)),
6129                [
6130                    ("B".to_string(), Some(DiagnosticSeverity::ERROR)),
6131                    (" }\nfn c() { ".to_string(), None),
6132                    ("CC".to_string(), Some(DiagnosticSeverity::ERROR)),
6133                ]
6134            );
6135        });
6136
6137        // Ensure overlapping diagnostics are highlighted correctly.
6138        fake_server.notify::<lsp::notification::PublishDiagnostics>(
6139            lsp::PublishDiagnosticsParams {
6140                uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
6141                version: Some(open_notification.text_document.version),
6142                diagnostics: vec![
6143                    lsp::Diagnostic {
6144                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6145                        severity: Some(DiagnosticSeverity::ERROR),
6146                        message: "undefined variable 'A'".to_string(),
6147                        source: Some("disk".to_string()),
6148                        ..Default::default()
6149                    },
6150                    lsp::Diagnostic {
6151                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 12)),
6152                        severity: Some(DiagnosticSeverity::WARNING),
6153                        message: "unreachable statement".to_string(),
6154                        source: Some("disk".to_string()),
6155                        ..Default::default()
6156                    },
6157                ],
6158            },
6159        );
6160
6161        buffer.next_notification(cx).await;
6162        buffer.read_with(cx, |buffer, _| {
6163            assert_eq!(
6164                buffer
6165                    .snapshot()
6166                    .diagnostics_in_range::<_, Point>(Point::new(2, 0)..Point::new(3, 0), false)
6167                    .collect::<Vec<_>>(),
6168                &[
6169                    DiagnosticEntry {
6170                        range: Point::new(2, 9)..Point::new(2, 12),
6171                        diagnostic: Diagnostic {
6172                            severity: DiagnosticSeverity::WARNING,
6173                            message: "unreachable statement".to_string(),
6174                            is_disk_based: true,
6175                            group_id: 1,
6176                            is_primary: true,
6177                            ..Default::default()
6178                        }
6179                    },
6180                    DiagnosticEntry {
6181                        range: Point::new(2, 9)..Point::new(2, 10),
6182                        diagnostic: Diagnostic {
6183                            severity: DiagnosticSeverity::ERROR,
6184                            message: "undefined variable 'A'".to_string(),
6185                            is_disk_based: true,
6186                            group_id: 0,
6187                            is_primary: true,
6188                            ..Default::default()
6189                        },
6190                    }
6191                ]
6192            );
6193            assert_eq!(
6194                chunks_with_diagnostics(buffer, Point::new(2, 0)..Point::new(3, 0)),
6195                [
6196                    ("fn a() { ".to_string(), None),
6197                    ("A".to_string(), Some(DiagnosticSeverity::ERROR)),
6198                    (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
6199                    ("\n".to_string(), None),
6200                ]
6201            );
6202            assert_eq!(
6203                chunks_with_diagnostics(buffer, Point::new(2, 10)..Point::new(3, 0)),
6204                [
6205                    (" }".to_string(), Some(DiagnosticSeverity::WARNING)),
6206                    ("\n".to_string(), None),
6207                ]
6208            );
6209        });
6210
6211        // Keep editing the buffer and ensure disk-based diagnostics get translated according to the
6212        // changes since the last save.
6213        buffer.update(cx, |buffer, cx| {
6214            buffer.edit([(Point::new(2, 0)..Point::new(2, 0), "    ")], cx);
6215            buffer.edit([(Point::new(2, 8)..Point::new(2, 10), "(x: usize)")], cx);
6216            buffer.edit([(Point::new(3, 10)..Point::new(3, 10), "xxx")], cx);
6217        });
6218        let change_notification_2 = fake_server
6219            .receive_notification::<lsp::notification::DidChangeTextDocument>()
6220            .await;
6221        assert!(
6222            change_notification_2.text_document.version
6223                > change_notification_1.text_document.version
6224        );
6225
6226        // Handle out-of-order diagnostics
6227        fake_server.notify::<lsp::notification::PublishDiagnostics>(
6228            lsp::PublishDiagnosticsParams {
6229                uri: lsp::Url::from_file_path("/dir/a.rs").unwrap(),
6230                version: Some(change_notification_2.text_document.version),
6231                diagnostics: vec![
6232                    lsp::Diagnostic {
6233                        range: lsp::Range::new(lsp::Position::new(1, 9), lsp::Position::new(1, 11)),
6234                        severity: Some(DiagnosticSeverity::ERROR),
6235                        message: "undefined variable 'BB'".to_string(),
6236                        source: Some("disk".to_string()),
6237                        ..Default::default()
6238                    },
6239                    lsp::Diagnostic {
6240                        range: lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6241                        severity: Some(DiagnosticSeverity::WARNING),
6242                        message: "undefined variable 'A'".to_string(),
6243                        source: Some("disk".to_string()),
6244                        ..Default::default()
6245                    },
6246                ],
6247            },
6248        );
6249
6250        buffer.next_notification(cx).await;
6251        buffer.read_with(cx, |buffer, _| {
6252            assert_eq!(
6253                buffer
6254                    .snapshot()
6255                    .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
6256                    .collect::<Vec<_>>(),
6257                &[
6258                    DiagnosticEntry {
6259                        range: Point::new(2, 21)..Point::new(2, 22),
6260                        diagnostic: Diagnostic {
6261                            severity: DiagnosticSeverity::WARNING,
6262                            message: "undefined variable 'A'".to_string(),
6263                            is_disk_based: true,
6264                            group_id: 1,
6265                            is_primary: true,
6266                            ..Default::default()
6267                        }
6268                    },
6269                    DiagnosticEntry {
6270                        range: Point::new(3, 9)..Point::new(3, 14),
6271                        diagnostic: Diagnostic {
6272                            severity: DiagnosticSeverity::ERROR,
6273                            message: "undefined variable 'BB'".to_string(),
6274                            is_disk_based: true,
6275                            group_id: 0,
6276                            is_primary: true,
6277                            ..Default::default()
6278                        },
6279                    }
6280                ]
6281            );
6282        });
6283    }
6284
6285    #[gpui::test]
6286    async fn test_empty_diagnostic_ranges(cx: &mut gpui::TestAppContext) {
6287        cx.foreground().forbid_parking();
6288
6289        let text = concat!(
6290            "let one = ;\n", //
6291            "let two = \n",
6292            "let three = 3;\n",
6293        );
6294
6295        let fs = FakeFs::new(cx.background());
6296        fs.insert_tree("/dir", json!({ "a.rs": text })).await;
6297
6298        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6299        let buffer = project
6300            .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6301            .await
6302            .unwrap();
6303
6304        project.update(cx, |project, cx| {
6305            project
6306                .update_buffer_diagnostics(
6307                    &buffer,
6308                    vec![
6309                        DiagnosticEntry {
6310                            range: PointUtf16::new(0, 10)..PointUtf16::new(0, 10),
6311                            diagnostic: Diagnostic {
6312                                severity: DiagnosticSeverity::ERROR,
6313                                message: "syntax error 1".to_string(),
6314                                ..Default::default()
6315                            },
6316                        },
6317                        DiagnosticEntry {
6318                            range: PointUtf16::new(1, 10)..PointUtf16::new(1, 10),
6319                            diagnostic: Diagnostic {
6320                                severity: DiagnosticSeverity::ERROR,
6321                                message: "syntax error 2".to_string(),
6322                                ..Default::default()
6323                            },
6324                        },
6325                    ],
6326                    None,
6327                    cx,
6328                )
6329                .unwrap();
6330        });
6331
6332        // An empty range is extended forward to include the following character.
6333        // At the end of a line, an empty range is extended backward to include
6334        // the preceding character.
6335        buffer.read_with(cx, |buffer, _| {
6336            let chunks = chunks_with_diagnostics(&buffer, 0..buffer.len());
6337            assert_eq!(
6338                chunks
6339                    .iter()
6340                    .map(|(s, d)| (s.as_str(), *d))
6341                    .collect::<Vec<_>>(),
6342                &[
6343                    ("let one = ", None),
6344                    (";", Some(DiagnosticSeverity::ERROR)),
6345                    ("\nlet two =", None),
6346                    (" ", Some(DiagnosticSeverity::ERROR)),
6347                    ("\nlet three = 3;\n", None)
6348                ]
6349            );
6350        });
6351    }
6352
6353    #[gpui::test]
6354    async fn test_edits_from_lsp_with_past_version(cx: &mut gpui::TestAppContext) {
6355        cx.foreground().forbid_parking();
6356
6357        let mut language = Language::new(
6358            LanguageConfig {
6359                name: "Rust".into(),
6360                path_suffixes: vec!["rs".to_string()],
6361                ..Default::default()
6362            },
6363            Some(tree_sitter_rust::language()),
6364        );
6365        let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
6366
6367        let text = "
6368            fn a() {
6369                f1();
6370            }
6371            fn b() {
6372                f2();
6373            }
6374            fn c() {
6375                f3();
6376            }
6377        "
6378        .unindent();
6379
6380        let fs = FakeFs::new(cx.background());
6381        fs.insert_tree(
6382            "/dir",
6383            json!({
6384                "a.rs": text.clone(),
6385            }),
6386        )
6387        .await;
6388
6389        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6390        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6391        let buffer = project
6392            .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6393            .await
6394            .unwrap();
6395
6396        let mut fake_server = fake_servers.next().await.unwrap();
6397        let lsp_document_version = fake_server
6398            .receive_notification::<lsp::notification::DidOpenTextDocument>()
6399            .await
6400            .text_document
6401            .version;
6402
6403        // Simulate editing the buffer after the language server computes some edits.
6404        buffer.update(cx, |buffer, cx| {
6405            buffer.edit(
6406                [(
6407                    Point::new(0, 0)..Point::new(0, 0),
6408                    "// above first function\n",
6409                )],
6410                cx,
6411            );
6412            buffer.edit(
6413                [(
6414                    Point::new(2, 0)..Point::new(2, 0),
6415                    "    // inside first function\n",
6416                )],
6417                cx,
6418            );
6419            buffer.edit(
6420                [(
6421                    Point::new(6, 4)..Point::new(6, 4),
6422                    "// inside second function ",
6423                )],
6424                cx,
6425            );
6426
6427            assert_eq!(
6428                buffer.text(),
6429                "
6430                    // above first function
6431                    fn a() {
6432                        // inside first function
6433                        f1();
6434                    }
6435                    fn b() {
6436                        // inside second function f2();
6437                    }
6438                    fn c() {
6439                        f3();
6440                    }
6441                "
6442                .unindent()
6443            );
6444        });
6445
6446        let edits = project
6447            .update(cx, |project, cx| {
6448                project.edits_from_lsp(
6449                    &buffer,
6450                    vec![
6451                        // replace body of first function
6452                        lsp::TextEdit {
6453                            range: lsp::Range::new(
6454                                lsp::Position::new(0, 0),
6455                                lsp::Position::new(3, 0),
6456                            ),
6457                            new_text: "
6458                                fn a() {
6459                                    f10();
6460                                }
6461                            "
6462                            .unindent(),
6463                        },
6464                        // edit inside second function
6465                        lsp::TextEdit {
6466                            range: lsp::Range::new(
6467                                lsp::Position::new(4, 6),
6468                                lsp::Position::new(4, 6),
6469                            ),
6470                            new_text: "00".into(),
6471                        },
6472                        // edit inside third function via two distinct edits
6473                        lsp::TextEdit {
6474                            range: lsp::Range::new(
6475                                lsp::Position::new(7, 5),
6476                                lsp::Position::new(7, 5),
6477                            ),
6478                            new_text: "4000".into(),
6479                        },
6480                        lsp::TextEdit {
6481                            range: lsp::Range::new(
6482                                lsp::Position::new(7, 5),
6483                                lsp::Position::new(7, 6),
6484                            ),
6485                            new_text: "".into(),
6486                        },
6487                    ],
6488                    Some(lsp_document_version),
6489                    cx,
6490                )
6491            })
6492            .await
6493            .unwrap();
6494
6495        buffer.update(cx, |buffer, cx| {
6496            for (range, new_text) in edits {
6497                buffer.edit([(range, new_text)], cx);
6498            }
6499            assert_eq!(
6500                buffer.text(),
6501                "
6502                    // above first function
6503                    fn a() {
6504                        // inside first function
6505                        f10();
6506                    }
6507                    fn b() {
6508                        // inside second function f200();
6509                    }
6510                    fn c() {
6511                        f4000();
6512                    }
6513                "
6514                .unindent()
6515            );
6516        });
6517    }
6518
6519    #[gpui::test]
6520    async fn test_edits_from_lsp_with_edits_on_adjacent_lines(cx: &mut gpui::TestAppContext) {
6521        cx.foreground().forbid_parking();
6522
6523        let text = "
6524            use a::b;
6525            use a::c;
6526
6527            fn f() {
6528                b();
6529                c();
6530            }
6531        "
6532        .unindent();
6533
6534        let fs = FakeFs::new(cx.background());
6535        fs.insert_tree(
6536            "/dir",
6537            json!({
6538                "a.rs": text.clone(),
6539            }),
6540        )
6541        .await;
6542
6543        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6544        let buffer = project
6545            .update(cx, |project, cx| project.open_local_buffer("/dir/a.rs", cx))
6546            .await
6547            .unwrap();
6548
6549        // Simulate the language server sending us a small edit in the form of a very large diff.
6550        // Rust-analyzer does this when performing a merge-imports code action.
6551        let edits = project
6552            .update(cx, |project, cx| {
6553                project.edits_from_lsp(
6554                    &buffer,
6555                    [
6556                        // Replace the first use statement without editing the semicolon.
6557                        lsp::TextEdit {
6558                            range: lsp::Range::new(
6559                                lsp::Position::new(0, 4),
6560                                lsp::Position::new(0, 8),
6561                            ),
6562                            new_text: "a::{b, c}".into(),
6563                        },
6564                        // Reinsert the remainder of the file between the semicolon and the final
6565                        // newline of the file.
6566                        lsp::TextEdit {
6567                            range: lsp::Range::new(
6568                                lsp::Position::new(0, 9),
6569                                lsp::Position::new(0, 9),
6570                            ),
6571                            new_text: "\n\n".into(),
6572                        },
6573                        lsp::TextEdit {
6574                            range: lsp::Range::new(
6575                                lsp::Position::new(0, 9),
6576                                lsp::Position::new(0, 9),
6577                            ),
6578                            new_text: "
6579                                fn f() {
6580                                    b();
6581                                    c();
6582                                }"
6583                            .unindent(),
6584                        },
6585                        // Delete everything after the first newline of the file.
6586                        lsp::TextEdit {
6587                            range: lsp::Range::new(
6588                                lsp::Position::new(1, 0),
6589                                lsp::Position::new(7, 0),
6590                            ),
6591                            new_text: "".into(),
6592                        },
6593                    ],
6594                    None,
6595                    cx,
6596                )
6597            })
6598            .await
6599            .unwrap();
6600
6601        buffer.update(cx, |buffer, cx| {
6602            let edits = edits
6603                .into_iter()
6604                .map(|(range, text)| {
6605                    (
6606                        range.start.to_point(&buffer)..range.end.to_point(&buffer),
6607                        text,
6608                    )
6609                })
6610                .collect::<Vec<_>>();
6611
6612            assert_eq!(
6613                edits,
6614                [
6615                    (Point::new(0, 4)..Point::new(0, 8), "a::{b, c}".into()),
6616                    (Point::new(1, 0)..Point::new(2, 0), "".into())
6617                ]
6618            );
6619
6620            for (range, new_text) in edits {
6621                buffer.edit([(range, new_text)], cx);
6622            }
6623            assert_eq!(
6624                buffer.text(),
6625                "
6626                    use a::{b, c};
6627
6628                    fn f() {
6629                        b();
6630                        c();
6631                    }
6632                "
6633                .unindent()
6634            );
6635        });
6636    }
6637
6638    fn chunks_with_diagnostics<T: ToOffset + ToPoint>(
6639        buffer: &Buffer,
6640        range: Range<T>,
6641    ) -> Vec<(String, Option<DiagnosticSeverity>)> {
6642        let mut chunks: Vec<(String, Option<DiagnosticSeverity>)> = Vec::new();
6643        for chunk in buffer.snapshot().chunks(range, true) {
6644            if chunks.last().map_or(false, |prev_chunk| {
6645                prev_chunk.1 == chunk.diagnostic_severity
6646            }) {
6647                chunks.last_mut().unwrap().0.push_str(chunk.text);
6648            } else {
6649                chunks.push((chunk.text.to_string(), chunk.diagnostic_severity));
6650            }
6651        }
6652        chunks
6653    }
6654
6655    #[gpui::test]
6656    async fn test_search_worktree_without_files(cx: &mut gpui::TestAppContext) {
6657        let dir = temp_tree(json!({
6658            "root": {
6659                "dir1": {},
6660                "dir2": {
6661                    "dir3": {}
6662                }
6663            }
6664        }));
6665
6666        let project = Project::test(Arc::new(RealFs), [dir.path()], cx).await;
6667        let cancel_flag = Default::default();
6668        let results = project
6669            .read_with(cx, |project, cx| {
6670                project.match_paths("dir", false, false, 10, &cancel_flag, cx)
6671            })
6672            .await;
6673
6674        assert!(results.is_empty());
6675    }
6676
6677    #[gpui::test(iterations = 10)]
6678    async fn test_definition(cx: &mut gpui::TestAppContext) {
6679        let mut language = Language::new(
6680            LanguageConfig {
6681                name: "Rust".into(),
6682                path_suffixes: vec!["rs".to_string()],
6683                ..Default::default()
6684            },
6685            Some(tree_sitter_rust::language()),
6686        );
6687        let mut fake_servers = language.set_fake_lsp_adapter(Default::default());
6688
6689        let fs = FakeFs::new(cx.background());
6690        fs.insert_tree(
6691            "/dir",
6692            json!({
6693                "a.rs": "const fn a() { A }",
6694                "b.rs": "const y: i32 = crate::a()",
6695            }),
6696        )
6697        .await;
6698
6699        let project = Project::test(fs, ["/dir/b.rs".as_ref()], cx).await;
6700        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6701
6702        let buffer = project
6703            .update(cx, |project, cx| project.open_local_buffer("/dir/b.rs", cx))
6704            .await
6705            .unwrap();
6706
6707        let fake_server = fake_servers.next().await.unwrap();
6708        fake_server.handle_request::<lsp::request::GotoDefinition, _, _>(|params, _| async move {
6709            let params = params.text_document_position_params;
6710            assert_eq!(
6711                params.text_document.uri.to_file_path().unwrap(),
6712                Path::new("/dir/b.rs"),
6713            );
6714            assert_eq!(params.position, lsp::Position::new(0, 22));
6715
6716            Ok(Some(lsp::GotoDefinitionResponse::Scalar(
6717                lsp::Location::new(
6718                    lsp::Url::from_file_path("/dir/a.rs").unwrap(),
6719                    lsp::Range::new(lsp::Position::new(0, 9), lsp::Position::new(0, 10)),
6720                ),
6721            )))
6722        });
6723
6724        let mut definitions = project
6725            .update(cx, |project, cx| project.definition(&buffer, 22, cx))
6726            .await
6727            .unwrap();
6728
6729        assert_eq!(definitions.len(), 1);
6730        let definition = definitions.pop().unwrap();
6731        cx.update(|cx| {
6732            let target_buffer = definition.buffer.read(cx);
6733            assert_eq!(
6734                target_buffer
6735                    .file()
6736                    .unwrap()
6737                    .as_local()
6738                    .unwrap()
6739                    .abs_path(cx),
6740                Path::new("/dir/a.rs"),
6741            );
6742            assert_eq!(definition.range.to_offset(target_buffer), 9..10);
6743            assert_eq!(
6744                list_worktrees(&project, cx),
6745                [("/dir/b.rs".as_ref(), true), ("/dir/a.rs".as_ref(), false)]
6746            );
6747
6748            drop(definition);
6749        });
6750        cx.read(|cx| {
6751            assert_eq!(list_worktrees(&project, cx), [("/dir/b.rs".as_ref(), true)]);
6752        });
6753
6754        fn list_worktrees<'a>(
6755            project: &'a ModelHandle<Project>,
6756            cx: &'a AppContext,
6757        ) -> Vec<(&'a Path, bool)> {
6758            project
6759                .read(cx)
6760                .worktrees(cx)
6761                .map(|worktree| {
6762                    let worktree = worktree.read(cx);
6763                    (
6764                        worktree.as_local().unwrap().abs_path().as_ref(),
6765                        worktree.is_visible(),
6766                    )
6767                })
6768                .collect::<Vec<_>>()
6769        }
6770    }
6771
6772    #[gpui::test]
6773    async fn test_completions_without_edit_ranges(cx: &mut gpui::TestAppContext) {
6774        let mut language = Language::new(
6775            LanguageConfig {
6776                name: "TypeScript".into(),
6777                path_suffixes: vec!["ts".to_string()],
6778                ..Default::default()
6779            },
6780            Some(tree_sitter_typescript::language_typescript()),
6781        );
6782        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
6783
6784        let fs = FakeFs::new(cx.background());
6785        fs.insert_tree(
6786            "/dir",
6787            json!({
6788                "a.ts": "",
6789            }),
6790        )
6791        .await;
6792
6793        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6794        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6795        let buffer = project
6796            .update(cx, |p, cx| p.open_local_buffer("/dir/a.ts", cx))
6797            .await
6798            .unwrap();
6799
6800        let fake_server = fake_language_servers.next().await.unwrap();
6801
6802        let text = "let a = b.fqn";
6803        buffer.update(cx, |buffer, cx| buffer.set_text(text, cx));
6804        let completions = project.update(cx, |project, cx| {
6805            project.completions(&buffer, text.len(), cx)
6806        });
6807
6808        fake_server
6809            .handle_request::<lsp::request::Completion, _, _>(|_, _| async move {
6810                Ok(Some(lsp::CompletionResponse::Array(vec![
6811                    lsp::CompletionItem {
6812                        label: "fullyQualifiedName?".into(),
6813                        insert_text: Some("fullyQualifiedName".into()),
6814                        ..Default::default()
6815                    },
6816                ])))
6817            })
6818            .next()
6819            .await;
6820        let completions = completions.await.unwrap();
6821        let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
6822        assert_eq!(completions.len(), 1);
6823        assert_eq!(completions[0].new_text, "fullyQualifiedName");
6824        assert_eq!(
6825            completions[0].old_range.to_offset(&snapshot),
6826            text.len() - 3..text.len()
6827        );
6828    }
6829
6830    #[gpui::test(iterations = 10)]
6831    async fn test_apply_code_actions_with_commands(cx: &mut gpui::TestAppContext) {
6832        let mut language = Language::new(
6833            LanguageConfig {
6834                name: "TypeScript".into(),
6835                path_suffixes: vec!["ts".to_string()],
6836                ..Default::default()
6837            },
6838            None,
6839        );
6840        let mut fake_language_servers = language.set_fake_lsp_adapter(Default::default());
6841
6842        let fs = FakeFs::new(cx.background());
6843        fs.insert_tree(
6844            "/dir",
6845            json!({
6846                "a.ts": "a",
6847            }),
6848        )
6849        .await;
6850
6851        let project = Project::test(fs, ["/dir".as_ref()], cx).await;
6852        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
6853        let buffer = project
6854            .update(cx, |p, cx| p.open_local_buffer("/dir/a.ts", cx))
6855            .await
6856            .unwrap();
6857
6858        let fake_server = fake_language_servers.next().await.unwrap();
6859
6860        // Language server returns code actions that contain commands, and not edits.
6861        let actions = project.update(cx, |project, cx| project.code_actions(&buffer, 0..0, cx));
6862        fake_server
6863            .handle_request::<lsp::request::CodeActionRequest, _, _>(|_, _| async move {
6864                Ok(Some(vec![
6865                    lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
6866                        title: "The code action".into(),
6867                        command: Some(lsp::Command {
6868                            title: "The command".into(),
6869                            command: "_the/command".into(),
6870                            arguments: Some(vec![json!("the-argument")]),
6871                        }),
6872                        ..Default::default()
6873                    }),
6874                    lsp::CodeActionOrCommand::CodeAction(lsp::CodeAction {
6875                        title: "two".into(),
6876                        ..Default::default()
6877                    }),
6878                ]))
6879            })
6880            .next()
6881            .await;
6882
6883        let action = actions.await.unwrap()[0].clone();
6884        let apply = project.update(cx, |project, cx| {
6885            project.apply_code_action(buffer.clone(), action, true, cx)
6886        });
6887
6888        // Resolving the code action does not populate its edits. In absence of
6889        // edits, we must execute the given command.
6890        fake_server.handle_request::<lsp::request::CodeActionResolveRequest, _, _>(
6891            |action, _| async move { Ok(action) },
6892        );
6893
6894        // While executing the command, the language server sends the editor
6895        // a `workspaceEdit` request.
6896        fake_server
6897            .handle_request::<lsp::request::ExecuteCommand, _, _>({
6898                let fake = fake_server.clone();
6899                move |params, _| {
6900                    assert_eq!(params.command, "_the/command");
6901                    let fake = fake.clone();
6902                    async move {
6903                        fake.server
6904                            .request::<lsp::request::ApplyWorkspaceEdit>(
6905                                lsp::ApplyWorkspaceEditParams {
6906                                    label: None,
6907                                    edit: lsp::WorkspaceEdit {
6908                                        changes: Some(
6909                                            [(
6910                                                lsp::Url::from_file_path("/dir/a.ts").unwrap(),
6911                                                vec![lsp::TextEdit {
6912                                                    range: lsp::Range::new(
6913                                                        lsp::Position::new(0, 0),
6914                                                        lsp::Position::new(0, 0),
6915                                                    ),
6916                                                    new_text: "X".into(),
6917                                                }],
6918                                            )]
6919                                            .into_iter()
6920                                            .collect(),
6921                                        ),
6922                                        ..Default::default()
6923                                    },
6924                                },
6925                            )
6926                            .await
6927                            .unwrap();
6928                        Ok(Some(json!(null)))
6929                    }
6930                }
6931            })
6932            .next()
6933            .await;
6934
6935        // Applying the code action returns a project transaction containing the edits
6936        // sent by the language server in its `workspaceEdit` request.
6937        let transaction = apply.await.unwrap();
6938        assert!(transaction.0.contains_key(&buffer));
6939        buffer.update(cx, |buffer, cx| {
6940            assert_eq!(buffer.text(), "Xa");
6941            buffer.undo(cx);
6942            assert_eq!(buffer.text(), "a");
6943        });
6944    }
6945
6946    #[gpui::test]
6947    async fn test_save_file(cx: &mut gpui::TestAppContext) {
6948        let fs = FakeFs::new(cx.background());
6949        fs.insert_tree(
6950            "/dir",
6951            json!({
6952                "file1": "the old contents",
6953            }),
6954        )
6955        .await;
6956
6957        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
6958        let buffer = project
6959            .update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
6960            .await
6961            .unwrap();
6962        buffer
6963            .update(cx, |buffer, cx| {
6964                assert_eq!(buffer.text(), "the old contents");
6965                buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], cx);
6966                buffer.save(cx)
6967            })
6968            .await
6969            .unwrap();
6970
6971        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
6972        assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
6973    }
6974
6975    #[gpui::test]
6976    async fn test_save_in_single_file_worktree(cx: &mut gpui::TestAppContext) {
6977        let fs = FakeFs::new(cx.background());
6978        fs.insert_tree(
6979            "/dir",
6980            json!({
6981                "file1": "the old contents",
6982            }),
6983        )
6984        .await;
6985
6986        let project = Project::test(fs.clone(), ["/dir/file1".as_ref()], cx).await;
6987        let buffer = project
6988            .update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
6989            .await
6990            .unwrap();
6991        buffer
6992            .update(cx, |buffer, cx| {
6993                buffer.edit([(0..0, "a line of text.\n".repeat(10 * 1024))], cx);
6994                buffer.save(cx)
6995            })
6996            .await
6997            .unwrap();
6998
6999        let new_text = fs.load(Path::new("/dir/file1")).await.unwrap();
7000        assert_eq!(new_text, buffer.read_with(cx, |buffer, _| buffer.text()));
7001    }
7002
7003    #[gpui::test]
7004    async fn test_save_as(cx: &mut gpui::TestAppContext) {
7005        let fs = FakeFs::new(cx.background());
7006        fs.insert_tree("/dir", json!({})).await;
7007
7008        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7009        let buffer = project.update(cx, |project, cx| {
7010            project.create_buffer("", None, cx).unwrap()
7011        });
7012        buffer.update(cx, |buffer, cx| {
7013            buffer.edit([(0..0, "abc")], cx);
7014            assert!(buffer.is_dirty());
7015            assert!(!buffer.has_conflict());
7016        });
7017        project
7018            .update(cx, |project, cx| {
7019                project.save_buffer_as(buffer.clone(), "/dir/file1".into(), cx)
7020            })
7021            .await
7022            .unwrap();
7023        assert_eq!(fs.load(Path::new("/dir/file1")).await.unwrap(), "abc");
7024        buffer.read_with(cx, |buffer, cx| {
7025            assert_eq!(buffer.file().unwrap().full_path(cx), Path::new("dir/file1"));
7026            assert!(!buffer.is_dirty());
7027            assert!(!buffer.has_conflict());
7028        });
7029
7030        let opened_buffer = project
7031            .update(cx, |project, cx| {
7032                project.open_local_buffer("/dir/file1", cx)
7033            })
7034            .await
7035            .unwrap();
7036        assert_eq!(opened_buffer, buffer);
7037    }
7038
7039    #[gpui::test(retries = 5)]
7040    async fn test_rescan_and_remote_updates(cx: &mut gpui::TestAppContext) {
7041        let dir = temp_tree(json!({
7042            "a": {
7043                "file1": "",
7044                "file2": "",
7045                "file3": "",
7046            },
7047            "b": {
7048                "c": {
7049                    "file4": "",
7050                    "file5": "",
7051                }
7052            }
7053        }));
7054
7055        let project = Project::test(Arc::new(RealFs), [dir.path()], cx).await;
7056        let rpc = project.read_with(cx, |p, _| p.client.clone());
7057
7058        let buffer_for_path = |path: &'static str, cx: &mut gpui::TestAppContext| {
7059            let buffer = project.update(cx, |p, cx| p.open_local_buffer(dir.path().join(path), cx));
7060            async move { buffer.await.unwrap() }
7061        };
7062        let id_for_path = |path: &'static str, cx: &gpui::TestAppContext| {
7063            project.read_with(cx, |project, cx| {
7064                let tree = project.worktrees(cx).next().unwrap();
7065                tree.read(cx)
7066                    .entry_for_path(path)
7067                    .expect(&format!("no entry for path {}", path))
7068                    .id
7069            })
7070        };
7071
7072        let buffer2 = buffer_for_path("a/file2", cx).await;
7073        let buffer3 = buffer_for_path("a/file3", cx).await;
7074        let buffer4 = buffer_for_path("b/c/file4", cx).await;
7075        let buffer5 = buffer_for_path("b/c/file5", cx).await;
7076
7077        let file2_id = id_for_path("a/file2", &cx);
7078        let file3_id = id_for_path("a/file3", &cx);
7079        let file4_id = id_for_path("b/c/file4", &cx);
7080
7081        // Create a remote copy of this worktree.
7082        let tree = project.read_with(cx, |project, cx| project.worktrees(cx).next().unwrap());
7083        let initial_snapshot = tree.read_with(cx, |tree, _| tree.as_local().unwrap().snapshot());
7084        let (remote, load_task) = cx.update(|cx| {
7085            Worktree::remote(
7086                1,
7087                1,
7088                initial_snapshot.to_proto(&Default::default(), true),
7089                rpc.clone(),
7090                cx,
7091            )
7092        });
7093        // tree
7094        load_task.await;
7095
7096        cx.read(|cx| {
7097            assert!(!buffer2.read(cx).is_dirty());
7098            assert!(!buffer3.read(cx).is_dirty());
7099            assert!(!buffer4.read(cx).is_dirty());
7100            assert!(!buffer5.read(cx).is_dirty());
7101        });
7102
7103        // Rename and delete files and directories.
7104        tree.flush_fs_events(&cx).await;
7105        std::fs::rename(dir.path().join("a/file3"), dir.path().join("b/c/file3")).unwrap();
7106        std::fs::remove_file(dir.path().join("b/c/file5")).unwrap();
7107        std::fs::rename(dir.path().join("b/c"), dir.path().join("d")).unwrap();
7108        std::fs::rename(dir.path().join("a/file2"), dir.path().join("a/file2.new")).unwrap();
7109        tree.flush_fs_events(&cx).await;
7110
7111        let expected_paths = vec![
7112            "a",
7113            "a/file1",
7114            "a/file2.new",
7115            "b",
7116            "d",
7117            "d/file3",
7118            "d/file4",
7119        ];
7120
7121        cx.read(|app| {
7122            assert_eq!(
7123                tree.read(app)
7124                    .paths()
7125                    .map(|p| p.to_str().unwrap())
7126                    .collect::<Vec<_>>(),
7127                expected_paths
7128            );
7129
7130            assert_eq!(id_for_path("a/file2.new", &cx), file2_id);
7131            assert_eq!(id_for_path("d/file3", &cx), file3_id);
7132            assert_eq!(id_for_path("d/file4", &cx), file4_id);
7133
7134            assert_eq!(
7135                buffer2.read(app).file().unwrap().path().as_ref(),
7136                Path::new("a/file2.new")
7137            );
7138            assert_eq!(
7139                buffer3.read(app).file().unwrap().path().as_ref(),
7140                Path::new("d/file3")
7141            );
7142            assert_eq!(
7143                buffer4.read(app).file().unwrap().path().as_ref(),
7144                Path::new("d/file4")
7145            );
7146            assert_eq!(
7147                buffer5.read(app).file().unwrap().path().as_ref(),
7148                Path::new("b/c/file5")
7149            );
7150
7151            assert!(!buffer2.read(app).file().unwrap().is_deleted());
7152            assert!(!buffer3.read(app).file().unwrap().is_deleted());
7153            assert!(!buffer4.read(app).file().unwrap().is_deleted());
7154            assert!(buffer5.read(app).file().unwrap().is_deleted());
7155        });
7156
7157        // Update the remote worktree. Check that it becomes consistent with the
7158        // local worktree.
7159        remote.update(cx, |remote, cx| {
7160            let update_message = tree.read(cx).as_local().unwrap().snapshot().build_update(
7161                &initial_snapshot,
7162                1,
7163                1,
7164                true,
7165            );
7166            remote
7167                .as_remote_mut()
7168                .unwrap()
7169                .snapshot
7170                .apply_remote_update(update_message)
7171                .unwrap();
7172
7173            assert_eq!(
7174                remote
7175                    .paths()
7176                    .map(|p| p.to_str().unwrap())
7177                    .collect::<Vec<_>>(),
7178                expected_paths
7179            );
7180        });
7181    }
7182
7183    #[gpui::test]
7184    async fn test_buffer_deduping(cx: &mut gpui::TestAppContext) {
7185        let fs = FakeFs::new(cx.background());
7186        fs.insert_tree(
7187            "/dir",
7188            json!({
7189                "a.txt": "a-contents",
7190                "b.txt": "b-contents",
7191            }),
7192        )
7193        .await;
7194
7195        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7196
7197        // Spawn multiple tasks to open paths, repeating some paths.
7198        let (buffer_a_1, buffer_b, buffer_a_2) = project.update(cx, |p, cx| {
7199            (
7200                p.open_local_buffer("/dir/a.txt", cx),
7201                p.open_local_buffer("/dir/b.txt", cx),
7202                p.open_local_buffer("/dir/a.txt", cx),
7203            )
7204        });
7205
7206        let buffer_a_1 = buffer_a_1.await.unwrap();
7207        let buffer_a_2 = buffer_a_2.await.unwrap();
7208        let buffer_b = buffer_b.await.unwrap();
7209        assert_eq!(buffer_a_1.read_with(cx, |b, _| b.text()), "a-contents");
7210        assert_eq!(buffer_b.read_with(cx, |b, _| b.text()), "b-contents");
7211
7212        // There is only one buffer per path.
7213        let buffer_a_id = buffer_a_1.id();
7214        assert_eq!(buffer_a_2.id(), buffer_a_id);
7215
7216        // Open the same path again while it is still open.
7217        drop(buffer_a_1);
7218        let buffer_a_3 = project
7219            .update(cx, |p, cx| p.open_local_buffer("/dir/a.txt", cx))
7220            .await
7221            .unwrap();
7222
7223        // There's still only one buffer per path.
7224        assert_eq!(buffer_a_3.id(), buffer_a_id);
7225    }
7226
7227    #[gpui::test]
7228    async fn test_buffer_is_dirty(cx: &mut gpui::TestAppContext) {
7229        let fs = FakeFs::new(cx.background());
7230        fs.insert_tree(
7231            "/dir",
7232            json!({
7233                "file1": "abc",
7234                "file2": "def",
7235                "file3": "ghi",
7236            }),
7237        )
7238        .await;
7239
7240        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7241
7242        let buffer1 = project
7243            .update(cx, |p, cx| p.open_local_buffer("/dir/file1", cx))
7244            .await
7245            .unwrap();
7246        let events = Rc::new(RefCell::new(Vec::new()));
7247
7248        // initially, the buffer isn't dirty.
7249        buffer1.update(cx, |buffer, cx| {
7250            cx.subscribe(&buffer1, {
7251                let events = events.clone();
7252                move |_, _, event, _| match event {
7253                    BufferEvent::Operation(_) => {}
7254                    _ => events.borrow_mut().push(event.clone()),
7255                }
7256            })
7257            .detach();
7258
7259            assert!(!buffer.is_dirty());
7260            assert!(events.borrow().is_empty());
7261
7262            buffer.edit([(1..2, "")], cx);
7263        });
7264
7265        // after the first edit, the buffer is dirty, and emits a dirtied event.
7266        buffer1.update(cx, |buffer, cx| {
7267            assert!(buffer.text() == "ac");
7268            assert!(buffer.is_dirty());
7269            assert_eq!(
7270                *events.borrow(),
7271                &[language::Event::Edited, language::Event::Dirtied]
7272            );
7273            events.borrow_mut().clear();
7274            buffer.did_save(buffer.version(), buffer.file().unwrap().mtime(), None, cx);
7275        });
7276
7277        // after saving, the buffer is not dirty, and emits a saved event.
7278        buffer1.update(cx, |buffer, cx| {
7279            assert!(!buffer.is_dirty());
7280            assert_eq!(*events.borrow(), &[language::Event::Saved]);
7281            events.borrow_mut().clear();
7282
7283            buffer.edit([(1..1, "B")], cx);
7284            buffer.edit([(2..2, "D")], cx);
7285        });
7286
7287        // after editing again, the buffer is dirty, and emits another dirty event.
7288        buffer1.update(cx, |buffer, cx| {
7289            assert!(buffer.text() == "aBDc");
7290            assert!(buffer.is_dirty());
7291            assert_eq!(
7292                *events.borrow(),
7293                &[
7294                    language::Event::Edited,
7295                    language::Event::Dirtied,
7296                    language::Event::Edited,
7297                ],
7298            );
7299            events.borrow_mut().clear();
7300
7301            // TODO - currently, after restoring the buffer to its
7302            // previously-saved state, the is still considered dirty.
7303            buffer.edit([(1..3, "")], cx);
7304            assert!(buffer.text() == "ac");
7305            assert!(buffer.is_dirty());
7306        });
7307
7308        assert_eq!(*events.borrow(), &[language::Event::Edited]);
7309
7310        // When a file is deleted, the buffer is considered dirty.
7311        let events = Rc::new(RefCell::new(Vec::new()));
7312        let buffer2 = project
7313            .update(cx, |p, cx| p.open_local_buffer("/dir/file2", cx))
7314            .await
7315            .unwrap();
7316        buffer2.update(cx, |_, cx| {
7317            cx.subscribe(&buffer2, {
7318                let events = events.clone();
7319                move |_, _, event, _| events.borrow_mut().push(event.clone())
7320            })
7321            .detach();
7322        });
7323
7324        fs.remove_file("/dir/file2".as_ref(), Default::default())
7325            .await
7326            .unwrap();
7327        buffer2.condition(&cx, |b, _| b.is_dirty()).await;
7328        assert_eq!(
7329            *events.borrow(),
7330            &[language::Event::Dirtied, language::Event::FileHandleChanged]
7331        );
7332
7333        // When a file is already dirty when deleted, we don't emit a Dirtied event.
7334        let events = Rc::new(RefCell::new(Vec::new()));
7335        let buffer3 = project
7336            .update(cx, |p, cx| p.open_local_buffer("/dir/file3", cx))
7337            .await
7338            .unwrap();
7339        buffer3.update(cx, |_, cx| {
7340            cx.subscribe(&buffer3, {
7341                let events = events.clone();
7342                move |_, _, event, _| events.borrow_mut().push(event.clone())
7343            })
7344            .detach();
7345        });
7346
7347        buffer3.update(cx, |buffer, cx| {
7348            buffer.edit([(0..0, "x")], cx);
7349        });
7350        events.borrow_mut().clear();
7351        fs.remove_file("/dir/file3".as_ref(), Default::default())
7352            .await
7353            .unwrap();
7354        buffer3
7355            .condition(&cx, |_, _| !events.borrow().is_empty())
7356            .await;
7357        assert_eq!(*events.borrow(), &[language::Event::FileHandleChanged]);
7358        cx.read(|cx| assert!(buffer3.read(cx).is_dirty()));
7359    }
7360
7361    #[gpui::test]
7362    async fn test_buffer_file_changes_on_disk(cx: &mut gpui::TestAppContext) {
7363        let initial_contents = "aaa\nbbbbb\nc\n";
7364        let fs = FakeFs::new(cx.background());
7365        fs.insert_tree(
7366            "/dir",
7367            json!({
7368                "the-file": initial_contents,
7369            }),
7370        )
7371        .await;
7372        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7373        let buffer = project
7374            .update(cx, |p, cx| p.open_local_buffer("/dir/the-file", cx))
7375            .await
7376            .unwrap();
7377
7378        let anchors = (0..3)
7379            .map(|row| buffer.read_with(cx, |b, _| b.anchor_before(Point::new(row, 1))))
7380            .collect::<Vec<_>>();
7381
7382        // Change the file on disk, adding two new lines of text, and removing
7383        // one line.
7384        buffer.read_with(cx, |buffer, _| {
7385            assert!(!buffer.is_dirty());
7386            assert!(!buffer.has_conflict());
7387        });
7388        let new_contents = "AAAA\naaa\nBB\nbbbbb\n";
7389        fs.save("/dir/the-file".as_ref(), &new_contents.into())
7390            .await
7391            .unwrap();
7392
7393        // Because the buffer was not modified, it is reloaded from disk. Its
7394        // contents are edited according to the diff between the old and new
7395        // file contents.
7396        buffer
7397            .condition(&cx, |buffer, _| buffer.text() == new_contents)
7398            .await;
7399
7400        buffer.update(cx, |buffer, _| {
7401            assert_eq!(buffer.text(), new_contents);
7402            assert!(!buffer.is_dirty());
7403            assert!(!buffer.has_conflict());
7404
7405            let anchor_positions = anchors
7406                .iter()
7407                .map(|anchor| anchor.to_point(&*buffer))
7408                .collect::<Vec<_>>();
7409            assert_eq!(
7410                anchor_positions,
7411                [Point::new(1, 1), Point::new(3, 1), Point::new(4, 0)]
7412            );
7413        });
7414
7415        // Modify the buffer
7416        buffer.update(cx, |buffer, cx| {
7417            buffer.edit([(0..0, " ")], cx);
7418            assert!(buffer.is_dirty());
7419            assert!(!buffer.has_conflict());
7420        });
7421
7422        // Change the file on disk again, adding blank lines to the beginning.
7423        fs.save(
7424            "/dir/the-file".as_ref(),
7425            &"\n\n\nAAAA\naaa\nBB\nbbbbb\n".into(),
7426        )
7427        .await
7428        .unwrap();
7429
7430        // Because the buffer is modified, it doesn't reload from disk, but is
7431        // marked as having a conflict.
7432        buffer
7433            .condition(&cx, |buffer, _| buffer.has_conflict())
7434            .await;
7435    }
7436
7437    #[gpui::test]
7438    async fn test_grouped_diagnostics(cx: &mut gpui::TestAppContext) {
7439        cx.foreground().forbid_parking();
7440
7441        let fs = FakeFs::new(cx.background());
7442        fs.insert_tree(
7443            "/the-dir",
7444            json!({
7445                "a.rs": "
7446                    fn foo(mut v: Vec<usize>) {
7447                        for x in &v {
7448                            v.push(1);
7449                        }
7450                    }
7451                "
7452                .unindent(),
7453            }),
7454        )
7455        .await;
7456
7457        let project = Project::test(fs.clone(), ["/the-dir".as_ref()], cx).await;
7458        let buffer = project
7459            .update(cx, |p, cx| p.open_local_buffer("/the-dir/a.rs", cx))
7460            .await
7461            .unwrap();
7462
7463        let buffer_uri = Url::from_file_path("/the-dir/a.rs").unwrap();
7464        let message = lsp::PublishDiagnosticsParams {
7465            uri: buffer_uri.clone(),
7466            diagnostics: vec![
7467                lsp::Diagnostic {
7468                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
7469                    severity: Some(DiagnosticSeverity::WARNING),
7470                    message: "error 1".to_string(),
7471                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
7472                        location: lsp::Location {
7473                            uri: buffer_uri.clone(),
7474                            range: lsp::Range::new(
7475                                lsp::Position::new(1, 8),
7476                                lsp::Position::new(1, 9),
7477                            ),
7478                        },
7479                        message: "error 1 hint 1".to_string(),
7480                    }]),
7481                    ..Default::default()
7482                },
7483                lsp::Diagnostic {
7484                    range: lsp::Range::new(lsp::Position::new(1, 8), lsp::Position::new(1, 9)),
7485                    severity: Some(DiagnosticSeverity::HINT),
7486                    message: "error 1 hint 1".to_string(),
7487                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
7488                        location: lsp::Location {
7489                            uri: buffer_uri.clone(),
7490                            range: lsp::Range::new(
7491                                lsp::Position::new(1, 8),
7492                                lsp::Position::new(1, 9),
7493                            ),
7494                        },
7495                        message: "original diagnostic".to_string(),
7496                    }]),
7497                    ..Default::default()
7498                },
7499                lsp::Diagnostic {
7500                    range: lsp::Range::new(lsp::Position::new(2, 8), lsp::Position::new(2, 17)),
7501                    severity: Some(DiagnosticSeverity::ERROR),
7502                    message: "error 2".to_string(),
7503                    related_information: Some(vec![
7504                        lsp::DiagnosticRelatedInformation {
7505                            location: lsp::Location {
7506                                uri: buffer_uri.clone(),
7507                                range: lsp::Range::new(
7508                                    lsp::Position::new(1, 13),
7509                                    lsp::Position::new(1, 15),
7510                                ),
7511                            },
7512                            message: "error 2 hint 1".to_string(),
7513                        },
7514                        lsp::DiagnosticRelatedInformation {
7515                            location: lsp::Location {
7516                                uri: buffer_uri.clone(),
7517                                range: lsp::Range::new(
7518                                    lsp::Position::new(1, 13),
7519                                    lsp::Position::new(1, 15),
7520                                ),
7521                            },
7522                            message: "error 2 hint 2".to_string(),
7523                        },
7524                    ]),
7525                    ..Default::default()
7526                },
7527                lsp::Diagnostic {
7528                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
7529                    severity: Some(DiagnosticSeverity::HINT),
7530                    message: "error 2 hint 1".to_string(),
7531                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
7532                        location: lsp::Location {
7533                            uri: buffer_uri.clone(),
7534                            range: lsp::Range::new(
7535                                lsp::Position::new(2, 8),
7536                                lsp::Position::new(2, 17),
7537                            ),
7538                        },
7539                        message: "original diagnostic".to_string(),
7540                    }]),
7541                    ..Default::default()
7542                },
7543                lsp::Diagnostic {
7544                    range: lsp::Range::new(lsp::Position::new(1, 13), lsp::Position::new(1, 15)),
7545                    severity: Some(DiagnosticSeverity::HINT),
7546                    message: "error 2 hint 2".to_string(),
7547                    related_information: Some(vec![lsp::DiagnosticRelatedInformation {
7548                        location: lsp::Location {
7549                            uri: buffer_uri.clone(),
7550                            range: lsp::Range::new(
7551                                lsp::Position::new(2, 8),
7552                                lsp::Position::new(2, 17),
7553                            ),
7554                        },
7555                        message: "original diagnostic".to_string(),
7556                    }]),
7557                    ..Default::default()
7558                },
7559            ],
7560            version: None,
7561        };
7562
7563        project
7564            .update(cx, |p, cx| p.update_diagnostics(message, &[], cx))
7565            .unwrap();
7566        let buffer = buffer.read_with(cx, |buffer, _| buffer.snapshot());
7567
7568        assert_eq!(
7569            buffer
7570                .diagnostics_in_range::<_, Point>(0..buffer.len(), false)
7571                .collect::<Vec<_>>(),
7572            &[
7573                DiagnosticEntry {
7574                    range: Point::new(1, 8)..Point::new(1, 9),
7575                    diagnostic: Diagnostic {
7576                        severity: DiagnosticSeverity::WARNING,
7577                        message: "error 1".to_string(),
7578                        group_id: 0,
7579                        is_primary: true,
7580                        ..Default::default()
7581                    }
7582                },
7583                DiagnosticEntry {
7584                    range: Point::new(1, 8)..Point::new(1, 9),
7585                    diagnostic: Diagnostic {
7586                        severity: DiagnosticSeverity::HINT,
7587                        message: "error 1 hint 1".to_string(),
7588                        group_id: 0,
7589                        is_primary: false,
7590                        ..Default::default()
7591                    }
7592                },
7593                DiagnosticEntry {
7594                    range: Point::new(1, 13)..Point::new(1, 15),
7595                    diagnostic: Diagnostic {
7596                        severity: DiagnosticSeverity::HINT,
7597                        message: "error 2 hint 1".to_string(),
7598                        group_id: 1,
7599                        is_primary: false,
7600                        ..Default::default()
7601                    }
7602                },
7603                DiagnosticEntry {
7604                    range: Point::new(1, 13)..Point::new(1, 15),
7605                    diagnostic: Diagnostic {
7606                        severity: DiagnosticSeverity::HINT,
7607                        message: "error 2 hint 2".to_string(),
7608                        group_id: 1,
7609                        is_primary: false,
7610                        ..Default::default()
7611                    }
7612                },
7613                DiagnosticEntry {
7614                    range: Point::new(2, 8)..Point::new(2, 17),
7615                    diagnostic: Diagnostic {
7616                        severity: DiagnosticSeverity::ERROR,
7617                        message: "error 2".to_string(),
7618                        group_id: 1,
7619                        is_primary: true,
7620                        ..Default::default()
7621                    }
7622                }
7623            ]
7624        );
7625
7626        assert_eq!(
7627            buffer.diagnostic_group::<Point>(0).collect::<Vec<_>>(),
7628            &[
7629                DiagnosticEntry {
7630                    range: Point::new(1, 8)..Point::new(1, 9),
7631                    diagnostic: Diagnostic {
7632                        severity: DiagnosticSeverity::WARNING,
7633                        message: "error 1".to_string(),
7634                        group_id: 0,
7635                        is_primary: true,
7636                        ..Default::default()
7637                    }
7638                },
7639                DiagnosticEntry {
7640                    range: Point::new(1, 8)..Point::new(1, 9),
7641                    diagnostic: Diagnostic {
7642                        severity: DiagnosticSeverity::HINT,
7643                        message: "error 1 hint 1".to_string(),
7644                        group_id: 0,
7645                        is_primary: false,
7646                        ..Default::default()
7647                    }
7648                },
7649            ]
7650        );
7651        assert_eq!(
7652            buffer.diagnostic_group::<Point>(1).collect::<Vec<_>>(),
7653            &[
7654                DiagnosticEntry {
7655                    range: Point::new(1, 13)..Point::new(1, 15),
7656                    diagnostic: Diagnostic {
7657                        severity: DiagnosticSeverity::HINT,
7658                        message: "error 2 hint 1".to_string(),
7659                        group_id: 1,
7660                        is_primary: false,
7661                        ..Default::default()
7662                    }
7663                },
7664                DiagnosticEntry {
7665                    range: Point::new(1, 13)..Point::new(1, 15),
7666                    diagnostic: Diagnostic {
7667                        severity: DiagnosticSeverity::HINT,
7668                        message: "error 2 hint 2".to_string(),
7669                        group_id: 1,
7670                        is_primary: false,
7671                        ..Default::default()
7672                    }
7673                },
7674                DiagnosticEntry {
7675                    range: Point::new(2, 8)..Point::new(2, 17),
7676                    diagnostic: Diagnostic {
7677                        severity: DiagnosticSeverity::ERROR,
7678                        message: "error 2".to_string(),
7679                        group_id: 1,
7680                        is_primary: true,
7681                        ..Default::default()
7682                    }
7683                }
7684            ]
7685        );
7686    }
7687
7688    #[gpui::test]
7689    async fn test_rename(cx: &mut gpui::TestAppContext) {
7690        cx.foreground().forbid_parking();
7691
7692        let mut language = Language::new(
7693            LanguageConfig {
7694                name: "Rust".into(),
7695                path_suffixes: vec!["rs".to_string()],
7696                ..Default::default()
7697            },
7698            Some(tree_sitter_rust::language()),
7699        );
7700        let mut fake_servers = language.set_fake_lsp_adapter(FakeLspAdapter {
7701            capabilities: lsp::ServerCapabilities {
7702                rename_provider: Some(lsp::OneOf::Right(lsp::RenameOptions {
7703                    prepare_provider: Some(true),
7704                    work_done_progress_options: Default::default(),
7705                })),
7706                ..Default::default()
7707            },
7708            ..Default::default()
7709        });
7710
7711        let fs = FakeFs::new(cx.background());
7712        fs.insert_tree(
7713            "/dir",
7714            json!({
7715                "one.rs": "const ONE: usize = 1;",
7716                "two.rs": "const TWO: usize = one::ONE + one::ONE;"
7717            }),
7718        )
7719        .await;
7720
7721        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7722        project.update(cx, |project, _| project.languages.add(Arc::new(language)));
7723        let buffer = project
7724            .update(cx, |project, cx| {
7725                project.open_local_buffer("/dir/one.rs", cx)
7726            })
7727            .await
7728            .unwrap();
7729
7730        let fake_server = fake_servers.next().await.unwrap();
7731
7732        let response = project.update(cx, |project, cx| {
7733            project.prepare_rename(buffer.clone(), 7, cx)
7734        });
7735        fake_server
7736            .handle_request::<lsp::request::PrepareRenameRequest, _, _>(|params, _| async move {
7737                assert_eq!(params.text_document.uri.as_str(), "file:///dir/one.rs");
7738                assert_eq!(params.position, lsp::Position::new(0, 7));
7739                Ok(Some(lsp::PrepareRenameResponse::Range(lsp::Range::new(
7740                    lsp::Position::new(0, 6),
7741                    lsp::Position::new(0, 9),
7742                ))))
7743            })
7744            .next()
7745            .await
7746            .unwrap();
7747        let range = response.await.unwrap().unwrap();
7748        let range = buffer.read_with(cx, |buffer, _| range.to_offset(buffer));
7749        assert_eq!(range, 6..9);
7750
7751        let response = project.update(cx, |project, cx| {
7752            project.perform_rename(buffer.clone(), 7, "THREE".to_string(), true, cx)
7753        });
7754        fake_server
7755            .handle_request::<lsp::request::Rename, _, _>(|params, _| async move {
7756                assert_eq!(
7757                    params.text_document_position.text_document.uri.as_str(),
7758                    "file:///dir/one.rs"
7759                );
7760                assert_eq!(
7761                    params.text_document_position.position,
7762                    lsp::Position::new(0, 7)
7763                );
7764                assert_eq!(params.new_name, "THREE");
7765                Ok(Some(lsp::WorkspaceEdit {
7766                    changes: Some(
7767                        [
7768                            (
7769                                lsp::Url::from_file_path("/dir/one.rs").unwrap(),
7770                                vec![lsp::TextEdit::new(
7771                                    lsp::Range::new(
7772                                        lsp::Position::new(0, 6),
7773                                        lsp::Position::new(0, 9),
7774                                    ),
7775                                    "THREE".to_string(),
7776                                )],
7777                            ),
7778                            (
7779                                lsp::Url::from_file_path("/dir/two.rs").unwrap(),
7780                                vec![
7781                                    lsp::TextEdit::new(
7782                                        lsp::Range::new(
7783                                            lsp::Position::new(0, 24),
7784                                            lsp::Position::new(0, 27),
7785                                        ),
7786                                        "THREE".to_string(),
7787                                    ),
7788                                    lsp::TextEdit::new(
7789                                        lsp::Range::new(
7790                                            lsp::Position::new(0, 35),
7791                                            lsp::Position::new(0, 38),
7792                                        ),
7793                                        "THREE".to_string(),
7794                                    ),
7795                                ],
7796                            ),
7797                        ]
7798                        .into_iter()
7799                        .collect(),
7800                    ),
7801                    ..Default::default()
7802                }))
7803            })
7804            .next()
7805            .await
7806            .unwrap();
7807        let mut transaction = response.await.unwrap().0;
7808        assert_eq!(transaction.len(), 2);
7809        assert_eq!(
7810            transaction
7811                .remove_entry(&buffer)
7812                .unwrap()
7813                .0
7814                .read_with(cx, |buffer, _| buffer.text()),
7815            "const THREE: usize = 1;"
7816        );
7817        assert_eq!(
7818            transaction
7819                .into_keys()
7820                .next()
7821                .unwrap()
7822                .read_with(cx, |buffer, _| buffer.text()),
7823            "const TWO: usize = one::THREE + one::THREE;"
7824        );
7825    }
7826
7827    #[gpui::test]
7828    async fn test_search(cx: &mut gpui::TestAppContext) {
7829        let fs = FakeFs::new(cx.background());
7830        fs.insert_tree(
7831            "/dir",
7832            json!({
7833                "one.rs": "const ONE: usize = 1;",
7834                "two.rs": "const TWO: usize = one::ONE + one::ONE;",
7835                "three.rs": "const THREE: usize = one::ONE + two::TWO;",
7836                "four.rs": "const FOUR: usize = one::ONE + three::THREE;",
7837            }),
7838        )
7839        .await;
7840        let project = Project::test(fs.clone(), ["/dir".as_ref()], cx).await;
7841        assert_eq!(
7842            search(&project, SearchQuery::text("TWO", false, true), cx)
7843                .await
7844                .unwrap(),
7845            HashMap::from_iter([
7846                ("two.rs".to_string(), vec![6..9]),
7847                ("three.rs".to_string(), vec![37..40])
7848            ])
7849        );
7850
7851        let buffer_4 = project
7852            .update(cx, |project, cx| {
7853                project.open_local_buffer("/dir/four.rs", cx)
7854            })
7855            .await
7856            .unwrap();
7857        buffer_4.update(cx, |buffer, cx| {
7858            let text = "two::TWO";
7859            buffer.edit([(20..28, text), (31..43, text)], cx);
7860        });
7861
7862        assert_eq!(
7863            search(&project, SearchQuery::text("TWO", false, true), cx)
7864                .await
7865                .unwrap(),
7866            HashMap::from_iter([
7867                ("two.rs".to_string(), vec![6..9]),
7868                ("three.rs".to_string(), vec![37..40]),
7869                ("four.rs".to_string(), vec![25..28, 36..39])
7870            ])
7871        );
7872
7873        async fn search(
7874            project: &ModelHandle<Project>,
7875            query: SearchQuery,
7876            cx: &mut gpui::TestAppContext,
7877        ) -> Result<HashMap<String, Vec<Range<usize>>>> {
7878            let results = project
7879                .update(cx, |project, cx| project.search(query, cx))
7880                .await?;
7881
7882            Ok(results
7883                .into_iter()
7884                .map(|(buffer, ranges)| {
7885                    buffer.read_with(cx, |buffer, _| {
7886                        let path = buffer.file().unwrap().path().to_string_lossy().to_string();
7887                        let ranges = ranges
7888                            .into_iter()
7889                            .map(|range| range.to_offset(buffer))
7890                            .collect::<Vec<_>>();
7891                        (path, ranges)
7892                    })
7893                })
7894                .collect())
7895        }
7896    }
7897}