project.rs

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