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