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