project.rs

   1mod db;
   2pub mod fs;
   3mod ignore;
   4mod lsp_command;
   5pub mod search;
   6pub mod worktree;
   7
   8#[cfg(test)]
   9mod project_tests;
  10
  11use anyhow::{anyhow, Context, Result};
  12use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
  13use clock::ReplicaId;
  14use collections::{hash_map, BTreeMap, HashMap, HashSet};
  15use futures::{future::Shared, Future, FutureExt, StreamExt, TryFutureExt};
  16use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
  17use gpui::{
  18    AnyModelHandle, AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle,
  19    MutableAppContext, Task, UpgradeModelHandle, WeakModelHandle,
  20};
  21use language::{
  22    point_to_lsp,
  23    proto::{
  24        deserialize_anchor, deserialize_line_ending, deserialize_version, serialize_anchor,
  25        serialize_version,
  26    },
  27    range_from_lsp, range_to_lsp, Anchor, Bias, Buffer, CharKind, CodeAction, CodeLabel,
  28    Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Event as BufferEvent, File as _,
  29    Language, LanguageRegistry, LanguageServerName, LineEnding, LocalFile, LspAdapter,
  30    OffsetRangeExt, Operation, Patch, PointUtf16, TextBufferSnapshot, ToOffset, ToPointUtf16,
  31    Transaction,
  32};
  33use lsp::{
  34    DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
  35    MarkedString,
  36};
  37use lsp_command::*;
  38use parking_lot::Mutex;
  39use postage::stream::Stream;
  40use postage::watch;
  41use rand::prelude::*;
  42use search::SearchQuery;
  43use serde::Serialize;
  44use settings::Settings;
  45use sha2::{Digest, Sha256};
  46use similar::{ChangeTag, TextDiff};
  47use std::{
  48    cell::RefCell,
  49    cmp::{self, Ordering},
  50    convert::TryInto,
  51    ffi::OsString,
  52    hash::Hash,
  53    mem,
  54    ops::Range,
  55    os::unix::{ffi::OsStrExt, prelude::OsStringExt},
  56    path::{Component, Path, PathBuf},
  57    rc::Rc,
  58    sync::{
  59        atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
  60        Arc,
  61    },
  62    time::Instant,
  63};
  64use thiserror::Error;
  65use util::{post_inc, ResultExt, TryFutureExt as _};
  66
  67pub use db::Db;
  68pub use fs::*;
  69pub use worktree::*;
  70
  71pub trait Item: Entity {
  72    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  73}
  74
  75pub struct ProjectStore {
  76    db: Arc<Db>,
  77    projects: Vec<WeakModelHandle<Project>>,
  78}
  79
  80// Language server state is stored across 3 collections:
  81//     language_servers =>
  82//         a mapping from unique server id to LanguageServerState which can either be a task for a
  83//         server in the process of starting, or a running server with adapter and language server arcs
  84//     language_server_ids => a mapping from worktreeId and server name to the unique server id
  85//     language_server_statuses => a mapping from unique server id to the current server status
  86//
  87// Multiple worktrees can map to the same language server for example when you jump to the definition
  88// of a file in the standard library. So language_server_ids is used to look up which server is active
  89// for a given worktree and language server name
  90//
  91// When starting a language server, first the id map is checked to make sure a server isn't already available
  92// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
  93// the Starting variant of LanguageServerState is stored in the language_servers map.
  94pub struct Project {
  95    worktrees: Vec<WorktreeHandle>,
  96    active_entry: Option<ProjectEntryId>,
  97    languages: Arc<LanguageRegistry>,
  98    language_servers: HashMap<usize, LanguageServerState>,
  99    language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
 100    language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
 101    language_server_settings: Arc<Mutex<serde_json::Value>>,
 102    last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
 103    next_language_server_id: usize,
 104    client: Arc<client::Client>,
 105    next_entry_id: Arc<AtomicUsize>,
 106    next_diagnostic_group_id: usize,
 107    user_store: ModelHandle<UserStore>,
 108    project_store: ModelHandle<ProjectStore>,
 109    fs: Arc<dyn Fs>,
 110    client_state: ProjectClientState,
 111    collaborators: HashMap<PeerId, Collaborator>,
 112    client_subscriptions: Vec<client::Subscription>,
 113    _subscriptions: Vec<gpui::Subscription>,
 114    opened_buffer: (Rc<RefCell<watch::Sender<()>>>, watch::Receiver<()>),
 115    shared_buffers: HashMap<PeerId, HashSet<u64>>,
 116    loading_buffers: HashMap<
 117        ProjectPath,
 118        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 119    >,
 120    loading_local_worktrees:
 121        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 122    opened_buffers: HashMap<u64, OpenBuffer>,
 123    buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
 124    nonce: u128,
 125    initialized_persistent_state: bool,
 126}
 127
 128#[derive(Error, Debug)]
 129pub enum JoinProjectError {
 130    #[error("host declined join request")]
 131    HostDeclined,
 132    #[error("host closed the project")]
 133    HostClosedProject,
 134    #[error("host went offline")]
 135    HostWentOffline,
 136    #[error("{0}")]
 137    Other(#[from] anyhow::Error),
 138}
 139
 140enum OpenBuffer {
 141    Strong(ModelHandle<Buffer>),
 142    Weak(WeakModelHandle<Buffer>),
 143    Loading(Vec<Operation>),
 144}
 145
 146enum WorktreeHandle {
 147    Strong(ModelHandle<Worktree>),
 148    Weak(WeakModelHandle<Worktree>),
 149}
 150
 151enum ProjectClientState {
 152    Local {
 153        is_shared: bool,
 154        remote_id_tx: watch::Sender<Option<u64>>,
 155        remote_id_rx: watch::Receiver<Option<u64>>,
 156        online_tx: watch::Sender<bool>,
 157        online_rx: watch::Receiver<bool>,
 158        _maintain_remote_id: Task<Option<()>>,
 159        _maintain_online_status: Task<Option<()>>,
 160    },
 161    Remote {
 162        sharing_has_stopped: bool,
 163        remote_id: u64,
 164        replica_id: ReplicaId,
 165        _detect_unshare: Task<Option<()>>,
 166    },
 167}
 168
 169#[derive(Clone, Debug)]
 170pub struct Collaborator {
 171    pub user: Arc<User>,
 172    pub peer_id: PeerId,
 173    pub replica_id: ReplicaId,
 174}
 175
 176#[derive(Clone, Debug, PartialEq, Eq)]
 177pub enum Event {
 178    ActiveEntryChanged(Option<ProjectEntryId>),
 179    WorktreeAdded,
 180    WorktreeRemoved(WorktreeId),
 181    DiskBasedDiagnosticsStarted {
 182        language_server_id: usize,
 183    },
 184    DiskBasedDiagnosticsFinished {
 185        language_server_id: usize,
 186    },
 187    DiagnosticsUpdated {
 188        path: ProjectPath,
 189        language_server_id: usize,
 190    },
 191    RemoteIdChanged(Option<u64>),
 192    CollaboratorLeft(PeerId),
 193    ContactRequestedJoin(Arc<User>),
 194    ContactCancelledJoinRequest(Arc<User>),
 195}
 196
 197pub enum LanguageServerState {
 198    Starting(Task<Option<Arc<LanguageServer>>>),
 199    Running {
 200        adapter: Arc<dyn LspAdapter>,
 201        server: Arc<LanguageServer>,
 202    },
 203}
 204
 205#[derive(Serialize)]
 206pub struct LanguageServerStatus {
 207    pub name: String,
 208    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 209    pub has_pending_diagnostic_updates: bool,
 210    progress_tokens: HashSet<String>,
 211}
 212
 213#[derive(Clone, Debug, Serialize)]
 214pub struct LanguageServerProgress {
 215    pub message: Option<String>,
 216    pub percentage: Option<usize>,
 217    #[serde(skip_serializing)]
 218    pub last_update_at: Instant,
 219}
 220
 221#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 222pub struct ProjectPath {
 223    pub worktree_id: WorktreeId,
 224    pub path: Arc<Path>,
 225}
 226
 227#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 228pub struct DiagnosticSummary {
 229    pub language_server_id: usize,
 230    pub error_count: usize,
 231    pub warning_count: usize,
 232}
 233
 234#[derive(Debug, Clone)]
 235pub struct Location {
 236    pub buffer: ModelHandle<Buffer>,
 237    pub range: Range<language::Anchor>,
 238}
 239
 240#[derive(Debug, Clone)]
 241pub struct LocationLink {
 242    pub origin: Option<Location>,
 243    pub target: Location,
 244}
 245
 246#[derive(Debug)]
 247pub struct DocumentHighlight {
 248    pub range: Range<language::Anchor>,
 249    pub kind: DocumentHighlightKind,
 250}
 251
 252#[derive(Clone, Debug)]
 253pub struct Symbol {
 254    pub source_worktree_id: WorktreeId,
 255    pub worktree_id: WorktreeId,
 256    pub language_server_name: LanguageServerName,
 257    pub path: PathBuf,
 258    pub label: CodeLabel,
 259    pub name: String,
 260    pub kind: lsp::SymbolKind,
 261    pub range: Range<PointUtf16>,
 262    pub signature: [u8; 32],
 263}
 264
 265#[derive(Clone, Debug, PartialEq)]
 266pub struct HoverBlock {
 267    pub text: String,
 268    pub language: Option<String>,
 269}
 270
 271impl HoverBlock {
 272    fn try_new(marked_string: MarkedString) -> Option<Self> {
 273        let result = match marked_string {
 274            MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
 275                text: value,
 276                language: Some(language),
 277            },
 278            MarkedString::String(text) => HoverBlock {
 279                text,
 280                language: None,
 281            },
 282        };
 283        if result.text.is_empty() {
 284            None
 285        } else {
 286            Some(result)
 287        }
 288    }
 289}
 290
 291#[derive(Debug)]
 292pub struct Hover {
 293    pub contents: Vec<HoverBlock>,
 294    pub range: Option<Range<language::Anchor>>,
 295}
 296
 297#[derive(Default)]
 298pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 299
 300impl DiagnosticSummary {
 301    fn new<'a, T: 'a>(
 302        language_server_id: usize,
 303        diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
 304    ) -> Self {
 305        let mut this = Self {
 306            language_server_id,
 307            error_count: 0,
 308            warning_count: 0,
 309        };
 310
 311        for entry in diagnostics {
 312            if entry.diagnostic.is_primary {
 313                match entry.diagnostic.severity {
 314                    DiagnosticSeverity::ERROR => this.error_count += 1,
 315                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 316                    _ => {}
 317                }
 318            }
 319        }
 320
 321        this
 322    }
 323
 324    pub fn is_empty(&self) -> bool {
 325        self.error_count == 0 && self.warning_count == 0
 326    }
 327
 328    pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
 329        proto::DiagnosticSummary {
 330            path: path.to_string_lossy().to_string(),
 331            language_server_id: self.language_server_id as u64,
 332            error_count: self.error_count as u32,
 333            warning_count: self.warning_count as u32,
 334        }
 335    }
 336}
 337
 338#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 339pub struct ProjectEntryId(usize);
 340
 341impl ProjectEntryId {
 342    pub const MAX: Self = Self(usize::MAX);
 343
 344    pub fn new(counter: &AtomicUsize) -> Self {
 345        Self(counter.fetch_add(1, SeqCst))
 346    }
 347
 348    pub fn from_proto(id: u64) -> Self {
 349        Self(id as usize)
 350    }
 351
 352    pub fn to_proto(&self) -> u64 {
 353        self.0 as u64
 354    }
 355
 356    pub fn to_usize(&self) -> usize {
 357        self.0
 358    }
 359}
 360
 361impl Project {
 362    pub fn init(client: &Arc<Client>) {
 363        client.add_model_message_handler(Self::handle_request_join_project);
 364        client.add_model_message_handler(Self::handle_add_collaborator);
 365        client.add_model_message_handler(Self::handle_buffer_reloaded);
 366        client.add_model_message_handler(Self::handle_buffer_saved);
 367        client.add_model_message_handler(Self::handle_start_language_server);
 368        client.add_model_message_handler(Self::handle_update_language_server);
 369        client.add_model_message_handler(Self::handle_remove_collaborator);
 370        client.add_model_message_handler(Self::handle_join_project_request_cancelled);
 371        client.add_model_message_handler(Self::handle_update_project);
 372        client.add_model_message_handler(Self::handle_unregister_project);
 373        client.add_model_message_handler(Self::handle_project_unshared);
 374        client.add_model_message_handler(Self::handle_update_buffer_file);
 375        client.add_model_message_handler(Self::handle_update_buffer);
 376        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 377        client.add_model_message_handler(Self::handle_update_worktree);
 378        client.add_model_request_handler(Self::handle_create_project_entry);
 379        client.add_model_request_handler(Self::handle_rename_project_entry);
 380        client.add_model_request_handler(Self::handle_copy_project_entry);
 381        client.add_model_request_handler(Self::handle_delete_project_entry);
 382        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 383        client.add_model_request_handler(Self::handle_apply_code_action);
 384        client.add_model_request_handler(Self::handle_reload_buffers);
 385        client.add_model_request_handler(Self::handle_format_buffers);
 386        client.add_model_request_handler(Self::handle_get_code_actions);
 387        client.add_model_request_handler(Self::handle_get_completions);
 388        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 389        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 390        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 391        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 392        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 393        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 394        client.add_model_request_handler(Self::handle_search_project);
 395        client.add_model_request_handler(Self::handle_get_project_symbols);
 396        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 397        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 398        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 399        client.add_model_request_handler(Self::handle_save_buffer);
 400    }
 401
 402    pub fn local(
 403        online: bool,
 404        client: Arc<Client>,
 405        user_store: ModelHandle<UserStore>,
 406        project_store: ModelHandle<ProjectStore>,
 407        languages: Arc<LanguageRegistry>,
 408        fs: Arc<dyn Fs>,
 409        cx: &mut MutableAppContext,
 410    ) -> ModelHandle<Self> {
 411        cx.add_model(|cx: &mut ModelContext<Self>| {
 412            let (remote_id_tx, remote_id_rx) = watch::channel();
 413            let _maintain_remote_id = cx.spawn_weak({
 414                let mut status_rx = client.clone().status();
 415                move |this, mut cx| async move {
 416                    while let Some(status) = status_rx.recv().await {
 417                        let this = this.upgrade(&cx)?;
 418                        if status.is_connected() {
 419                            this.update(&mut cx, |this, cx| this.register(cx))
 420                                .await
 421                                .log_err()?;
 422                        } else {
 423                            this.update(&mut cx, |this, cx| this.unregister(cx))
 424                                .await
 425                                .log_err();
 426                        }
 427                    }
 428                    None
 429                }
 430            });
 431
 432            let (online_tx, online_rx) = watch::channel_with(online);
 433            let _maintain_online_status = cx.spawn_weak({
 434                let mut online_rx = online_rx.clone();
 435                move |this, mut cx| async move {
 436                    while let Some(online) = online_rx.recv().await {
 437                        let this = this.upgrade(&cx)?;
 438                        this.update(&mut cx, |this, cx| {
 439                            if !online {
 440                                this.unshared(cx);
 441                            }
 442                            this.metadata_changed(false, cx)
 443                        });
 444                    }
 445                    None
 446                }
 447            });
 448
 449            let handle = cx.weak_handle();
 450            project_store.update(cx, |store, cx| store.add_project(handle, cx));
 451
 452            let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
 453            Self {
 454                worktrees: Default::default(),
 455                collaborators: Default::default(),
 456                opened_buffers: Default::default(),
 457                shared_buffers: Default::default(),
 458                loading_buffers: Default::default(),
 459                loading_local_worktrees: Default::default(),
 460                buffer_snapshots: Default::default(),
 461                client_state: ProjectClientState::Local {
 462                    is_shared: false,
 463                    remote_id_tx,
 464                    remote_id_rx,
 465                    online_tx,
 466                    online_rx,
 467                    _maintain_remote_id,
 468                    _maintain_online_status,
 469                },
 470                opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
 471                client_subscriptions: Vec::new(),
 472                _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
 473                active_entry: None,
 474                languages,
 475                client,
 476                user_store,
 477                project_store,
 478                fs,
 479                next_entry_id: Default::default(),
 480                next_diagnostic_group_id: Default::default(),
 481                language_servers: Default::default(),
 482                language_server_ids: Default::default(),
 483                language_server_statuses: Default::default(),
 484                last_workspace_edits_by_language_server: Default::default(),
 485                language_server_settings: Default::default(),
 486                next_language_server_id: 0,
 487                nonce: StdRng::from_entropy().gen(),
 488                initialized_persistent_state: false,
 489            }
 490        })
 491    }
 492
 493    pub async fn remote(
 494        remote_id: u64,
 495        client: Arc<Client>,
 496        user_store: ModelHandle<UserStore>,
 497        project_store: ModelHandle<ProjectStore>,
 498        languages: Arc<LanguageRegistry>,
 499        fs: Arc<dyn Fs>,
 500        mut cx: AsyncAppContext,
 501    ) -> Result<ModelHandle<Self>, JoinProjectError> {
 502        client.authenticate_and_connect(true, &cx).await?;
 503
 504        let response = client
 505            .request(proto::JoinProject {
 506                project_id: remote_id,
 507            })
 508            .await?;
 509
 510        let response = match response.variant.ok_or_else(|| anyhow!("missing variant"))? {
 511            proto::join_project_response::Variant::Accept(response) => response,
 512            proto::join_project_response::Variant::Decline(decline) => {
 513                match proto::join_project_response::decline::Reason::from_i32(decline.reason) {
 514                    Some(proto::join_project_response::decline::Reason::Declined) => {
 515                        Err(JoinProjectError::HostDeclined)?
 516                    }
 517                    Some(proto::join_project_response::decline::Reason::Closed) => {
 518                        Err(JoinProjectError::HostClosedProject)?
 519                    }
 520                    Some(proto::join_project_response::decline::Reason::WentOffline) => {
 521                        Err(JoinProjectError::HostWentOffline)?
 522                    }
 523                    None => Err(anyhow!("missing decline reason"))?,
 524                }
 525            }
 526        };
 527
 528        let replica_id = response.replica_id as ReplicaId;
 529
 530        let mut worktrees = Vec::new();
 531        for worktree in response.worktrees {
 532            let worktree = cx
 533                .update(|cx| Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx));
 534            worktrees.push(worktree);
 535        }
 536
 537        let (opened_buffer_tx, opened_buffer_rx) = watch::channel();
 538        let this = cx.add_model(|cx: &mut ModelContext<Self>| {
 539            let handle = cx.weak_handle();
 540            project_store.update(cx, |store, cx| store.add_project(handle, cx));
 541
 542            let mut this = Self {
 543                worktrees: Vec::new(),
 544                loading_buffers: Default::default(),
 545                opened_buffer: (Rc::new(RefCell::new(opened_buffer_tx)), opened_buffer_rx),
 546                shared_buffers: Default::default(),
 547                loading_local_worktrees: Default::default(),
 548                active_entry: None,
 549                collaborators: Default::default(),
 550                languages,
 551                user_store: user_store.clone(),
 552                project_store,
 553                fs,
 554                next_entry_id: Default::default(),
 555                next_diagnostic_group_id: Default::default(),
 556                client_subscriptions: vec![client.add_model_for_remote_entity(remote_id, cx)],
 557                _subscriptions: Default::default(),
 558                client: client.clone(),
 559                client_state: ProjectClientState::Remote {
 560                    sharing_has_stopped: false,
 561                    remote_id,
 562                    replica_id,
 563                    _detect_unshare: cx.spawn_weak(move |this, mut cx| {
 564                        async move {
 565                            let mut status = client.status();
 566                            let is_connected =
 567                                status.next().await.map_or(false, |s| s.is_connected());
 568                            // Even if we're initially connected, any future change of the status means we momentarily disconnected.
 569                            if !is_connected || status.next().await.is_some() {
 570                                if let Some(this) = this.upgrade(&cx) {
 571                                    this.update(&mut cx, |this, cx| this.removed_from_project(cx))
 572                                }
 573                            }
 574                            Ok(())
 575                        }
 576                        .log_err()
 577                    }),
 578                },
 579                language_servers: Default::default(),
 580                language_server_ids: Default::default(),
 581                language_server_settings: Default::default(),
 582                language_server_statuses: response
 583                    .language_servers
 584                    .into_iter()
 585                    .map(|server| {
 586                        (
 587                            server.id as usize,
 588                            LanguageServerStatus {
 589                                name: server.name,
 590                                pending_work: Default::default(),
 591                                has_pending_diagnostic_updates: false,
 592                                progress_tokens: Default::default(),
 593                            },
 594                        )
 595                    })
 596                    .collect(),
 597                last_workspace_edits_by_language_server: Default::default(),
 598                next_language_server_id: 0,
 599                opened_buffers: Default::default(),
 600                buffer_snapshots: Default::default(),
 601                nonce: StdRng::from_entropy().gen(),
 602                initialized_persistent_state: false,
 603            };
 604            for worktree in worktrees {
 605                this.add_worktree(&worktree, cx);
 606            }
 607            this
 608        });
 609
 610        let user_ids = response
 611            .collaborators
 612            .iter()
 613            .map(|peer| peer.user_id)
 614            .collect();
 615        user_store
 616            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 617            .await?;
 618        let mut collaborators = HashMap::default();
 619        for message in response.collaborators {
 620            let collaborator = Collaborator::from_proto(message, &user_store, &mut cx).await?;
 621            collaborators.insert(collaborator.peer_id, collaborator);
 622        }
 623
 624        this.update(&mut cx, |this, _| {
 625            this.collaborators = collaborators;
 626        });
 627
 628        Ok(this)
 629    }
 630
 631    #[cfg(any(test, feature = "test-support"))]
 632    pub async fn test(
 633        fs: Arc<dyn Fs>,
 634        root_paths: impl IntoIterator<Item = &Path>,
 635        cx: &mut gpui::TestAppContext,
 636    ) -> ModelHandle<Project> {
 637        if !cx.read(|cx| cx.has_global::<Settings>()) {
 638            cx.update(|cx| cx.set_global(Settings::test(cx)));
 639        }
 640
 641        let languages = Arc::new(LanguageRegistry::test());
 642        let http_client = client::test::FakeHttpClient::with_404_response();
 643        let client = client::Client::new(http_client.clone());
 644        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 645        let project_store = cx.add_model(|_| ProjectStore::new(Db::open_fake()));
 646        let project = cx.update(|cx| {
 647            Project::local(true, client, user_store, project_store, languages, fs, cx)
 648        });
 649        for path in root_paths {
 650            let (tree, _) = project
 651                .update(cx, |project, cx| {
 652                    project.find_or_create_local_worktree(path, true, cx)
 653                })
 654                .await
 655                .unwrap();
 656            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 657                .await;
 658        }
 659        project
 660    }
 661
 662    pub fn restore_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 663        if self.is_remote() {
 664            return Task::ready(Ok(()));
 665        }
 666
 667        let db = self.project_store.read(cx).db.clone();
 668        let keys = self.db_keys_for_online_state(cx);
 669        let online_by_default = cx.global::<Settings>().projects_online_by_default;
 670        let read_online = cx.background().spawn(async move {
 671            let values = db.read(keys)?;
 672            anyhow::Ok(
 673                values
 674                    .into_iter()
 675                    .all(|e| e.map_or(online_by_default, |e| e == [true as u8])),
 676            )
 677        });
 678        cx.spawn(|this, mut cx| async move {
 679            let online = read_online.await.log_err().unwrap_or(false);
 680            this.update(&mut cx, |this, cx| {
 681                this.initialized_persistent_state = true;
 682                if let ProjectClientState::Local { online_tx, .. } = &mut this.client_state {
 683                    let mut online_tx = online_tx.borrow_mut();
 684                    if *online_tx != online {
 685                        *online_tx = online;
 686                        drop(online_tx);
 687                        this.metadata_changed(false, cx);
 688                    }
 689                }
 690            });
 691            Ok(())
 692        })
 693    }
 694
 695    fn persist_state(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 696        if self.is_remote() || !self.initialized_persistent_state {
 697            return Task::ready(Ok(()));
 698        }
 699
 700        let db = self.project_store.read(cx).db.clone();
 701        let keys = self.db_keys_for_online_state(cx);
 702        let is_online = self.is_online();
 703        cx.background().spawn(async move {
 704            let value = &[is_online as u8];
 705            db.write(keys.into_iter().map(|key| (key, value)))
 706        })
 707    }
 708
 709    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 710        let settings = cx.global::<Settings>();
 711
 712        let mut language_servers_to_start = Vec::new();
 713        for buffer in self.opened_buffers.values() {
 714            if let Some(buffer) = buffer.upgrade(cx) {
 715                let buffer = buffer.read(cx);
 716                if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
 717                {
 718                    if settings.enable_language_server(Some(&language.name())) {
 719                        let worktree = file.worktree.read(cx);
 720                        language_servers_to_start.push((
 721                            worktree.id(),
 722                            worktree.as_local().unwrap().abs_path().clone(),
 723                            language.clone(),
 724                        ));
 725                    }
 726                }
 727            }
 728        }
 729
 730        let mut language_servers_to_stop = Vec::new();
 731        for language in self.languages.to_vec() {
 732            if let Some(lsp_adapter) = language.lsp_adapter() {
 733                if !settings.enable_language_server(Some(&language.name())) {
 734                    let lsp_name = lsp_adapter.name();
 735                    for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 736                        if lsp_name == *started_lsp_name {
 737                            language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 738                        }
 739                    }
 740                }
 741            }
 742        }
 743
 744        // Stop all newly-disabled language servers.
 745        for (worktree_id, adapter_name) in language_servers_to_stop {
 746            self.stop_language_server(worktree_id, adapter_name, cx)
 747                .detach();
 748        }
 749
 750        // Start all the newly-enabled language servers.
 751        for (worktree_id, worktree_path, language) in language_servers_to_start {
 752            self.start_language_server(worktree_id, worktree_path, language, cx);
 753        }
 754
 755        cx.notify();
 756    }
 757
 758    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 759        self.opened_buffers
 760            .get(&remote_id)
 761            .and_then(|buffer| buffer.upgrade(cx))
 762    }
 763
 764    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 765        &self.languages
 766    }
 767
 768    pub fn client(&self) -> Arc<Client> {
 769        self.client.clone()
 770    }
 771
 772    pub fn user_store(&self) -> ModelHandle<UserStore> {
 773        self.user_store.clone()
 774    }
 775
 776    pub fn project_store(&self) -> ModelHandle<ProjectStore> {
 777        self.project_store.clone()
 778    }
 779
 780    #[cfg(any(test, feature = "test-support"))]
 781    pub fn check_invariants(&self, cx: &AppContext) {
 782        if self.is_local() {
 783            let mut worktree_root_paths = HashMap::default();
 784            for worktree in self.worktrees(cx) {
 785                let worktree = worktree.read(cx);
 786                let abs_path = worktree.as_local().unwrap().abs_path().clone();
 787                let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
 788                assert_eq!(
 789                    prev_worktree_id,
 790                    None,
 791                    "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
 792                    abs_path,
 793                    worktree.id(),
 794                    prev_worktree_id
 795                )
 796            }
 797        } else {
 798            let replica_id = self.replica_id();
 799            for buffer in self.opened_buffers.values() {
 800                if let Some(buffer) = buffer.upgrade(cx) {
 801                    let buffer = buffer.read(cx);
 802                    assert_eq!(
 803                        buffer.deferred_ops_len(),
 804                        0,
 805                        "replica {}, buffer {} has deferred operations",
 806                        replica_id,
 807                        buffer.remote_id()
 808                    );
 809                }
 810            }
 811        }
 812    }
 813
 814    #[cfg(any(test, feature = "test-support"))]
 815    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 816        let path = path.into();
 817        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 818            self.opened_buffers.iter().any(|(_, buffer)| {
 819                if let Some(buffer) = buffer.upgrade(cx) {
 820                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 821                        if file.worktree == worktree && file.path() == &path.path {
 822                            return true;
 823                        }
 824                    }
 825                }
 826                false
 827            })
 828        } else {
 829            false
 830        }
 831    }
 832
 833    pub fn fs(&self) -> &Arc<dyn Fs> {
 834        &self.fs
 835    }
 836
 837    pub fn set_online(&mut self, online: bool, _: &mut ModelContext<Self>) {
 838        if let ProjectClientState::Local { online_tx, .. } = &mut self.client_state {
 839            let mut online_tx = online_tx.borrow_mut();
 840            if *online_tx != online {
 841                *online_tx = online;
 842            }
 843        }
 844    }
 845
 846    pub fn is_online(&self) -> bool {
 847        match &self.client_state {
 848            ProjectClientState::Local { online_rx, .. } => *online_rx.borrow(),
 849            ProjectClientState::Remote { .. } => true,
 850        }
 851    }
 852
 853    fn unregister(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 854        self.unshared(cx);
 855        if let ProjectClientState::Local { remote_id_rx, .. } = &mut self.client_state {
 856            if let Some(remote_id) = *remote_id_rx.borrow() {
 857                let request = self.client.request(proto::UnregisterProject {
 858                    project_id: remote_id,
 859                });
 860                return cx.spawn(|this, mut cx| async move {
 861                    let response = request.await;
 862
 863                    // Unregistering the project causes the server to send out a
 864                    // contact update removing this project from the host's list
 865                    // of online projects. Wait until this contact update has been
 866                    // processed before clearing out this project's remote id, so
 867                    // that there is no moment where this project appears in the
 868                    // contact metadata and *also* has no remote id.
 869                    this.update(&mut cx, |this, cx| {
 870                        this.user_store()
 871                            .update(cx, |store, _| store.contact_updates_done())
 872                    })
 873                    .await;
 874
 875                    this.update(&mut cx, |this, cx| {
 876                        if let ProjectClientState::Local { remote_id_tx, .. } =
 877                            &mut this.client_state
 878                        {
 879                            *remote_id_tx.borrow_mut() = None;
 880                        }
 881                        this.client_subscriptions.clear();
 882                        this.metadata_changed(false, cx);
 883                    });
 884                    response.map(drop)
 885                });
 886            }
 887        }
 888        Task::ready(Ok(()))
 889    }
 890
 891    fn register(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
 892        if let ProjectClientState::Local {
 893            remote_id_rx,
 894            online_rx,
 895            ..
 896        } = &self.client_state
 897        {
 898            if remote_id_rx.borrow().is_some() {
 899                return Task::ready(Ok(()));
 900            }
 901
 902            let response = self.client.request(proto::RegisterProject {
 903                online: *online_rx.borrow(),
 904            });
 905            cx.spawn(|this, mut cx| async move {
 906                let remote_id = response.await?.project_id;
 907                this.update(&mut cx, |this, cx| {
 908                    if let ProjectClientState::Local { remote_id_tx, .. } = &mut this.client_state {
 909                        *remote_id_tx.borrow_mut() = Some(remote_id);
 910                    }
 911
 912                    this.metadata_changed(false, cx);
 913                    cx.emit(Event::RemoteIdChanged(Some(remote_id)));
 914                    this.client_subscriptions
 915                        .push(this.client.add_model_for_remote_entity(remote_id, cx));
 916                    Ok(())
 917                })
 918            })
 919        } else {
 920            Task::ready(Err(anyhow!("can't register a remote project")))
 921        }
 922    }
 923
 924    pub fn remote_id(&self) -> Option<u64> {
 925        match &self.client_state {
 926            ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
 927            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 928        }
 929    }
 930
 931    pub fn next_remote_id(&self) -> impl Future<Output = u64> {
 932        let mut id = None;
 933        let mut watch = None;
 934        match &self.client_state {
 935            ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
 936            ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
 937        }
 938
 939        async move {
 940            if let Some(id) = id {
 941                return id;
 942            }
 943            let mut watch = watch.unwrap();
 944            loop {
 945                let id = *watch.borrow();
 946                if let Some(id) = id {
 947                    return id;
 948                }
 949                watch.next().await;
 950            }
 951        }
 952    }
 953
 954    pub fn shared_remote_id(&self) -> Option<u64> {
 955        match &self.client_state {
 956            ProjectClientState::Local {
 957                remote_id_rx,
 958                is_shared,
 959                ..
 960            } => {
 961                if *is_shared {
 962                    *remote_id_rx.borrow()
 963                } else {
 964                    None
 965                }
 966            }
 967            ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 968        }
 969    }
 970
 971    pub fn replica_id(&self) -> ReplicaId {
 972        match &self.client_state {
 973            ProjectClientState::Local { .. } => 0,
 974            ProjectClientState::Remote { replica_id, .. } => *replica_id,
 975        }
 976    }
 977
 978    fn metadata_changed(&mut self, persist: bool, cx: &mut ModelContext<Self>) {
 979        if let ProjectClientState::Local {
 980            remote_id_rx,
 981            online_rx,
 982            ..
 983        } = &self.client_state
 984        {
 985            // Broadcast worktrees only if the project is online.
 986            let worktrees = if *online_rx.borrow() {
 987                self.worktrees
 988                    .iter()
 989                    .filter_map(|worktree| {
 990                        worktree
 991                            .upgrade(&cx)
 992                            .map(|worktree| worktree.read(cx).as_local().unwrap().metadata_proto())
 993                    })
 994                    .collect()
 995            } else {
 996                Default::default()
 997            };
 998            if let Some(project_id) = *remote_id_rx.borrow() {
 999                let online = *online_rx.borrow();
1000                self.client
1001                    .send(proto::UpdateProject {
1002                        project_id,
1003                        worktrees,
1004                        online,
1005                    })
1006                    .log_err();
1007
1008                if online {
1009                    let worktrees = self.visible_worktrees(cx).collect::<Vec<_>>();
1010                    let scans_complete =
1011                        futures::future::join_all(worktrees.iter().filter_map(|worktree| {
1012                            Some(worktree.read(cx).as_local()?.scan_complete())
1013                        }));
1014
1015                    let worktrees = worktrees.into_iter().map(|handle| handle.downgrade());
1016                    cx.spawn_weak(move |_, cx| async move {
1017                        scans_complete.await;
1018                        cx.read(|cx| {
1019                            for worktree in worktrees {
1020                                if let Some(worktree) = worktree
1021                                    .upgrade(cx)
1022                                    .and_then(|worktree| worktree.read(cx).as_local())
1023                                {
1024                                    worktree.send_extension_counts(project_id);
1025                                }
1026                            }
1027                        })
1028                    })
1029                    .detach();
1030                }
1031            }
1032
1033            self.project_store.update(cx, |_, cx| cx.notify());
1034            if persist {
1035                self.persist_state(cx).detach_and_log_err(cx);
1036            }
1037            cx.notify();
1038        }
1039    }
1040
1041    pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
1042        &self.collaborators
1043    }
1044
1045    pub fn worktrees<'a>(
1046        &'a self,
1047        cx: &'a AppContext,
1048    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1049        self.worktrees
1050            .iter()
1051            .filter_map(move |worktree| worktree.upgrade(cx))
1052    }
1053
1054    pub fn visible_worktrees<'a>(
1055        &'a self,
1056        cx: &'a AppContext,
1057    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1058        self.worktrees.iter().filter_map(|worktree| {
1059            worktree.upgrade(cx).and_then(|worktree| {
1060                if worktree.read(cx).is_visible() {
1061                    Some(worktree)
1062                } else {
1063                    None
1064                }
1065            })
1066        })
1067    }
1068
1069    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1070        self.visible_worktrees(cx)
1071            .map(|tree| tree.read(cx).root_name())
1072    }
1073
1074    fn db_keys_for_online_state(&self, cx: &AppContext) -> Vec<String> {
1075        self.worktrees
1076            .iter()
1077            .filter_map(|worktree| {
1078                let worktree = worktree.upgrade(&cx)?.read(cx);
1079                if worktree.is_visible() {
1080                    Some(format!(
1081                        "project-path-online:{}",
1082                        worktree.as_local().unwrap().abs_path().to_string_lossy()
1083                    ))
1084                } else {
1085                    None
1086                }
1087            })
1088            .collect::<Vec<_>>()
1089    }
1090
1091    pub fn worktree_for_id(
1092        &self,
1093        id: WorktreeId,
1094        cx: &AppContext,
1095    ) -> Option<ModelHandle<Worktree>> {
1096        self.worktrees(cx)
1097            .find(|worktree| worktree.read(cx).id() == id)
1098    }
1099
1100    pub fn worktree_for_entry(
1101        &self,
1102        entry_id: ProjectEntryId,
1103        cx: &AppContext,
1104    ) -> Option<ModelHandle<Worktree>> {
1105        self.worktrees(cx)
1106            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1107    }
1108
1109    pub fn worktree_id_for_entry(
1110        &self,
1111        entry_id: ProjectEntryId,
1112        cx: &AppContext,
1113    ) -> Option<WorktreeId> {
1114        self.worktree_for_entry(entry_id, cx)
1115            .map(|worktree| worktree.read(cx).id())
1116    }
1117
1118    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1119        paths.iter().all(|path| self.contains_path(&path, cx))
1120    }
1121
1122    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1123        for worktree in self.worktrees(cx) {
1124            let worktree = worktree.read(cx).as_local();
1125            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1126                return true;
1127            }
1128        }
1129        false
1130    }
1131
1132    pub fn create_entry(
1133        &mut self,
1134        project_path: impl Into<ProjectPath>,
1135        is_directory: bool,
1136        cx: &mut ModelContext<Self>,
1137    ) -> Option<Task<Result<Entry>>> {
1138        let project_path = project_path.into();
1139        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1140        if self.is_local() {
1141            Some(worktree.update(cx, |worktree, cx| {
1142                worktree
1143                    .as_local_mut()
1144                    .unwrap()
1145                    .create_entry(project_path.path, is_directory, cx)
1146            }))
1147        } else {
1148            let client = self.client.clone();
1149            let project_id = self.remote_id().unwrap();
1150            Some(cx.spawn_weak(|_, mut cx| async move {
1151                let response = client
1152                    .request(proto::CreateProjectEntry {
1153                        worktree_id: project_path.worktree_id.to_proto(),
1154                        project_id,
1155                        path: project_path.path.as_os_str().as_bytes().to_vec(),
1156                        is_directory,
1157                    })
1158                    .await?;
1159                let entry = response
1160                    .entry
1161                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1162                worktree
1163                    .update(&mut cx, |worktree, cx| {
1164                        worktree.as_remote_mut().unwrap().insert_entry(
1165                            entry,
1166                            response.worktree_scan_id as usize,
1167                            cx,
1168                        )
1169                    })
1170                    .await
1171            }))
1172        }
1173    }
1174
1175    pub fn copy_entry(
1176        &mut self,
1177        entry_id: ProjectEntryId,
1178        new_path: impl Into<Arc<Path>>,
1179        cx: &mut ModelContext<Self>,
1180    ) -> Option<Task<Result<Entry>>> {
1181        let worktree = self.worktree_for_entry(entry_id, cx)?;
1182        let new_path = new_path.into();
1183        if self.is_local() {
1184            worktree.update(cx, |worktree, cx| {
1185                worktree
1186                    .as_local_mut()
1187                    .unwrap()
1188                    .copy_entry(entry_id, new_path, cx)
1189            })
1190        } else {
1191            let client = self.client.clone();
1192            let project_id = self.remote_id().unwrap();
1193
1194            Some(cx.spawn_weak(|_, mut cx| async move {
1195                let response = client
1196                    .request(proto::CopyProjectEntry {
1197                        project_id,
1198                        entry_id: entry_id.to_proto(),
1199                        new_path: new_path.as_os_str().as_bytes().to_vec(),
1200                    })
1201                    .await?;
1202                let entry = response
1203                    .entry
1204                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1205                worktree
1206                    .update(&mut cx, |worktree, cx| {
1207                        worktree.as_remote_mut().unwrap().insert_entry(
1208                            entry,
1209                            response.worktree_scan_id as usize,
1210                            cx,
1211                        )
1212                    })
1213                    .await
1214            }))
1215        }
1216    }
1217
1218    pub fn rename_entry(
1219        &mut self,
1220        entry_id: ProjectEntryId,
1221        new_path: impl Into<Arc<Path>>,
1222        cx: &mut ModelContext<Self>,
1223    ) -> Option<Task<Result<Entry>>> {
1224        let worktree = self.worktree_for_entry(entry_id, cx)?;
1225        let new_path = new_path.into();
1226        if self.is_local() {
1227            worktree.update(cx, |worktree, cx| {
1228                worktree
1229                    .as_local_mut()
1230                    .unwrap()
1231                    .rename_entry(entry_id, new_path, cx)
1232            })
1233        } else {
1234            let client = self.client.clone();
1235            let project_id = self.remote_id().unwrap();
1236
1237            Some(cx.spawn_weak(|_, mut cx| async move {
1238                let response = client
1239                    .request(proto::RenameProjectEntry {
1240                        project_id,
1241                        entry_id: entry_id.to_proto(),
1242                        new_path: new_path.as_os_str().as_bytes().to_vec(),
1243                    })
1244                    .await?;
1245                let entry = response
1246                    .entry
1247                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1248                worktree
1249                    .update(&mut cx, |worktree, cx| {
1250                        worktree.as_remote_mut().unwrap().insert_entry(
1251                            entry,
1252                            response.worktree_scan_id as usize,
1253                            cx,
1254                        )
1255                    })
1256                    .await
1257            }))
1258        }
1259    }
1260
1261    pub fn delete_entry(
1262        &mut self,
1263        entry_id: ProjectEntryId,
1264        cx: &mut ModelContext<Self>,
1265    ) -> Option<Task<Result<()>>> {
1266        let worktree = self.worktree_for_entry(entry_id, cx)?;
1267        if self.is_local() {
1268            worktree.update(cx, |worktree, cx| {
1269                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1270            })
1271        } else {
1272            let client = self.client.clone();
1273            let project_id = self.remote_id().unwrap();
1274            Some(cx.spawn_weak(|_, mut cx| async move {
1275                let response = client
1276                    .request(proto::DeleteProjectEntry {
1277                        project_id,
1278                        entry_id: entry_id.to_proto(),
1279                    })
1280                    .await?;
1281                worktree
1282                    .update(&mut cx, move |worktree, cx| {
1283                        worktree.as_remote_mut().unwrap().delete_entry(
1284                            entry_id,
1285                            response.worktree_scan_id as usize,
1286                            cx,
1287                        )
1288                    })
1289                    .await
1290            }))
1291        }
1292    }
1293
1294    fn share(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
1295        if !self.is_online() {
1296            return Task::ready(Err(anyhow!("can't share an offline project")));
1297        }
1298
1299        let project_id;
1300        if let ProjectClientState::Local {
1301            remote_id_rx,
1302            is_shared,
1303            ..
1304        } = &mut self.client_state
1305        {
1306            if *is_shared {
1307                return Task::ready(Ok(()));
1308            }
1309            *is_shared = true;
1310            if let Some(id) = *remote_id_rx.borrow() {
1311                project_id = id;
1312            } else {
1313                return Task::ready(Err(anyhow!("project hasn't been registered")));
1314            }
1315        } else {
1316            return Task::ready(Err(anyhow!("can't share a remote project")));
1317        };
1318
1319        for open_buffer in self.opened_buffers.values_mut() {
1320            match open_buffer {
1321                OpenBuffer::Strong(_) => {}
1322                OpenBuffer::Weak(buffer) => {
1323                    if let Some(buffer) = buffer.upgrade(cx) {
1324                        *open_buffer = OpenBuffer::Strong(buffer);
1325                    }
1326                }
1327                OpenBuffer::Loading(_) => unreachable!(),
1328            }
1329        }
1330
1331        for worktree_handle in self.worktrees.iter_mut() {
1332            match worktree_handle {
1333                WorktreeHandle::Strong(_) => {}
1334                WorktreeHandle::Weak(worktree) => {
1335                    if let Some(worktree) = worktree.upgrade(cx) {
1336                        *worktree_handle = WorktreeHandle::Strong(worktree);
1337                    }
1338                }
1339            }
1340        }
1341
1342        let mut tasks = Vec::new();
1343        for worktree in self.worktrees(cx).collect::<Vec<_>>() {
1344            worktree.update(cx, |worktree, cx| {
1345                let worktree = worktree.as_local_mut().unwrap();
1346                tasks.push(worktree.share(project_id, cx));
1347            });
1348        }
1349
1350        for (server_id, status) in &self.language_server_statuses {
1351            self.client
1352                .send(proto::StartLanguageServer {
1353                    project_id,
1354                    server: Some(proto::LanguageServer {
1355                        id: *server_id as u64,
1356                        name: status.name.clone(),
1357                    }),
1358                })
1359                .log_err();
1360        }
1361
1362        cx.spawn(|this, mut cx| async move {
1363            for task in tasks {
1364                task.await?;
1365            }
1366            this.update(&mut cx, |_, cx| cx.notify());
1367            Ok(())
1368        })
1369    }
1370
1371    fn unshared(&mut self, cx: &mut ModelContext<Self>) {
1372        if let ProjectClientState::Local { is_shared, .. } = &mut self.client_state {
1373            if !*is_shared {
1374                return;
1375            }
1376
1377            *is_shared = false;
1378            self.collaborators.clear();
1379            self.shared_buffers.clear();
1380            for worktree_handle in self.worktrees.iter_mut() {
1381                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1382                    let is_visible = worktree.update(cx, |worktree, _| {
1383                        worktree.as_local_mut().unwrap().unshare();
1384                        worktree.is_visible()
1385                    });
1386                    if !is_visible {
1387                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1388                    }
1389                }
1390            }
1391
1392            for open_buffer in self.opened_buffers.values_mut() {
1393                match open_buffer {
1394                    OpenBuffer::Strong(buffer) => {
1395                        *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1396                    }
1397                    _ => {}
1398                }
1399            }
1400
1401            cx.notify();
1402        } else {
1403            log::error!("attempted to unshare a remote project");
1404        }
1405    }
1406
1407    pub fn respond_to_join_request(
1408        &mut self,
1409        requester_id: u64,
1410        allow: bool,
1411        cx: &mut ModelContext<Self>,
1412    ) {
1413        if let Some(project_id) = self.remote_id() {
1414            let share = if self.is_online() && allow {
1415                Some(self.share(cx))
1416            } else {
1417                None
1418            };
1419            let client = self.client.clone();
1420            cx.foreground()
1421                .spawn(async move {
1422                    client.send(proto::RespondToJoinProjectRequest {
1423                        requester_id,
1424                        project_id,
1425                        allow,
1426                    })?;
1427                    if let Some(share) = share {
1428                        share.await?;
1429                    }
1430                    anyhow::Ok(())
1431                })
1432                .detach_and_log_err(cx);
1433        }
1434    }
1435
1436    fn removed_from_project(&mut self, cx: &mut ModelContext<Self>) {
1437        if let ProjectClientState::Remote {
1438            sharing_has_stopped,
1439            ..
1440        } = &mut self.client_state
1441        {
1442            *sharing_has_stopped = true;
1443            self.collaborators.clear();
1444            for worktree in &self.worktrees {
1445                if let Some(worktree) = worktree.upgrade(cx) {
1446                    worktree.update(cx, |worktree, _| {
1447                        if let Some(worktree) = worktree.as_remote_mut() {
1448                            worktree.disconnected_from_host();
1449                        }
1450                    });
1451                }
1452            }
1453            cx.notify();
1454        }
1455    }
1456
1457    pub fn is_read_only(&self) -> bool {
1458        match &self.client_state {
1459            ProjectClientState::Local { .. } => false,
1460            ProjectClientState::Remote {
1461                sharing_has_stopped,
1462                ..
1463            } => *sharing_has_stopped,
1464        }
1465    }
1466
1467    pub fn is_local(&self) -> bool {
1468        match &self.client_state {
1469            ProjectClientState::Local { .. } => true,
1470            ProjectClientState::Remote { .. } => false,
1471        }
1472    }
1473
1474    pub fn is_remote(&self) -> bool {
1475        !self.is_local()
1476    }
1477
1478    pub fn create_buffer(
1479        &mut self,
1480        text: &str,
1481        language: Option<Arc<Language>>,
1482        cx: &mut ModelContext<Self>,
1483    ) -> Result<ModelHandle<Buffer>> {
1484        if self.is_remote() {
1485            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1486        }
1487
1488        let buffer = cx.add_model(|cx| {
1489            Buffer::new(self.replica_id(), text, cx)
1490                .with_language(language.unwrap_or(language::PLAIN_TEXT.clone()), cx)
1491        });
1492        self.register_buffer(&buffer, cx)?;
1493        Ok(buffer)
1494    }
1495
1496    pub fn open_path(
1497        &mut self,
1498        path: impl Into<ProjectPath>,
1499        cx: &mut ModelContext<Self>,
1500    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1501        let task = self.open_buffer(path, cx);
1502        cx.spawn_weak(|_, cx| async move {
1503            let buffer = task.await?;
1504            let project_entry_id = buffer
1505                .read_with(&cx, |buffer, cx| {
1506                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1507                })
1508                .ok_or_else(|| anyhow!("no project entry"))?;
1509            Ok((project_entry_id, buffer.into()))
1510        })
1511    }
1512
1513    pub fn open_local_buffer(
1514        &mut self,
1515        abs_path: impl AsRef<Path>,
1516        cx: &mut ModelContext<Self>,
1517    ) -> Task<Result<ModelHandle<Buffer>>> {
1518        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1519            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1520        } else {
1521            Task::ready(Err(anyhow!("no such path")))
1522        }
1523    }
1524
1525    pub fn open_buffer(
1526        &mut self,
1527        path: impl Into<ProjectPath>,
1528        cx: &mut ModelContext<Self>,
1529    ) -> Task<Result<ModelHandle<Buffer>>> {
1530        let project_path = path.into();
1531        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1532            worktree
1533        } else {
1534            return Task::ready(Err(anyhow!("no such worktree")));
1535        };
1536
1537        // If there is already a buffer for the given path, then return it.
1538        let existing_buffer = self.get_open_buffer(&project_path, cx);
1539        if let Some(existing_buffer) = existing_buffer {
1540            return Task::ready(Ok(existing_buffer));
1541        }
1542
1543        let mut loading_watch = match self.loading_buffers.entry(project_path.clone()) {
1544            // If the given path is already being loaded, then wait for that existing
1545            // task to complete and return the same buffer.
1546            hash_map::Entry::Occupied(e) => e.get().clone(),
1547
1548            // Otherwise, record the fact that this path is now being loaded.
1549            hash_map::Entry::Vacant(entry) => {
1550                let (mut tx, rx) = postage::watch::channel();
1551                entry.insert(rx.clone());
1552
1553                let load_buffer = if worktree.read(cx).is_local() {
1554                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1555                } else {
1556                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1557                };
1558
1559                cx.spawn(move |this, mut cx| async move {
1560                    let load_result = load_buffer.await;
1561                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1562                        // Record the fact that the buffer is no longer loading.
1563                        this.loading_buffers.remove(&project_path);
1564                        let buffer = load_result.map_err(Arc::new)?;
1565                        Ok(buffer)
1566                    }));
1567                })
1568                .detach();
1569                rx
1570            }
1571        };
1572
1573        cx.foreground().spawn(async move {
1574            loop {
1575                if let Some(result) = loading_watch.borrow().as_ref() {
1576                    match result {
1577                        Ok(buffer) => return Ok(buffer.clone()),
1578                        Err(error) => return Err(anyhow!("{}", error)),
1579                    }
1580                }
1581                loading_watch.next().await;
1582            }
1583        })
1584    }
1585
1586    fn open_local_buffer_internal(
1587        &mut self,
1588        path: &Arc<Path>,
1589        worktree: &ModelHandle<Worktree>,
1590        cx: &mut ModelContext<Self>,
1591    ) -> Task<Result<ModelHandle<Buffer>>> {
1592        let load_buffer = worktree.update(cx, |worktree, cx| {
1593            let worktree = worktree.as_local_mut().unwrap();
1594            worktree.load_buffer(path, cx)
1595        });
1596        cx.spawn(|this, mut cx| async move {
1597            let buffer = load_buffer.await?;
1598            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1599            Ok(buffer)
1600        })
1601    }
1602
1603    fn open_remote_buffer_internal(
1604        &mut self,
1605        path: &Arc<Path>,
1606        worktree: &ModelHandle<Worktree>,
1607        cx: &mut ModelContext<Self>,
1608    ) -> Task<Result<ModelHandle<Buffer>>> {
1609        let rpc = self.client.clone();
1610        let project_id = self.remote_id().unwrap();
1611        let remote_worktree_id = worktree.read(cx).id();
1612        let path = path.clone();
1613        let path_string = path.to_string_lossy().to_string();
1614        cx.spawn(|this, mut cx| async move {
1615            let response = rpc
1616                .request(proto::OpenBufferByPath {
1617                    project_id,
1618                    worktree_id: remote_worktree_id.to_proto(),
1619                    path: path_string,
1620                })
1621                .await?;
1622            let buffer = response.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
1623            this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1624                .await
1625        })
1626    }
1627
1628    fn open_local_buffer_via_lsp(
1629        &mut self,
1630        abs_path: lsp::Url,
1631        language_server_id: usize,
1632        language_server_name: LanguageServerName,
1633        cx: &mut ModelContext<Self>,
1634    ) -> Task<Result<ModelHandle<Buffer>>> {
1635        cx.spawn(|this, mut cx| async move {
1636            let abs_path = abs_path
1637                .to_file_path()
1638                .map_err(|_| anyhow!("can't convert URI to path"))?;
1639            let (worktree, relative_path) = if let Some(result) =
1640                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1641            {
1642                result
1643            } else {
1644                let worktree = this
1645                    .update(&mut cx, |this, cx| {
1646                        this.create_local_worktree(&abs_path, false, cx)
1647                    })
1648                    .await?;
1649                this.update(&mut cx, |this, cx| {
1650                    this.language_server_ids.insert(
1651                        (worktree.read(cx).id(), language_server_name),
1652                        language_server_id,
1653                    );
1654                });
1655                (worktree, PathBuf::new())
1656            };
1657
1658            let project_path = ProjectPath {
1659                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1660                path: relative_path.into(),
1661            };
1662            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1663                .await
1664        })
1665    }
1666
1667    pub fn open_buffer_by_id(
1668        &mut self,
1669        id: u64,
1670        cx: &mut ModelContext<Self>,
1671    ) -> Task<Result<ModelHandle<Buffer>>> {
1672        if let Some(buffer) = self.buffer_for_id(id, cx) {
1673            Task::ready(Ok(buffer))
1674        } else if self.is_local() {
1675            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1676        } else if let Some(project_id) = self.remote_id() {
1677            let request = self
1678                .client
1679                .request(proto::OpenBufferById { project_id, id });
1680            cx.spawn(|this, mut cx| async move {
1681                let buffer = request
1682                    .await?
1683                    .buffer
1684                    .ok_or_else(|| anyhow!("invalid buffer"))?;
1685                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
1686                    .await
1687            })
1688        } else {
1689            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1690        }
1691    }
1692
1693    pub fn save_buffer_as(
1694        &mut self,
1695        buffer: ModelHandle<Buffer>,
1696        abs_path: PathBuf,
1697        cx: &mut ModelContext<Project>,
1698    ) -> Task<Result<()>> {
1699        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1700        let old_path =
1701            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1702        cx.spawn(|this, mut cx| async move {
1703            if let Some(old_path) = old_path {
1704                this.update(&mut cx, |this, cx| {
1705                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1706                });
1707            }
1708            let (worktree, path) = worktree_task.await?;
1709            worktree
1710                .update(&mut cx, |worktree, cx| {
1711                    worktree
1712                        .as_local_mut()
1713                        .unwrap()
1714                        .save_buffer_as(buffer.clone(), path, cx)
1715                })
1716                .await?;
1717            this.update(&mut cx, |this, cx| {
1718                this.assign_language_to_buffer(&buffer, cx);
1719                this.register_buffer_with_language_server(&buffer, cx);
1720            });
1721            Ok(())
1722        })
1723    }
1724
1725    pub fn get_open_buffer(
1726        &mut self,
1727        path: &ProjectPath,
1728        cx: &mut ModelContext<Self>,
1729    ) -> Option<ModelHandle<Buffer>> {
1730        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1731        self.opened_buffers.values().find_map(|buffer| {
1732            let buffer = buffer.upgrade(cx)?;
1733            let file = File::from_dyn(buffer.read(cx).file())?;
1734            if file.worktree == worktree && file.path() == &path.path {
1735                Some(buffer)
1736            } else {
1737                None
1738            }
1739        })
1740    }
1741
1742    fn register_buffer(
1743        &mut self,
1744        buffer: &ModelHandle<Buffer>,
1745        cx: &mut ModelContext<Self>,
1746    ) -> Result<()> {
1747        let remote_id = buffer.read(cx).remote_id();
1748        let open_buffer = if self.is_remote() || self.is_shared() {
1749            OpenBuffer::Strong(buffer.clone())
1750        } else {
1751            OpenBuffer::Weak(buffer.downgrade())
1752        };
1753
1754        match self.opened_buffers.insert(remote_id, open_buffer) {
1755            None => {}
1756            Some(OpenBuffer::Loading(operations)) => {
1757                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1758            }
1759            Some(OpenBuffer::Weak(existing_handle)) => {
1760                if existing_handle.upgrade(cx).is_some() {
1761                    Err(anyhow!(
1762                        "already registered buffer with remote id {}",
1763                        remote_id
1764                    ))?
1765                }
1766            }
1767            Some(OpenBuffer::Strong(_)) => Err(anyhow!(
1768                "already registered buffer with remote id {}",
1769                remote_id
1770            ))?,
1771        }
1772        cx.subscribe(buffer, |this, buffer, event, cx| {
1773            this.on_buffer_event(buffer, event, cx);
1774        })
1775        .detach();
1776
1777        self.assign_language_to_buffer(buffer, cx);
1778        self.register_buffer_with_language_server(buffer, cx);
1779        cx.observe_release(buffer, |this, buffer, cx| {
1780            if let Some(file) = File::from_dyn(buffer.file()) {
1781                if file.is_local() {
1782                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1783                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1784                        server
1785                            .notify::<lsp::notification::DidCloseTextDocument>(
1786                                lsp::DidCloseTextDocumentParams {
1787                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1788                                },
1789                            )
1790                            .log_err();
1791                    }
1792                }
1793            }
1794        })
1795        .detach();
1796
1797        Ok(())
1798    }
1799
1800    fn register_buffer_with_language_server(
1801        &mut self,
1802        buffer_handle: &ModelHandle<Buffer>,
1803        cx: &mut ModelContext<Self>,
1804    ) {
1805        let buffer = buffer_handle.read(cx);
1806        let buffer_id = buffer.remote_id();
1807        if let Some(file) = File::from_dyn(buffer.file()) {
1808            if file.is_local() {
1809                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1810                let initial_snapshot = buffer.text_snapshot();
1811
1812                let mut language_server = None;
1813                let mut language_id = None;
1814                if let Some(language) = buffer.language() {
1815                    let worktree_id = file.worktree_id(cx);
1816                    if let Some(adapter) = language.lsp_adapter() {
1817                        language_id = adapter.id_for_language(language.name().as_ref());
1818                        language_server = self
1819                            .language_server_ids
1820                            .get(&(worktree_id, adapter.name()))
1821                            .and_then(|id| self.language_servers.get(&id))
1822                            .and_then(|server_state| {
1823                                if let LanguageServerState::Running { server, .. } = server_state {
1824                                    Some(server.clone())
1825                                } else {
1826                                    None
1827                                }
1828                            });
1829                    }
1830                }
1831
1832                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1833                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1834                        self.update_buffer_diagnostics(&buffer_handle, diagnostics, None, cx)
1835                            .log_err();
1836                    }
1837                }
1838
1839                if let Some(server) = language_server {
1840                    server
1841                        .notify::<lsp::notification::DidOpenTextDocument>(
1842                            lsp::DidOpenTextDocumentParams {
1843                                text_document: lsp::TextDocumentItem::new(
1844                                    uri,
1845                                    language_id.unwrap_or_default(),
1846                                    0,
1847                                    initial_snapshot.text(),
1848                                ),
1849                            }
1850                            .clone(),
1851                        )
1852                        .log_err();
1853                    buffer_handle.update(cx, |buffer, cx| {
1854                        buffer.set_completion_triggers(
1855                            server
1856                                .capabilities()
1857                                .completion_provider
1858                                .as_ref()
1859                                .and_then(|provider| provider.trigger_characters.clone())
1860                                .unwrap_or(Vec::new()),
1861                            cx,
1862                        )
1863                    });
1864                    self.buffer_snapshots
1865                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1866                }
1867            }
1868        }
1869    }
1870
1871    fn unregister_buffer_from_language_server(
1872        &mut self,
1873        buffer: &ModelHandle<Buffer>,
1874        old_path: PathBuf,
1875        cx: &mut ModelContext<Self>,
1876    ) {
1877        buffer.update(cx, |buffer, cx| {
1878            buffer.update_diagnostics(Default::default(), cx);
1879            self.buffer_snapshots.remove(&buffer.remote_id());
1880            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1881                language_server
1882                    .notify::<lsp::notification::DidCloseTextDocument>(
1883                        lsp::DidCloseTextDocumentParams {
1884                            text_document: lsp::TextDocumentIdentifier::new(
1885                                lsp::Url::from_file_path(old_path).unwrap(),
1886                            ),
1887                        },
1888                    )
1889                    .log_err();
1890            }
1891        });
1892    }
1893
1894    fn on_buffer_event(
1895        &mut self,
1896        buffer: ModelHandle<Buffer>,
1897        event: &BufferEvent,
1898        cx: &mut ModelContext<Self>,
1899    ) -> Option<()> {
1900        match event {
1901            BufferEvent::Operation(operation) => {
1902                if let Some(project_id) = self.shared_remote_id() {
1903                    let request = self.client.request(proto::UpdateBuffer {
1904                        project_id,
1905                        buffer_id: buffer.read(cx).remote_id(),
1906                        operations: vec![language::proto::serialize_operation(&operation)],
1907                    });
1908                    cx.background().spawn(request).detach_and_log_err(cx);
1909                } else if let Some(project_id) = self.remote_id() {
1910                    let _ = self
1911                        .client
1912                        .send(proto::RegisterProjectActivity { project_id });
1913                }
1914            }
1915            BufferEvent::Edited { .. } => {
1916                let language_server = self
1917                    .language_server_for_buffer(buffer.read(cx), cx)
1918                    .map(|(_, server)| server.clone())?;
1919                let buffer = buffer.read(cx);
1920                let file = File::from_dyn(buffer.file())?;
1921                let abs_path = file.as_local()?.abs_path(cx);
1922                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1923                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1924                let (version, prev_snapshot) = buffer_snapshots.last()?;
1925                let next_snapshot = buffer.text_snapshot();
1926                let next_version = version + 1;
1927
1928                let content_changes = buffer
1929                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1930                    .map(|edit| {
1931                        let edit_start = edit.new.start.0;
1932                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1933                        let new_text = next_snapshot
1934                            .text_for_range(edit.new.start.1..edit.new.end.1)
1935                            .collect();
1936                        lsp::TextDocumentContentChangeEvent {
1937                            range: Some(lsp::Range::new(
1938                                point_to_lsp(edit_start),
1939                                point_to_lsp(edit_end),
1940                            )),
1941                            range_length: None,
1942                            text: new_text,
1943                        }
1944                    })
1945                    .collect();
1946
1947                buffer_snapshots.push((next_version, next_snapshot));
1948
1949                language_server
1950                    .notify::<lsp::notification::DidChangeTextDocument>(
1951                        lsp::DidChangeTextDocumentParams {
1952                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1953                                uri,
1954                                next_version,
1955                            ),
1956                            content_changes,
1957                        },
1958                    )
1959                    .log_err();
1960            }
1961            BufferEvent::Saved => {
1962                let file = File::from_dyn(buffer.read(cx).file())?;
1963                let worktree_id = file.worktree_id(cx);
1964                let abs_path = file.as_local()?.abs_path(cx);
1965                let text_document = lsp::TextDocumentIdentifier {
1966                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1967                };
1968
1969                for (_, server) in self.language_servers_for_worktree(worktree_id) {
1970                    server
1971                        .notify::<lsp::notification::DidSaveTextDocument>(
1972                            lsp::DidSaveTextDocumentParams {
1973                                text_document: text_document.clone(),
1974                                text: None,
1975                            },
1976                        )
1977                        .log_err();
1978                }
1979
1980                // After saving a buffer, simulate disk-based diagnostics being finished for languages
1981                // that don't support a disk-based progress token.
1982                let (lsp_adapter, language_server) =
1983                    self.language_server_for_buffer(buffer.read(cx), cx)?;
1984                if lsp_adapter
1985                    .disk_based_diagnostics_progress_token()
1986                    .is_none()
1987                {
1988                    let server_id = language_server.server_id();
1989                    self.disk_based_diagnostics_finished(server_id, cx);
1990                    self.broadcast_language_server_update(
1991                        server_id,
1992                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1993                            proto::LspDiskBasedDiagnosticsUpdated {},
1994                        ),
1995                    );
1996                }
1997            }
1998            _ => {}
1999        }
2000
2001        None
2002    }
2003
2004    fn language_servers_for_worktree(
2005        &self,
2006        worktree_id: WorktreeId,
2007    ) -> impl Iterator<Item = (&Arc<dyn LspAdapter>, &Arc<LanguageServer>)> {
2008        self.language_server_ids
2009            .iter()
2010            .filter_map(move |((language_server_worktree_id, _), id)| {
2011                if *language_server_worktree_id == worktree_id {
2012                    if let Some(LanguageServerState::Running { adapter, server }) =
2013                        self.language_servers.get(&id)
2014                    {
2015                        return Some((adapter, server));
2016                    }
2017                }
2018                None
2019            })
2020    }
2021
2022    fn assign_language_to_buffer(
2023        &mut self,
2024        buffer: &ModelHandle<Buffer>,
2025        cx: &mut ModelContext<Self>,
2026    ) -> Option<()> {
2027        // If the buffer has a language, set it and start the language server if we haven't already.
2028        let full_path = buffer.read(cx).file()?.full_path(cx);
2029        let language = self.languages.select_language(&full_path)?;
2030        buffer.update(cx, |buffer, cx| {
2031            buffer.set_language(Some(language.clone()), cx);
2032        });
2033
2034        let file = File::from_dyn(buffer.read(cx).file())?;
2035        let worktree = file.worktree.read(cx).as_local()?;
2036        let worktree_id = worktree.id();
2037        let worktree_abs_path = worktree.abs_path().clone();
2038        self.start_language_server(worktree_id, worktree_abs_path, language, cx);
2039
2040        None
2041    }
2042
2043    fn start_language_server(
2044        &mut self,
2045        worktree_id: WorktreeId,
2046        worktree_path: Arc<Path>,
2047        language: Arc<Language>,
2048        cx: &mut ModelContext<Self>,
2049    ) {
2050        if !cx
2051            .global::<Settings>()
2052            .enable_language_server(Some(&language.name()))
2053        {
2054            return;
2055        }
2056
2057        let adapter = if let Some(adapter) = language.lsp_adapter() {
2058            adapter
2059        } else {
2060            return;
2061        };
2062        let key = (worktree_id, adapter.name());
2063
2064        self.language_server_ids
2065            .entry(key.clone())
2066            .or_insert_with(|| {
2067                let server_id = post_inc(&mut self.next_language_server_id);
2068                let language_server = self.languages.start_language_server(
2069                    server_id,
2070                    language.clone(),
2071                    worktree_path,
2072                    self.client.http_client(),
2073                    cx,
2074                );
2075                self.language_servers.insert(
2076                    server_id,
2077                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
2078                        let language_server = language_server?.await.log_err()?;
2079                        let language_server = language_server
2080                            .initialize(adapter.initialization_options())
2081                            .await
2082                            .log_err()?;
2083                        let this = this.upgrade(&cx)?;
2084                        let disk_based_diagnostics_progress_token =
2085                            adapter.disk_based_diagnostics_progress_token();
2086
2087                        language_server
2088                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
2089                                let this = this.downgrade();
2090                                let adapter = adapter.clone();
2091                                move |params, mut cx| {
2092                                    if let Some(this) = this.upgrade(&cx) {
2093                                        this.update(&mut cx, |this, cx| {
2094                                            this.on_lsp_diagnostics_published(
2095                                                server_id, params, &adapter, cx,
2096                                            );
2097                                        });
2098                                    }
2099                                }
2100                            })
2101                            .detach();
2102
2103                        language_server
2104                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2105                                let settings = this.read_with(&cx, |this, _| {
2106                                    this.language_server_settings.clone()
2107                                });
2108                                move |params, _| {
2109                                    let settings = settings.lock().clone();
2110                                    async move {
2111                                        Ok(params
2112                                            .items
2113                                            .into_iter()
2114                                            .map(|item| {
2115                                                if let Some(section) = &item.section {
2116                                                    settings
2117                                                        .get(section)
2118                                                        .cloned()
2119                                                        .unwrap_or(serde_json::Value::Null)
2120                                                } else {
2121                                                    settings.clone()
2122                                                }
2123                                            })
2124                                            .collect())
2125                                    }
2126                                }
2127                            })
2128                            .detach();
2129
2130                        // Even though we don't have handling for these requests, respond to them to
2131                        // avoid stalling any language server like `gopls` which waits for a response
2132                        // to these requests when initializing.
2133                        language_server
2134                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2135                                let this = this.downgrade();
2136                                move |params, mut cx| async move {
2137                                    if let Some(this) = this.upgrade(&cx) {
2138                                        this.update(&mut cx, |this, _| {
2139                                            if let Some(status) =
2140                                                this.language_server_statuses.get_mut(&server_id)
2141                                            {
2142                                                if let lsp::NumberOrString::String(token) =
2143                                                    params.token
2144                                                {
2145                                                    status.progress_tokens.insert(token);
2146                                                }
2147                                            }
2148                                        });
2149                                    }
2150                                    Ok(())
2151                                }
2152                            })
2153                            .detach();
2154                        language_server
2155                            .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2156                                Ok(())
2157                            })
2158                            .detach();
2159
2160                        language_server
2161                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2162                                let this = this.downgrade();
2163                                let adapter = adapter.clone();
2164                                let language_server = language_server.clone();
2165                                move |params, cx| {
2166                                    Self::on_lsp_workspace_edit(
2167                                        this,
2168                                        params,
2169                                        server_id,
2170                                        adapter.clone(),
2171                                        language_server.clone(),
2172                                        cx,
2173                                    )
2174                                }
2175                            })
2176                            .detach();
2177
2178                        language_server
2179                            .on_notification::<lsp::notification::Progress, _>({
2180                                let this = this.downgrade();
2181                                move |params, mut cx| {
2182                                    if let Some(this) = this.upgrade(&cx) {
2183                                        this.update(&mut cx, |this, cx| {
2184                                            this.on_lsp_progress(
2185                                                params,
2186                                                server_id,
2187                                                disk_based_diagnostics_progress_token,
2188                                                cx,
2189                                            );
2190                                        });
2191                                    }
2192                                }
2193                            })
2194                            .detach();
2195
2196                        this.update(&mut cx, |this, cx| {
2197                            // If the language server for this key doesn't match the server id, don't store the
2198                            // server. Which will cause it to be dropped, killing the process
2199                            if this
2200                                .language_server_ids
2201                                .get(&key)
2202                                .map(|id| id != &server_id)
2203                                .unwrap_or(false)
2204                            {
2205                                return None;
2206                            }
2207
2208                            // Update language_servers collection with Running variant of LanguageServerState
2209                            // indicating that the server is up and running and ready
2210                            this.language_servers.insert(
2211                                server_id,
2212                                LanguageServerState::Running {
2213                                    adapter: adapter.clone(),
2214                                    server: language_server.clone(),
2215                                },
2216                            );
2217                            this.language_server_statuses.insert(
2218                                server_id,
2219                                LanguageServerStatus {
2220                                    name: language_server.name().to_string(),
2221                                    pending_work: Default::default(),
2222                                    has_pending_diagnostic_updates: false,
2223                                    progress_tokens: Default::default(),
2224                                },
2225                            );
2226                            language_server
2227                                .notify::<lsp::notification::DidChangeConfiguration>(
2228                                    lsp::DidChangeConfigurationParams {
2229                                        settings: this.language_server_settings.lock().clone(),
2230                                    },
2231                                )
2232                                .ok();
2233
2234                            if let Some(project_id) = this.shared_remote_id() {
2235                                this.client
2236                                    .send(proto::StartLanguageServer {
2237                                        project_id,
2238                                        server: Some(proto::LanguageServer {
2239                                            id: server_id as u64,
2240                                            name: language_server.name().to_string(),
2241                                        }),
2242                                    })
2243                                    .log_err();
2244                            }
2245
2246                            // Tell the language server about every open buffer in the worktree that matches the language.
2247                            for buffer in this.opened_buffers.values() {
2248                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2249                                    let buffer = buffer_handle.read(cx);
2250                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2251                                        file
2252                                    } else {
2253                                        continue;
2254                                    };
2255                                    let language = if let Some(language) = buffer.language() {
2256                                        language
2257                                    } else {
2258                                        continue;
2259                                    };
2260                                    if file.worktree.read(cx).id() != key.0
2261                                        || language.lsp_adapter().map(|a| a.name())
2262                                            != Some(key.1.clone())
2263                                    {
2264                                        continue;
2265                                    }
2266
2267                                    let file = file.as_local()?;
2268                                    let versions = this
2269                                        .buffer_snapshots
2270                                        .entry(buffer.remote_id())
2271                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2272                                    let (version, initial_snapshot) = versions.last().unwrap();
2273                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2274                                    let language_id =
2275                                        adapter.id_for_language(language.name().as_ref());
2276                                    language_server
2277                                        .notify::<lsp::notification::DidOpenTextDocument>(
2278                                            lsp::DidOpenTextDocumentParams {
2279                                                text_document: lsp::TextDocumentItem::new(
2280                                                    uri,
2281                                                    language_id.unwrap_or_default(),
2282                                                    *version,
2283                                                    initial_snapshot.text(),
2284                                                ),
2285                                            },
2286                                        )
2287                                        .log_err()?;
2288                                    buffer_handle.update(cx, |buffer, cx| {
2289                                        buffer.set_completion_triggers(
2290                                            language_server
2291                                                .capabilities()
2292                                                .completion_provider
2293                                                .as_ref()
2294                                                .and_then(|provider| {
2295                                                    provider.trigger_characters.clone()
2296                                                })
2297                                                .unwrap_or(Vec::new()),
2298                                            cx,
2299                                        )
2300                                    });
2301                                }
2302                            }
2303
2304                            cx.notify();
2305                            Some(language_server)
2306                        })
2307                    })),
2308                );
2309
2310                server_id
2311            });
2312    }
2313
2314    // Returns a list of all of the worktrees which no longer have a language server and the root path
2315    // for the stopped server
2316    fn stop_language_server(
2317        &mut self,
2318        worktree_id: WorktreeId,
2319        adapter_name: LanguageServerName,
2320        cx: &mut ModelContext<Self>,
2321    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2322        let key = (worktree_id, adapter_name);
2323        if let Some(server_id) = self.language_server_ids.remove(&key) {
2324            // Remove other entries for this language server as well
2325            let mut orphaned_worktrees = vec![worktree_id];
2326            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2327            for other_key in other_keys {
2328                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2329                    self.language_server_ids.remove(&other_key);
2330                    orphaned_worktrees.push(other_key.0);
2331                }
2332            }
2333
2334            self.language_server_statuses.remove(&server_id);
2335            cx.notify();
2336
2337            let server_state = self.language_servers.remove(&server_id);
2338            cx.spawn_weak(|this, mut cx| async move {
2339                let mut root_path = None;
2340
2341                let server = match server_state {
2342                    Some(LanguageServerState::Starting(started_language_server)) => {
2343                        started_language_server.await
2344                    }
2345                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2346                    None => None,
2347                };
2348
2349                if let Some(server) = server {
2350                    root_path = Some(server.root_path().clone());
2351                    if let Some(shutdown) = server.shutdown() {
2352                        shutdown.await;
2353                    }
2354                }
2355
2356                if let Some(this) = this.upgrade(&cx) {
2357                    this.update(&mut cx, |this, cx| {
2358                        this.language_server_statuses.remove(&server_id);
2359                        cx.notify();
2360                    });
2361                }
2362
2363                (root_path, orphaned_worktrees)
2364            })
2365        } else {
2366            Task::ready((None, Vec::new()))
2367        }
2368    }
2369
2370    pub fn restart_language_servers_for_buffers(
2371        &mut self,
2372        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2373        cx: &mut ModelContext<Self>,
2374    ) -> Option<()> {
2375        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2376            .into_iter()
2377            .filter_map(|buffer| {
2378                let file = File::from_dyn(buffer.read(cx).file())?;
2379                let worktree = file.worktree.read(cx).as_local()?;
2380                let worktree_id = worktree.id();
2381                let worktree_abs_path = worktree.abs_path().clone();
2382                let full_path = file.full_path(cx);
2383                Some((worktree_id, worktree_abs_path, full_path))
2384            })
2385            .collect();
2386        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2387            let language = self.languages.select_language(&full_path)?;
2388            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2389        }
2390
2391        None
2392    }
2393
2394    fn restart_language_server(
2395        &mut self,
2396        worktree_id: WorktreeId,
2397        fallback_path: Arc<Path>,
2398        language: Arc<Language>,
2399        cx: &mut ModelContext<Self>,
2400    ) {
2401        let adapter = if let Some(adapter) = language.lsp_adapter() {
2402            adapter
2403        } else {
2404            return;
2405        };
2406
2407        let server_name = adapter.name();
2408        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2409        cx.spawn_weak(|this, mut cx| async move {
2410            let (original_root_path, orphaned_worktrees) = stop.await;
2411            if let Some(this) = this.upgrade(&cx) {
2412                this.update(&mut cx, |this, cx| {
2413                    // Attempt to restart using original server path. Fallback to passed in
2414                    // path if we could not retrieve the root path
2415                    let root_path = original_root_path
2416                        .map(|path_buf| Arc::from(path_buf.as_path()))
2417                        .unwrap_or(fallback_path);
2418
2419                    this.start_language_server(worktree_id, root_path, language, cx);
2420
2421                    // Lookup new server id and set it for each of the orphaned worktrees
2422                    if let Some(new_server_id) = this
2423                        .language_server_ids
2424                        .get(&(worktree_id, server_name.clone()))
2425                        .cloned()
2426                    {
2427                        for orphaned_worktree in orphaned_worktrees {
2428                            this.language_server_ids.insert(
2429                                (orphaned_worktree, server_name.clone()),
2430                                new_server_id.clone(),
2431                            );
2432                        }
2433                    }
2434                });
2435            }
2436        })
2437        .detach();
2438    }
2439
2440    fn on_lsp_diagnostics_published(
2441        &mut self,
2442        server_id: usize,
2443        mut params: lsp::PublishDiagnosticsParams,
2444        adapter: &Arc<dyn LspAdapter>,
2445        cx: &mut ModelContext<Self>,
2446    ) {
2447        adapter.process_diagnostics(&mut params);
2448        self.update_diagnostics(
2449            server_id,
2450            params,
2451            adapter.disk_based_diagnostic_sources(),
2452            cx,
2453        )
2454        .log_err();
2455    }
2456
2457    fn on_lsp_progress(
2458        &mut self,
2459        progress: lsp::ProgressParams,
2460        server_id: usize,
2461        disk_based_diagnostics_progress_token: Option<&str>,
2462        cx: &mut ModelContext<Self>,
2463    ) {
2464        let token = match progress.token {
2465            lsp::NumberOrString::String(token) => token,
2466            lsp::NumberOrString::Number(token) => {
2467                log::info!("skipping numeric progress token {}", token);
2468                return;
2469            }
2470        };
2471        let progress = match progress.value {
2472            lsp::ProgressParamsValue::WorkDone(value) => value,
2473        };
2474        let language_server_status =
2475            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2476                status
2477            } else {
2478                return;
2479            };
2480
2481        if !language_server_status.progress_tokens.contains(&token) {
2482            return;
2483        }
2484
2485        match progress {
2486            lsp::WorkDoneProgress::Begin(report) => {
2487                if Some(token.as_str()) == disk_based_diagnostics_progress_token {
2488                    language_server_status.has_pending_diagnostic_updates = true;
2489                    self.disk_based_diagnostics_started(server_id, cx);
2490                    self.broadcast_language_server_update(
2491                        server_id,
2492                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2493                            proto::LspDiskBasedDiagnosticsUpdating {},
2494                        ),
2495                    );
2496                } else {
2497                    self.on_lsp_work_start(
2498                        server_id,
2499                        token.clone(),
2500                        LanguageServerProgress {
2501                            message: report.message.clone(),
2502                            percentage: report.percentage.map(|p| p as usize),
2503                            last_update_at: Instant::now(),
2504                        },
2505                        cx,
2506                    );
2507                    self.broadcast_language_server_update(
2508                        server_id,
2509                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2510                            token,
2511                            message: report.message,
2512                            percentage: report.percentage.map(|p| p as u32),
2513                        }),
2514                    );
2515                }
2516            }
2517            lsp::WorkDoneProgress::Report(report) => {
2518                if Some(token.as_str()) != disk_based_diagnostics_progress_token {
2519                    self.on_lsp_work_progress(
2520                        server_id,
2521                        token.clone(),
2522                        LanguageServerProgress {
2523                            message: report.message.clone(),
2524                            percentage: report.percentage.map(|p| p as usize),
2525                            last_update_at: Instant::now(),
2526                        },
2527                        cx,
2528                    );
2529                    self.broadcast_language_server_update(
2530                        server_id,
2531                        proto::update_language_server::Variant::WorkProgress(
2532                            proto::LspWorkProgress {
2533                                token,
2534                                message: report.message,
2535                                percentage: report.percentage.map(|p| p as u32),
2536                            },
2537                        ),
2538                    );
2539                }
2540            }
2541            lsp::WorkDoneProgress::End(_) => {
2542                language_server_status.progress_tokens.remove(&token);
2543
2544                if Some(token.as_str()) == disk_based_diagnostics_progress_token {
2545                    language_server_status.has_pending_diagnostic_updates = false;
2546                    self.disk_based_diagnostics_finished(server_id, cx);
2547                    self.broadcast_language_server_update(
2548                        server_id,
2549                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2550                            proto::LspDiskBasedDiagnosticsUpdated {},
2551                        ),
2552                    );
2553                } else {
2554                    self.on_lsp_work_end(server_id, token.clone(), cx);
2555                    self.broadcast_language_server_update(
2556                        server_id,
2557                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2558                            token,
2559                        }),
2560                    );
2561                }
2562            }
2563        }
2564    }
2565
2566    fn on_lsp_work_start(
2567        &mut self,
2568        language_server_id: usize,
2569        token: String,
2570        progress: LanguageServerProgress,
2571        cx: &mut ModelContext<Self>,
2572    ) {
2573        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2574            status.pending_work.insert(token, progress);
2575            cx.notify();
2576        }
2577    }
2578
2579    fn on_lsp_work_progress(
2580        &mut self,
2581        language_server_id: usize,
2582        token: String,
2583        progress: LanguageServerProgress,
2584        cx: &mut ModelContext<Self>,
2585    ) {
2586        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2587            let entry = status
2588                .pending_work
2589                .entry(token)
2590                .or_insert(LanguageServerProgress {
2591                    message: Default::default(),
2592                    percentage: Default::default(),
2593                    last_update_at: progress.last_update_at,
2594                });
2595            if progress.message.is_some() {
2596                entry.message = progress.message;
2597            }
2598            if progress.percentage.is_some() {
2599                entry.percentage = progress.percentage;
2600            }
2601            entry.last_update_at = progress.last_update_at;
2602            cx.notify();
2603        }
2604    }
2605
2606    fn on_lsp_work_end(
2607        &mut self,
2608        language_server_id: usize,
2609        token: String,
2610        cx: &mut ModelContext<Self>,
2611    ) {
2612        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2613            status.pending_work.remove(&token);
2614            cx.notify();
2615        }
2616    }
2617
2618    async fn on_lsp_workspace_edit(
2619        this: WeakModelHandle<Self>,
2620        params: lsp::ApplyWorkspaceEditParams,
2621        server_id: usize,
2622        adapter: Arc<dyn LspAdapter>,
2623        language_server: Arc<LanguageServer>,
2624        mut cx: AsyncAppContext,
2625    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2626        let this = this
2627            .upgrade(&cx)
2628            .ok_or_else(|| anyhow!("project project closed"))?;
2629        let transaction = Self::deserialize_workspace_edit(
2630            this.clone(),
2631            params.edit,
2632            true,
2633            adapter.clone(),
2634            language_server.clone(),
2635            &mut cx,
2636        )
2637        .await
2638        .log_err();
2639        this.update(&mut cx, |this, _| {
2640            if let Some(transaction) = transaction {
2641                this.last_workspace_edits_by_language_server
2642                    .insert(server_id, transaction);
2643            }
2644        });
2645        Ok(lsp::ApplyWorkspaceEditResponse {
2646            applied: true,
2647            failed_change: None,
2648            failure_reason: None,
2649        })
2650    }
2651
2652    fn broadcast_language_server_update(
2653        &self,
2654        language_server_id: usize,
2655        event: proto::update_language_server::Variant,
2656    ) {
2657        if let Some(project_id) = self.shared_remote_id() {
2658            self.client
2659                .send(proto::UpdateLanguageServer {
2660                    project_id,
2661                    language_server_id: language_server_id as u64,
2662                    variant: Some(event),
2663                })
2664                .log_err();
2665        }
2666    }
2667
2668    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2669        for server_state in self.language_servers.values() {
2670            if let LanguageServerState::Running { server, .. } = server_state {
2671                server
2672                    .notify::<lsp::notification::DidChangeConfiguration>(
2673                        lsp::DidChangeConfigurationParams {
2674                            settings: settings.clone(),
2675                        },
2676                    )
2677                    .ok();
2678            }
2679        }
2680        *self.language_server_settings.lock() = settings;
2681    }
2682
2683    pub fn language_server_statuses(
2684        &self,
2685    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2686        self.language_server_statuses.values()
2687    }
2688
2689    pub fn update_diagnostics(
2690        &mut self,
2691        language_server_id: usize,
2692        params: lsp::PublishDiagnosticsParams,
2693        disk_based_sources: &[&str],
2694        cx: &mut ModelContext<Self>,
2695    ) -> Result<()> {
2696        let abs_path = params
2697            .uri
2698            .to_file_path()
2699            .map_err(|_| anyhow!("URI is not a file"))?;
2700        let mut diagnostics = Vec::default();
2701        let mut primary_diagnostic_group_ids = HashMap::default();
2702        let mut sources_by_group_id = HashMap::default();
2703        let mut supporting_diagnostics = HashMap::default();
2704        for diagnostic in &params.diagnostics {
2705            let source = diagnostic.source.as_ref();
2706            let code = diagnostic.code.as_ref().map(|code| match code {
2707                lsp::NumberOrString::Number(code) => code.to_string(),
2708                lsp::NumberOrString::String(code) => code.clone(),
2709            });
2710            let range = range_from_lsp(diagnostic.range);
2711            let is_supporting = diagnostic
2712                .related_information
2713                .as_ref()
2714                .map_or(false, |infos| {
2715                    infos.iter().any(|info| {
2716                        primary_diagnostic_group_ids.contains_key(&(
2717                            source,
2718                            code.clone(),
2719                            range_from_lsp(info.location.range),
2720                        ))
2721                    })
2722                });
2723
2724            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2725                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2726            });
2727
2728            if is_supporting {
2729                supporting_diagnostics.insert(
2730                    (source, code.clone(), range),
2731                    (diagnostic.severity, is_unnecessary),
2732                );
2733            } else {
2734                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2735                let is_disk_based = source.map_or(false, |source| {
2736                    disk_based_sources.contains(&source.as_str())
2737                });
2738
2739                sources_by_group_id.insert(group_id, source);
2740                primary_diagnostic_group_ids
2741                    .insert((source, code.clone(), range.clone()), group_id);
2742
2743                diagnostics.push(DiagnosticEntry {
2744                    range,
2745                    diagnostic: Diagnostic {
2746                        code: code.clone(),
2747                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2748                        message: diagnostic.message.clone(),
2749                        group_id,
2750                        is_primary: true,
2751                        is_valid: true,
2752                        is_disk_based,
2753                        is_unnecessary,
2754                    },
2755                });
2756                if let Some(infos) = &diagnostic.related_information {
2757                    for info in infos {
2758                        if info.location.uri == params.uri && !info.message.is_empty() {
2759                            let range = range_from_lsp(info.location.range);
2760                            diagnostics.push(DiagnosticEntry {
2761                                range,
2762                                diagnostic: Diagnostic {
2763                                    code: code.clone(),
2764                                    severity: DiagnosticSeverity::INFORMATION,
2765                                    message: info.message.clone(),
2766                                    group_id,
2767                                    is_primary: false,
2768                                    is_valid: true,
2769                                    is_disk_based,
2770                                    is_unnecessary: false,
2771                                },
2772                            });
2773                        }
2774                    }
2775                }
2776            }
2777        }
2778
2779        for entry in &mut diagnostics {
2780            let diagnostic = &mut entry.diagnostic;
2781            if !diagnostic.is_primary {
2782                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2783                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2784                    source,
2785                    diagnostic.code.clone(),
2786                    entry.range.clone(),
2787                )) {
2788                    if let Some(severity) = severity {
2789                        diagnostic.severity = severity;
2790                    }
2791                    diagnostic.is_unnecessary = is_unnecessary;
2792                }
2793            }
2794        }
2795
2796        self.update_diagnostic_entries(
2797            language_server_id,
2798            abs_path,
2799            params.version,
2800            diagnostics,
2801            cx,
2802        )?;
2803        Ok(())
2804    }
2805
2806    pub fn update_diagnostic_entries(
2807        &mut self,
2808        language_server_id: usize,
2809        abs_path: PathBuf,
2810        version: Option<i32>,
2811        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2812        cx: &mut ModelContext<Project>,
2813    ) -> Result<(), anyhow::Error> {
2814        let (worktree, relative_path) = self
2815            .find_local_worktree(&abs_path, cx)
2816            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2817
2818        let project_path = ProjectPath {
2819            worktree_id: worktree.read(cx).id(),
2820            path: relative_path.into(),
2821        };
2822        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2823            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2824        }
2825
2826        let updated = worktree.update(cx, |worktree, cx| {
2827            worktree
2828                .as_local_mut()
2829                .ok_or_else(|| anyhow!("not a local worktree"))?
2830                .update_diagnostics(
2831                    language_server_id,
2832                    project_path.path.clone(),
2833                    diagnostics,
2834                    cx,
2835                )
2836        })?;
2837        if updated {
2838            cx.emit(Event::DiagnosticsUpdated {
2839                language_server_id,
2840                path: project_path,
2841            });
2842        }
2843        Ok(())
2844    }
2845
2846    fn update_buffer_diagnostics(
2847        &mut self,
2848        buffer: &ModelHandle<Buffer>,
2849        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2850        version: Option<i32>,
2851        cx: &mut ModelContext<Self>,
2852    ) -> Result<()> {
2853        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2854            Ordering::Equal
2855                .then_with(|| b.is_primary.cmp(&a.is_primary))
2856                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2857                .then_with(|| a.severity.cmp(&b.severity))
2858                .then_with(|| a.message.cmp(&b.message))
2859        }
2860
2861        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2862
2863        diagnostics.sort_unstable_by(|a, b| {
2864            Ordering::Equal
2865                .then_with(|| a.range.start.cmp(&b.range.start))
2866                .then_with(|| b.range.end.cmp(&a.range.end))
2867                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2868        });
2869
2870        let mut sanitized_diagnostics = Vec::new();
2871        let edits_since_save = Patch::new(
2872            snapshot
2873                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2874                .collect(),
2875        );
2876        for entry in diagnostics {
2877            let start;
2878            let end;
2879            if entry.diagnostic.is_disk_based {
2880                // Some diagnostics are based on files on disk instead of buffers'
2881                // current contents. Adjust these diagnostics' ranges to reflect
2882                // any unsaved edits.
2883                start = edits_since_save.old_to_new(entry.range.start);
2884                end = edits_since_save.old_to_new(entry.range.end);
2885            } else {
2886                start = entry.range.start;
2887                end = entry.range.end;
2888            }
2889
2890            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2891                ..snapshot.clip_point_utf16(end, Bias::Right);
2892
2893            // Expand empty ranges by one character
2894            if range.start == range.end {
2895                range.end.column += 1;
2896                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2897                if range.start == range.end && range.end.column > 0 {
2898                    range.start.column -= 1;
2899                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2900                }
2901            }
2902
2903            sanitized_diagnostics.push(DiagnosticEntry {
2904                range,
2905                diagnostic: entry.diagnostic,
2906            });
2907        }
2908        drop(edits_since_save);
2909
2910        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2911        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2912        Ok(())
2913    }
2914
2915    pub fn reload_buffers(
2916        &self,
2917        buffers: HashSet<ModelHandle<Buffer>>,
2918        push_to_history: bool,
2919        cx: &mut ModelContext<Self>,
2920    ) -> Task<Result<ProjectTransaction>> {
2921        let mut local_buffers = Vec::new();
2922        let mut remote_buffers = None;
2923        for buffer_handle in buffers {
2924            let buffer = buffer_handle.read(cx);
2925            if buffer.is_dirty() {
2926                if let Some(file) = File::from_dyn(buffer.file()) {
2927                    if file.is_local() {
2928                        local_buffers.push(buffer_handle);
2929                    } else {
2930                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2931                    }
2932                }
2933            }
2934        }
2935
2936        let remote_buffers = self.remote_id().zip(remote_buffers);
2937        let client = self.client.clone();
2938
2939        cx.spawn(|this, mut cx| async move {
2940            let mut project_transaction = ProjectTransaction::default();
2941
2942            if let Some((project_id, remote_buffers)) = remote_buffers {
2943                let response = client
2944                    .request(proto::ReloadBuffers {
2945                        project_id,
2946                        buffer_ids: remote_buffers
2947                            .iter()
2948                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2949                            .collect(),
2950                    })
2951                    .await?
2952                    .transaction
2953                    .ok_or_else(|| anyhow!("missing transaction"))?;
2954                project_transaction = this
2955                    .update(&mut cx, |this, cx| {
2956                        this.deserialize_project_transaction(response, push_to_history, cx)
2957                    })
2958                    .await?;
2959            }
2960
2961            for buffer in local_buffers {
2962                let transaction = buffer
2963                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2964                    .await?;
2965                buffer.update(&mut cx, |buffer, cx| {
2966                    if let Some(transaction) = transaction {
2967                        if !push_to_history {
2968                            buffer.forget_transaction(transaction.id);
2969                        }
2970                        project_transaction.0.insert(cx.handle(), transaction);
2971                    }
2972                });
2973            }
2974
2975            Ok(project_transaction)
2976        })
2977    }
2978
2979    pub fn format(
2980        &self,
2981        buffers: HashSet<ModelHandle<Buffer>>,
2982        push_to_history: bool,
2983        cx: &mut ModelContext<Project>,
2984    ) -> Task<Result<ProjectTransaction>> {
2985        let mut local_buffers = Vec::new();
2986        let mut remote_buffers = None;
2987        for buffer_handle in buffers {
2988            let buffer = buffer_handle.read(cx);
2989            if let Some(file) = File::from_dyn(buffer.file()) {
2990                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2991                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2992                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2993                    }
2994                } else {
2995                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2996                }
2997            } else {
2998                return Task::ready(Ok(Default::default()));
2999            }
3000        }
3001
3002        let remote_buffers = self.remote_id().zip(remote_buffers);
3003        let client = self.client.clone();
3004
3005        cx.spawn(|this, mut cx| async move {
3006            let mut project_transaction = ProjectTransaction::default();
3007
3008            if let Some((project_id, remote_buffers)) = remote_buffers {
3009                let response = client
3010                    .request(proto::FormatBuffers {
3011                        project_id,
3012                        buffer_ids: remote_buffers
3013                            .iter()
3014                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3015                            .collect(),
3016                    })
3017                    .await?
3018                    .transaction
3019                    .ok_or_else(|| anyhow!("missing transaction"))?;
3020                project_transaction = this
3021                    .update(&mut cx, |this, cx| {
3022                        this.deserialize_project_transaction(response, push_to_history, cx)
3023                    })
3024                    .await?;
3025            }
3026
3027            for (buffer, buffer_abs_path, language_server) in local_buffers {
3028                let text_document = lsp::TextDocumentIdentifier::new(
3029                    lsp::Url::from_file_path(&buffer_abs_path).unwrap(),
3030                );
3031                let capabilities = &language_server.capabilities();
3032                let tab_size = cx.update(|cx| {
3033                    let language_name = buffer.read(cx).language().map(|language| language.name());
3034                    cx.global::<Settings>().tab_size(language_name.as_deref())
3035                });
3036                let lsp_edits = if capabilities
3037                    .document_formatting_provider
3038                    .as_ref()
3039                    .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3040                {
3041                    language_server
3042                        .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
3043                            text_document,
3044                            options: lsp::FormattingOptions {
3045                                tab_size: tab_size.into(),
3046                                insert_spaces: true,
3047                                insert_final_newline: Some(true),
3048                                ..Default::default()
3049                            },
3050                            work_done_progress_params: Default::default(),
3051                        })
3052                        .await?
3053                } else if capabilities
3054                    .document_range_formatting_provider
3055                    .as_ref()
3056                    .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3057                {
3058                    let buffer_start = lsp::Position::new(0, 0);
3059                    let buffer_end =
3060                        buffer.read_with(&cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3061                    language_server
3062                        .request::<lsp::request::RangeFormatting>(
3063                            lsp::DocumentRangeFormattingParams {
3064                                text_document,
3065                                range: lsp::Range::new(buffer_start, buffer_end),
3066                                options: lsp::FormattingOptions {
3067                                    tab_size: tab_size.into(),
3068                                    insert_spaces: true,
3069                                    insert_final_newline: Some(true),
3070                                    ..Default::default()
3071                                },
3072                                work_done_progress_params: Default::default(),
3073                            },
3074                        )
3075                        .await?
3076                } else {
3077                    continue;
3078                };
3079
3080                if let Some(lsp_edits) = lsp_edits {
3081                    let edits = this
3082                        .update(&mut cx, |this, cx| {
3083                            this.edits_from_lsp(&buffer, lsp_edits, None, cx)
3084                        })
3085                        .await?;
3086                    buffer.update(&mut cx, |buffer, cx| {
3087                        buffer.finalize_last_transaction();
3088                        buffer.start_transaction();
3089                        for (range, text) in edits {
3090                            buffer.edit([(range, text)], cx);
3091                        }
3092                        if buffer.end_transaction(cx).is_some() {
3093                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3094                            if !push_to_history {
3095                                buffer.forget_transaction(transaction.id);
3096                            }
3097                            project_transaction.0.insert(cx.handle(), transaction);
3098                        }
3099                    });
3100                }
3101            }
3102
3103            Ok(project_transaction)
3104        })
3105    }
3106
3107    pub fn definition<T: ToPointUtf16>(
3108        &self,
3109        buffer: &ModelHandle<Buffer>,
3110        position: T,
3111        cx: &mut ModelContext<Self>,
3112    ) -> Task<Result<Vec<LocationLink>>> {
3113        let position = position.to_point_utf16(buffer.read(cx));
3114        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3115    }
3116
3117    pub fn references<T: ToPointUtf16>(
3118        &self,
3119        buffer: &ModelHandle<Buffer>,
3120        position: T,
3121        cx: &mut ModelContext<Self>,
3122    ) -> Task<Result<Vec<Location>>> {
3123        let position = position.to_point_utf16(buffer.read(cx));
3124        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3125    }
3126
3127    pub fn document_highlights<T: ToPointUtf16>(
3128        &self,
3129        buffer: &ModelHandle<Buffer>,
3130        position: T,
3131        cx: &mut ModelContext<Self>,
3132    ) -> Task<Result<Vec<DocumentHighlight>>> {
3133        let position = position.to_point_utf16(buffer.read(cx));
3134
3135        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3136    }
3137
3138    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3139        if self.is_local() {
3140            let mut requests = Vec::new();
3141            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3142                let worktree_id = *worktree_id;
3143                if let Some(worktree) = self
3144                    .worktree_for_id(worktree_id, cx)
3145                    .and_then(|worktree| worktree.read(cx).as_local())
3146                {
3147                    if let Some(LanguageServerState::Running { adapter, server }) =
3148                        self.language_servers.get(server_id)
3149                    {
3150                        let adapter = adapter.clone();
3151                        let worktree_abs_path = worktree.abs_path().clone();
3152                        requests.push(
3153                            server
3154                                .request::<lsp::request::WorkspaceSymbol>(
3155                                    lsp::WorkspaceSymbolParams {
3156                                        query: query.to_string(),
3157                                        ..Default::default()
3158                                    },
3159                                )
3160                                .log_err()
3161                                .map(move |response| {
3162                                    (
3163                                        adapter,
3164                                        worktree_id,
3165                                        worktree_abs_path,
3166                                        response.unwrap_or_default(),
3167                                    )
3168                                }),
3169                        );
3170                    }
3171                }
3172            }
3173
3174            cx.spawn_weak(|this, cx| async move {
3175                let responses = futures::future::join_all(requests).await;
3176                let this = if let Some(this) = this.upgrade(&cx) {
3177                    this
3178                } else {
3179                    return Ok(Default::default());
3180                };
3181                this.read_with(&cx, |this, cx| {
3182                    let mut symbols = Vec::new();
3183                    for (adapter, source_worktree_id, worktree_abs_path, response) in responses {
3184                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3185                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3186                            let mut worktree_id = source_worktree_id;
3187                            let path;
3188                            if let Some((worktree, rel_path)) =
3189                                this.find_local_worktree(&abs_path, cx)
3190                            {
3191                                worktree_id = worktree.read(cx).id();
3192                                path = rel_path;
3193                            } else {
3194                                path = relativize_path(&worktree_abs_path, &abs_path);
3195                            }
3196
3197                            let label = this
3198                                .languages
3199                                .select_language(&path)
3200                                .and_then(|language| {
3201                                    language.label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3202                                })
3203                                .unwrap_or_else(|| CodeLabel::plain(lsp_symbol.name.clone(), None));
3204                            let signature = this.symbol_signature(worktree_id, &path);
3205
3206                            Some(Symbol {
3207                                source_worktree_id,
3208                                worktree_id,
3209                                language_server_name: adapter.name(),
3210                                name: lsp_symbol.name,
3211                                kind: lsp_symbol.kind,
3212                                label,
3213                                path,
3214                                range: range_from_lsp(lsp_symbol.location.range),
3215                                signature,
3216                            })
3217                        }));
3218                    }
3219                    Ok(symbols)
3220                })
3221            })
3222        } else if let Some(project_id) = self.remote_id() {
3223            let request = self.client.request(proto::GetProjectSymbols {
3224                project_id,
3225                query: query.to_string(),
3226            });
3227            cx.spawn_weak(|this, cx| async move {
3228                let response = request.await?;
3229                let mut symbols = Vec::new();
3230                if let Some(this) = this.upgrade(&cx) {
3231                    this.read_with(&cx, |this, _| {
3232                        symbols.extend(
3233                            response
3234                                .symbols
3235                                .into_iter()
3236                                .filter_map(|symbol| this.deserialize_symbol(symbol).log_err()),
3237                        );
3238                    })
3239                }
3240                Ok(symbols)
3241            })
3242        } else {
3243            Task::ready(Ok(Default::default()))
3244        }
3245    }
3246
3247    pub fn open_buffer_for_symbol(
3248        &mut self,
3249        symbol: &Symbol,
3250        cx: &mut ModelContext<Self>,
3251    ) -> Task<Result<ModelHandle<Buffer>>> {
3252        if self.is_local() {
3253            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3254                symbol.source_worktree_id,
3255                symbol.language_server_name.clone(),
3256            )) {
3257                *id
3258            } else {
3259                return Task::ready(Err(anyhow!(
3260                    "language server for worktree and language not found"
3261                )));
3262            };
3263
3264            let worktree_abs_path = if let Some(worktree_abs_path) = self
3265                .worktree_for_id(symbol.worktree_id, cx)
3266                .and_then(|worktree| worktree.read(cx).as_local())
3267                .map(|local_worktree| local_worktree.abs_path())
3268            {
3269                worktree_abs_path
3270            } else {
3271                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3272            };
3273            let symbol_abs_path = worktree_abs_path.join(&symbol.path);
3274            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3275                uri
3276            } else {
3277                return Task::ready(Err(anyhow!("invalid symbol path")));
3278            };
3279
3280            self.open_local_buffer_via_lsp(
3281                symbol_uri,
3282                language_server_id,
3283                symbol.language_server_name.clone(),
3284                cx,
3285            )
3286        } else if let Some(project_id) = self.remote_id() {
3287            let request = self.client.request(proto::OpenBufferForSymbol {
3288                project_id,
3289                symbol: Some(serialize_symbol(symbol)),
3290            });
3291            cx.spawn(|this, mut cx| async move {
3292                let response = request.await?;
3293                let buffer = response.buffer.ok_or_else(|| anyhow!("invalid buffer"))?;
3294                this.update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
3295                    .await
3296            })
3297        } else {
3298            Task::ready(Err(anyhow!("project does not have a remote id")))
3299        }
3300    }
3301
3302    pub fn hover<T: ToPointUtf16>(
3303        &self,
3304        buffer: &ModelHandle<Buffer>,
3305        position: T,
3306        cx: &mut ModelContext<Self>,
3307    ) -> Task<Result<Option<Hover>>> {
3308        let position = position.to_point_utf16(buffer.read(cx));
3309        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3310    }
3311
3312    pub fn completions<T: ToPointUtf16>(
3313        &self,
3314        source_buffer_handle: &ModelHandle<Buffer>,
3315        position: T,
3316        cx: &mut ModelContext<Self>,
3317    ) -> Task<Result<Vec<Completion>>> {
3318        let source_buffer_handle = source_buffer_handle.clone();
3319        let source_buffer = source_buffer_handle.read(cx);
3320        let buffer_id = source_buffer.remote_id();
3321        let language = source_buffer.language().cloned();
3322        let worktree;
3323        let buffer_abs_path;
3324        if let Some(file) = File::from_dyn(source_buffer.file()) {
3325            worktree = file.worktree.clone();
3326            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3327        } else {
3328            return Task::ready(Ok(Default::default()));
3329        };
3330
3331        let position = position.to_point_utf16(source_buffer);
3332        let anchor = source_buffer.anchor_after(position);
3333
3334        if worktree.read(cx).as_local().is_some() {
3335            let buffer_abs_path = buffer_abs_path.unwrap();
3336            let lang_server =
3337                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3338                    server.clone()
3339                } else {
3340                    return Task::ready(Ok(Default::default()));
3341                };
3342
3343            cx.spawn(|_, cx| async move {
3344                let completions = lang_server
3345                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3346                        text_document_position: lsp::TextDocumentPositionParams::new(
3347                            lsp::TextDocumentIdentifier::new(
3348                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3349                            ),
3350                            point_to_lsp(position),
3351                        ),
3352                        context: Default::default(),
3353                        work_done_progress_params: Default::default(),
3354                        partial_result_params: Default::default(),
3355                    })
3356                    .await
3357                    .context("lsp completion request failed")?;
3358
3359                let completions = if let Some(completions) = completions {
3360                    match completions {
3361                        lsp::CompletionResponse::Array(completions) => completions,
3362                        lsp::CompletionResponse::List(list) => list.items,
3363                    }
3364                } else {
3365                    Default::default()
3366                };
3367
3368                source_buffer_handle.read_with(&cx, |this, _| {
3369                    let snapshot = this.snapshot();
3370                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3371                    let mut range_for_token = None;
3372                    Ok(completions
3373                        .into_iter()
3374                        .filter_map(|lsp_completion| {
3375                            // For now, we can only handle additional edits if they are returned
3376                            // when resolving the completion, not if they are present initially.
3377                            if lsp_completion
3378                                .additional_text_edits
3379                                .as_ref()
3380                                .map_or(false, |edits| !edits.is_empty())
3381                            {
3382                                return None;
3383                            }
3384
3385                            let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3386                            {
3387                                // If the language server provides a range to overwrite, then
3388                                // check that the range is valid.
3389                                Some(lsp::CompletionTextEdit::Edit(edit)) => {
3390                                    let range = range_from_lsp(edit.range);
3391                                    let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3392                                    let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3393                                    if start != range.start || end != range.end {
3394                                        log::info!("completion out of expected range");
3395                                        return None;
3396                                    }
3397                                    (
3398                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3399                                        edit.new_text.clone(),
3400                                    )
3401                                }
3402                                // If the language server does not provide a range, then infer
3403                                // the range based on the syntax tree.
3404                                None => {
3405                                    if position != clipped_position {
3406                                        log::info!("completion out of expected range");
3407                                        return None;
3408                                    }
3409                                    let Range { start, end } = range_for_token
3410                                        .get_or_insert_with(|| {
3411                                            let offset = position.to_offset(&snapshot);
3412                                            let (range, kind) = snapshot.surrounding_word(offset);
3413                                            if kind == Some(CharKind::Word) {
3414                                                range
3415                                            } else {
3416                                                offset..offset
3417                                            }
3418                                        })
3419                                        .clone();
3420                                    let text = lsp_completion
3421                                        .insert_text
3422                                        .as_ref()
3423                                        .unwrap_or(&lsp_completion.label)
3424                                        .clone();
3425                                    (
3426                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3427                                        text.clone(),
3428                                    )
3429                                }
3430                                Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3431                                    log::info!("unsupported insert/replace completion");
3432                                    return None;
3433                                }
3434                            };
3435
3436                            LineEnding::normalize(&mut new_text);
3437                            Some(Completion {
3438                                old_range,
3439                                new_text,
3440                                label: language
3441                                    .as_ref()
3442                                    .and_then(|l| l.label_for_completion(&lsp_completion))
3443                                    .unwrap_or_else(|| {
3444                                        CodeLabel::plain(
3445                                            lsp_completion.label.clone(),
3446                                            lsp_completion.filter_text.as_deref(),
3447                                        )
3448                                    }),
3449                                lsp_completion,
3450                            })
3451                        })
3452                        .collect())
3453                })
3454            })
3455        } else if let Some(project_id) = self.remote_id() {
3456            let rpc = self.client.clone();
3457            let message = proto::GetCompletions {
3458                project_id,
3459                buffer_id,
3460                position: Some(language::proto::serialize_anchor(&anchor)),
3461                version: serialize_version(&source_buffer.version()),
3462            };
3463            cx.spawn_weak(|_, mut cx| async move {
3464                let response = rpc.request(message).await?;
3465
3466                source_buffer_handle
3467                    .update(&mut cx, |buffer, _| {
3468                        buffer.wait_for_version(deserialize_version(response.version))
3469                    })
3470                    .await;
3471
3472                response
3473                    .completions
3474                    .into_iter()
3475                    .map(|completion| {
3476                        language::proto::deserialize_completion(completion, language.as_ref())
3477                    })
3478                    .collect()
3479            })
3480        } else {
3481            Task::ready(Ok(Default::default()))
3482        }
3483    }
3484
3485    pub fn apply_additional_edits_for_completion(
3486        &self,
3487        buffer_handle: ModelHandle<Buffer>,
3488        completion: Completion,
3489        push_to_history: bool,
3490        cx: &mut ModelContext<Self>,
3491    ) -> Task<Result<Option<Transaction>>> {
3492        let buffer = buffer_handle.read(cx);
3493        let buffer_id = buffer.remote_id();
3494
3495        if self.is_local() {
3496            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3497            {
3498                server.clone()
3499            } else {
3500                return Task::ready(Ok(Default::default()));
3501            };
3502
3503            cx.spawn(|this, mut cx| async move {
3504                let resolved_completion = lang_server
3505                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3506                    .await?;
3507                if let Some(edits) = resolved_completion.additional_text_edits {
3508                    let edits = this
3509                        .update(&mut cx, |this, cx| {
3510                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3511                        })
3512                        .await?;
3513                    buffer_handle.update(&mut cx, |buffer, cx| {
3514                        buffer.finalize_last_transaction();
3515                        buffer.start_transaction();
3516                        for (range, text) in edits {
3517                            buffer.edit([(range, text)], cx);
3518                        }
3519                        let transaction = if buffer.end_transaction(cx).is_some() {
3520                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3521                            if !push_to_history {
3522                                buffer.forget_transaction(transaction.id);
3523                            }
3524                            Some(transaction)
3525                        } else {
3526                            None
3527                        };
3528                        Ok(transaction)
3529                    })
3530                } else {
3531                    Ok(None)
3532                }
3533            })
3534        } else if let Some(project_id) = self.remote_id() {
3535            let client = self.client.clone();
3536            cx.spawn(|_, mut cx| async move {
3537                let response = client
3538                    .request(proto::ApplyCompletionAdditionalEdits {
3539                        project_id,
3540                        buffer_id,
3541                        completion: Some(language::proto::serialize_completion(&completion)),
3542                    })
3543                    .await?;
3544
3545                if let Some(transaction) = response.transaction {
3546                    let transaction = language::proto::deserialize_transaction(transaction)?;
3547                    buffer_handle
3548                        .update(&mut cx, |buffer, _| {
3549                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3550                        })
3551                        .await;
3552                    if push_to_history {
3553                        buffer_handle.update(&mut cx, |buffer, _| {
3554                            buffer.push_transaction(transaction.clone(), Instant::now());
3555                        });
3556                    }
3557                    Ok(Some(transaction))
3558                } else {
3559                    Ok(None)
3560                }
3561            })
3562        } else {
3563            Task::ready(Err(anyhow!("project does not have a remote id")))
3564        }
3565    }
3566
3567    pub fn code_actions<T: Clone + ToOffset>(
3568        &self,
3569        buffer_handle: &ModelHandle<Buffer>,
3570        range: Range<T>,
3571        cx: &mut ModelContext<Self>,
3572    ) -> Task<Result<Vec<CodeAction>>> {
3573        let buffer_handle = buffer_handle.clone();
3574        let buffer = buffer_handle.read(cx);
3575        let snapshot = buffer.snapshot();
3576        let relevant_diagnostics = snapshot
3577            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3578            .map(|entry| entry.to_lsp_diagnostic_stub())
3579            .collect();
3580        let buffer_id = buffer.remote_id();
3581        let worktree;
3582        let buffer_abs_path;
3583        if let Some(file) = File::from_dyn(buffer.file()) {
3584            worktree = file.worktree.clone();
3585            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3586        } else {
3587            return Task::ready(Ok(Default::default()));
3588        };
3589        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3590
3591        if worktree.read(cx).as_local().is_some() {
3592            let buffer_abs_path = buffer_abs_path.unwrap();
3593            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3594            {
3595                server.clone()
3596            } else {
3597                return Task::ready(Ok(Default::default()));
3598            };
3599
3600            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3601            cx.foreground().spawn(async move {
3602                if !lang_server.capabilities().code_action_provider.is_some() {
3603                    return Ok(Default::default());
3604                }
3605
3606                Ok(lang_server
3607                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3608                        text_document: lsp::TextDocumentIdentifier::new(
3609                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3610                        ),
3611                        range: lsp_range,
3612                        work_done_progress_params: Default::default(),
3613                        partial_result_params: Default::default(),
3614                        context: lsp::CodeActionContext {
3615                            diagnostics: relevant_diagnostics,
3616                            only: Some(vec![
3617                                lsp::CodeActionKind::QUICKFIX,
3618                                lsp::CodeActionKind::REFACTOR,
3619                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3620                                lsp::CodeActionKind::SOURCE,
3621                            ]),
3622                        },
3623                    })
3624                    .await?
3625                    .unwrap_or_default()
3626                    .into_iter()
3627                    .filter_map(|entry| {
3628                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3629                            Some(CodeAction {
3630                                range: range.clone(),
3631                                lsp_action,
3632                            })
3633                        } else {
3634                            None
3635                        }
3636                    })
3637                    .collect())
3638            })
3639        } else if let Some(project_id) = self.remote_id() {
3640            let rpc = self.client.clone();
3641            let version = buffer.version();
3642            cx.spawn_weak(|_, mut cx| async move {
3643                let response = rpc
3644                    .request(proto::GetCodeActions {
3645                        project_id,
3646                        buffer_id,
3647                        start: Some(language::proto::serialize_anchor(&range.start)),
3648                        end: Some(language::proto::serialize_anchor(&range.end)),
3649                        version: serialize_version(&version),
3650                    })
3651                    .await?;
3652
3653                buffer_handle
3654                    .update(&mut cx, |buffer, _| {
3655                        buffer.wait_for_version(deserialize_version(response.version))
3656                    })
3657                    .await;
3658
3659                response
3660                    .actions
3661                    .into_iter()
3662                    .map(language::proto::deserialize_code_action)
3663                    .collect()
3664            })
3665        } else {
3666            Task::ready(Ok(Default::default()))
3667        }
3668    }
3669
3670    pub fn apply_code_action(
3671        &self,
3672        buffer_handle: ModelHandle<Buffer>,
3673        mut action: CodeAction,
3674        push_to_history: bool,
3675        cx: &mut ModelContext<Self>,
3676    ) -> Task<Result<ProjectTransaction>> {
3677        if self.is_local() {
3678            let buffer = buffer_handle.read(cx);
3679            let (lsp_adapter, lang_server) =
3680                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3681                    (adapter.clone(), server.clone())
3682                } else {
3683                    return Task::ready(Ok(Default::default()));
3684                };
3685            let range = action.range.to_point_utf16(buffer);
3686
3687            cx.spawn(|this, mut cx| async move {
3688                if let Some(lsp_range) = action
3689                    .lsp_action
3690                    .data
3691                    .as_mut()
3692                    .and_then(|d| d.get_mut("codeActionParams"))
3693                    .and_then(|d| d.get_mut("range"))
3694                {
3695                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3696                    action.lsp_action = lang_server
3697                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3698                        .await?;
3699                } else {
3700                    let actions = this
3701                        .update(&mut cx, |this, cx| {
3702                            this.code_actions(&buffer_handle, action.range, cx)
3703                        })
3704                        .await?;
3705                    action.lsp_action = actions
3706                        .into_iter()
3707                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3708                        .ok_or_else(|| anyhow!("code action is outdated"))?
3709                        .lsp_action;
3710                }
3711
3712                if let Some(edit) = action.lsp_action.edit {
3713                    if edit.changes.is_some() || edit.document_changes.is_some() {
3714                        return Self::deserialize_workspace_edit(
3715                            this,
3716                            edit,
3717                            push_to_history,
3718                            lsp_adapter.clone(),
3719                            lang_server.clone(),
3720                            &mut cx,
3721                        )
3722                        .await;
3723                    }
3724                }
3725
3726                if let Some(command) = action.lsp_action.command {
3727                    this.update(&mut cx, |this, _| {
3728                        this.last_workspace_edits_by_language_server
3729                            .remove(&lang_server.server_id());
3730                    });
3731                    lang_server
3732                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3733                            command: command.command,
3734                            arguments: command.arguments.unwrap_or_default(),
3735                            ..Default::default()
3736                        })
3737                        .await?;
3738                    return Ok(this.update(&mut cx, |this, _| {
3739                        this.last_workspace_edits_by_language_server
3740                            .remove(&lang_server.server_id())
3741                            .unwrap_or_default()
3742                    }));
3743                }
3744
3745                Ok(ProjectTransaction::default())
3746            })
3747        } else if let Some(project_id) = self.remote_id() {
3748            let client = self.client.clone();
3749            let request = proto::ApplyCodeAction {
3750                project_id,
3751                buffer_id: buffer_handle.read(cx).remote_id(),
3752                action: Some(language::proto::serialize_code_action(&action)),
3753            };
3754            cx.spawn(|this, mut cx| async move {
3755                let response = client
3756                    .request(request)
3757                    .await?
3758                    .transaction
3759                    .ok_or_else(|| anyhow!("missing transaction"))?;
3760                this.update(&mut cx, |this, cx| {
3761                    this.deserialize_project_transaction(response, push_to_history, cx)
3762                })
3763                .await
3764            })
3765        } else {
3766            Task::ready(Err(anyhow!("project does not have a remote id")))
3767        }
3768    }
3769
3770    async fn deserialize_workspace_edit(
3771        this: ModelHandle<Self>,
3772        edit: lsp::WorkspaceEdit,
3773        push_to_history: bool,
3774        lsp_adapter: Arc<dyn LspAdapter>,
3775        language_server: Arc<LanguageServer>,
3776        cx: &mut AsyncAppContext,
3777    ) -> Result<ProjectTransaction> {
3778        let fs = this.read_with(cx, |this, _| this.fs.clone());
3779        let mut operations = Vec::new();
3780        if let Some(document_changes) = edit.document_changes {
3781            match document_changes {
3782                lsp::DocumentChanges::Edits(edits) => {
3783                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3784                }
3785                lsp::DocumentChanges::Operations(ops) => operations = ops,
3786            }
3787        } else if let Some(changes) = edit.changes {
3788            operations.extend(changes.into_iter().map(|(uri, edits)| {
3789                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3790                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3791                        uri,
3792                        version: None,
3793                    },
3794                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3795                })
3796            }));
3797        }
3798
3799        let mut project_transaction = ProjectTransaction::default();
3800        for operation in operations {
3801            match operation {
3802                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3803                    let abs_path = op
3804                        .uri
3805                        .to_file_path()
3806                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3807
3808                    if let Some(parent_path) = abs_path.parent() {
3809                        fs.create_dir(parent_path).await?;
3810                    }
3811                    if abs_path.ends_with("/") {
3812                        fs.create_dir(&abs_path).await?;
3813                    } else {
3814                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3815                            .await?;
3816                    }
3817                }
3818                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3819                    let source_abs_path = op
3820                        .old_uri
3821                        .to_file_path()
3822                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3823                    let target_abs_path = op
3824                        .new_uri
3825                        .to_file_path()
3826                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3827                    fs.rename(
3828                        &source_abs_path,
3829                        &target_abs_path,
3830                        op.options.map(Into::into).unwrap_or_default(),
3831                    )
3832                    .await?;
3833                }
3834                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3835                    let abs_path = op
3836                        .uri
3837                        .to_file_path()
3838                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3839                    let options = op.options.map(Into::into).unwrap_or_default();
3840                    if abs_path.ends_with("/") {
3841                        fs.remove_dir(&abs_path, options).await?;
3842                    } else {
3843                        fs.remove_file(&abs_path, options).await?;
3844                    }
3845                }
3846                lsp::DocumentChangeOperation::Edit(op) => {
3847                    let buffer_to_edit = this
3848                        .update(cx, |this, cx| {
3849                            this.open_local_buffer_via_lsp(
3850                                op.text_document.uri,
3851                                language_server.server_id(),
3852                                lsp_adapter.name(),
3853                                cx,
3854                            )
3855                        })
3856                        .await?;
3857
3858                    let edits = this
3859                        .update(cx, |this, cx| {
3860                            let edits = op.edits.into_iter().map(|edit| match edit {
3861                                lsp::OneOf::Left(edit) => edit,
3862                                lsp::OneOf::Right(edit) => edit.text_edit,
3863                            });
3864                            this.edits_from_lsp(
3865                                &buffer_to_edit,
3866                                edits,
3867                                op.text_document.version,
3868                                cx,
3869                            )
3870                        })
3871                        .await?;
3872
3873                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3874                        buffer.finalize_last_transaction();
3875                        buffer.start_transaction();
3876                        for (range, text) in edits {
3877                            buffer.edit([(range, text)], cx);
3878                        }
3879                        let transaction = if buffer.end_transaction(cx).is_some() {
3880                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3881                            if !push_to_history {
3882                                buffer.forget_transaction(transaction.id);
3883                            }
3884                            Some(transaction)
3885                        } else {
3886                            None
3887                        };
3888
3889                        transaction
3890                    });
3891                    if let Some(transaction) = transaction {
3892                        project_transaction.0.insert(buffer_to_edit, transaction);
3893                    }
3894                }
3895            }
3896        }
3897
3898        Ok(project_transaction)
3899    }
3900
3901    pub fn prepare_rename<T: ToPointUtf16>(
3902        &self,
3903        buffer: ModelHandle<Buffer>,
3904        position: T,
3905        cx: &mut ModelContext<Self>,
3906    ) -> Task<Result<Option<Range<Anchor>>>> {
3907        let position = position.to_point_utf16(buffer.read(cx));
3908        self.request_lsp(buffer, PrepareRename { position }, cx)
3909    }
3910
3911    pub fn perform_rename<T: ToPointUtf16>(
3912        &self,
3913        buffer: ModelHandle<Buffer>,
3914        position: T,
3915        new_name: String,
3916        push_to_history: bool,
3917        cx: &mut ModelContext<Self>,
3918    ) -> Task<Result<ProjectTransaction>> {
3919        let position = position.to_point_utf16(buffer.read(cx));
3920        self.request_lsp(
3921            buffer,
3922            PerformRename {
3923                position,
3924                new_name,
3925                push_to_history,
3926            },
3927            cx,
3928        )
3929    }
3930
3931    pub fn search(
3932        &self,
3933        query: SearchQuery,
3934        cx: &mut ModelContext<Self>,
3935    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3936        if self.is_local() {
3937            let snapshots = self
3938                .visible_worktrees(cx)
3939                .filter_map(|tree| {
3940                    let tree = tree.read(cx).as_local()?;
3941                    Some(tree.snapshot())
3942                })
3943                .collect::<Vec<_>>();
3944
3945            let background = cx.background().clone();
3946            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3947            if path_count == 0 {
3948                return Task::ready(Ok(Default::default()));
3949            }
3950            let workers = background.num_cpus().min(path_count);
3951            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3952            cx.background()
3953                .spawn({
3954                    let fs = self.fs.clone();
3955                    let background = cx.background().clone();
3956                    let query = query.clone();
3957                    async move {
3958                        let fs = &fs;
3959                        let query = &query;
3960                        let matching_paths_tx = &matching_paths_tx;
3961                        let paths_per_worker = (path_count + workers - 1) / workers;
3962                        let snapshots = &snapshots;
3963                        background
3964                            .scoped(|scope| {
3965                                for worker_ix in 0..workers {
3966                                    let worker_start_ix = worker_ix * paths_per_worker;
3967                                    let worker_end_ix = worker_start_ix + paths_per_worker;
3968                                    scope.spawn(async move {
3969                                        let mut snapshot_start_ix = 0;
3970                                        let mut abs_path = PathBuf::new();
3971                                        for snapshot in snapshots {
3972                                            let snapshot_end_ix =
3973                                                snapshot_start_ix + snapshot.visible_file_count();
3974                                            if worker_end_ix <= snapshot_start_ix {
3975                                                break;
3976                                            } else if worker_start_ix > snapshot_end_ix {
3977                                                snapshot_start_ix = snapshot_end_ix;
3978                                                continue;
3979                                            } else {
3980                                                let start_in_snapshot = worker_start_ix
3981                                                    .saturating_sub(snapshot_start_ix);
3982                                                let end_in_snapshot =
3983                                                    cmp::min(worker_end_ix, snapshot_end_ix)
3984                                                        - snapshot_start_ix;
3985
3986                                                for entry in snapshot
3987                                                    .files(false, start_in_snapshot)
3988                                                    .take(end_in_snapshot - start_in_snapshot)
3989                                                {
3990                                                    if matching_paths_tx.is_closed() {
3991                                                        break;
3992                                                    }
3993
3994                                                    abs_path.clear();
3995                                                    abs_path.push(&snapshot.abs_path());
3996                                                    abs_path.push(&entry.path);
3997                                                    let matches = if let Some(file) =
3998                                                        fs.open_sync(&abs_path).await.log_err()
3999                                                    {
4000                                                        query.detect(file).unwrap_or(false)
4001                                                    } else {
4002                                                        false
4003                                                    };
4004
4005                                                    if matches {
4006                                                        let project_path =
4007                                                            (snapshot.id(), entry.path.clone());
4008                                                        if matching_paths_tx
4009                                                            .send(project_path)
4010                                                            .await
4011                                                            .is_err()
4012                                                        {
4013                                                            break;
4014                                                        }
4015                                                    }
4016                                                }
4017
4018                                                snapshot_start_ix = snapshot_end_ix;
4019                                            }
4020                                        }
4021                                    });
4022                                }
4023                            })
4024                            .await;
4025                    }
4026                })
4027                .detach();
4028
4029            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4030            let open_buffers = self
4031                .opened_buffers
4032                .values()
4033                .filter_map(|b| b.upgrade(cx))
4034                .collect::<HashSet<_>>();
4035            cx.spawn(|this, cx| async move {
4036                for buffer in &open_buffers {
4037                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4038                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4039                }
4040
4041                let open_buffers = Rc::new(RefCell::new(open_buffers));
4042                while let Some(project_path) = matching_paths_rx.next().await {
4043                    if buffers_tx.is_closed() {
4044                        break;
4045                    }
4046
4047                    let this = this.clone();
4048                    let open_buffers = open_buffers.clone();
4049                    let buffers_tx = buffers_tx.clone();
4050                    cx.spawn(|mut cx| async move {
4051                        if let Some(buffer) = this
4052                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4053                            .await
4054                            .log_err()
4055                        {
4056                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4057                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4058                                buffers_tx.send((buffer, snapshot)).await?;
4059                            }
4060                        }
4061
4062                        Ok::<_, anyhow::Error>(())
4063                    })
4064                    .detach();
4065                }
4066
4067                Ok::<_, anyhow::Error>(())
4068            })
4069            .detach_and_log_err(cx);
4070
4071            let background = cx.background().clone();
4072            cx.background().spawn(async move {
4073                let query = &query;
4074                let mut matched_buffers = Vec::new();
4075                for _ in 0..workers {
4076                    matched_buffers.push(HashMap::default());
4077                }
4078                background
4079                    .scoped(|scope| {
4080                        for worker_matched_buffers in matched_buffers.iter_mut() {
4081                            let mut buffers_rx = buffers_rx.clone();
4082                            scope.spawn(async move {
4083                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4084                                    let buffer_matches = query
4085                                        .search(snapshot.as_rope())
4086                                        .await
4087                                        .iter()
4088                                        .map(|range| {
4089                                            snapshot.anchor_before(range.start)
4090                                                ..snapshot.anchor_after(range.end)
4091                                        })
4092                                        .collect::<Vec<_>>();
4093                                    if !buffer_matches.is_empty() {
4094                                        worker_matched_buffers
4095                                            .insert(buffer.clone(), buffer_matches);
4096                                    }
4097                                }
4098                            });
4099                        }
4100                    })
4101                    .await;
4102                Ok(matched_buffers.into_iter().flatten().collect())
4103            })
4104        } else if let Some(project_id) = self.remote_id() {
4105            let request = self.client.request(query.to_proto(project_id));
4106            cx.spawn(|this, mut cx| async move {
4107                let response = request.await?;
4108                let mut result = HashMap::default();
4109                for location in response.locations {
4110                    let buffer = location.buffer.ok_or_else(|| anyhow!("missing buffer"))?;
4111                    let target_buffer = this
4112                        .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
4113                        .await?;
4114                    let start = location
4115                        .start
4116                        .and_then(deserialize_anchor)
4117                        .ok_or_else(|| anyhow!("missing target start"))?;
4118                    let end = location
4119                        .end
4120                        .and_then(deserialize_anchor)
4121                        .ok_or_else(|| anyhow!("missing target end"))?;
4122                    result
4123                        .entry(target_buffer)
4124                        .or_insert(Vec::new())
4125                        .push(start..end)
4126                }
4127                Ok(result)
4128            })
4129        } else {
4130            Task::ready(Ok(Default::default()))
4131        }
4132    }
4133
4134    fn request_lsp<R: LspCommand>(
4135        &self,
4136        buffer_handle: ModelHandle<Buffer>,
4137        request: R,
4138        cx: &mut ModelContext<Self>,
4139    ) -> Task<Result<R::Response>>
4140    where
4141        <R::LspRequest as lsp::request::Request>::Result: Send,
4142    {
4143        let buffer = buffer_handle.read(cx);
4144        if self.is_local() {
4145            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4146            if let Some((file, language_server)) = file.zip(
4147                self.language_server_for_buffer(buffer, cx)
4148                    .map(|(_, server)| server.clone()),
4149            ) {
4150                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4151                return cx.spawn(|this, cx| async move {
4152                    if !request.check_capabilities(&language_server.capabilities()) {
4153                        return Ok(Default::default());
4154                    }
4155
4156                    let response = language_server
4157                        .request::<R::LspRequest>(lsp_params)
4158                        .await
4159                        .context("lsp request failed")?;
4160                    request
4161                        .response_from_lsp(response, this, buffer_handle, cx)
4162                        .await
4163                });
4164            }
4165        } else if let Some(project_id) = self.remote_id() {
4166            let rpc = self.client.clone();
4167            let message = request.to_proto(project_id, buffer);
4168            return cx.spawn(|this, cx| async move {
4169                let response = rpc.request(message).await?;
4170                request
4171                    .response_from_proto(response, this, buffer_handle, cx)
4172                    .await
4173            });
4174        }
4175        Task::ready(Ok(Default::default()))
4176    }
4177
4178    pub fn find_or_create_local_worktree(
4179        &mut self,
4180        abs_path: impl AsRef<Path>,
4181        visible: bool,
4182        cx: &mut ModelContext<Self>,
4183    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4184        let abs_path = abs_path.as_ref();
4185        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4186            Task::ready(Ok((tree.clone(), relative_path.into())))
4187        } else {
4188            let worktree = self.create_local_worktree(abs_path, visible, cx);
4189            cx.foreground()
4190                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4191        }
4192    }
4193
4194    pub fn find_local_worktree(
4195        &self,
4196        abs_path: &Path,
4197        cx: &AppContext,
4198    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4199        for tree in &self.worktrees {
4200            if let Some(tree) = tree.upgrade(cx) {
4201                if let Some(relative_path) = tree
4202                    .read(cx)
4203                    .as_local()
4204                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4205                {
4206                    return Some((tree.clone(), relative_path.into()));
4207                }
4208            }
4209        }
4210        None
4211    }
4212
4213    pub fn is_shared(&self) -> bool {
4214        match &self.client_state {
4215            ProjectClientState::Local { is_shared, .. } => *is_shared,
4216            ProjectClientState::Remote { .. } => false,
4217        }
4218    }
4219
4220    fn create_local_worktree(
4221        &mut self,
4222        abs_path: impl AsRef<Path>,
4223        visible: bool,
4224        cx: &mut ModelContext<Self>,
4225    ) -> Task<Result<ModelHandle<Worktree>>> {
4226        let fs = self.fs.clone();
4227        let client = self.client.clone();
4228        let next_entry_id = self.next_entry_id.clone();
4229        let path: Arc<Path> = abs_path.as_ref().into();
4230        let task = self
4231            .loading_local_worktrees
4232            .entry(path.clone())
4233            .or_insert_with(|| {
4234                cx.spawn(|project, mut cx| {
4235                    async move {
4236                        let worktree = Worktree::local(
4237                            client.clone(),
4238                            path.clone(),
4239                            visible,
4240                            fs,
4241                            next_entry_id,
4242                            &mut cx,
4243                        )
4244                        .await;
4245                        project.update(&mut cx, |project, _| {
4246                            project.loading_local_worktrees.remove(&path);
4247                        });
4248                        let worktree = worktree?;
4249
4250                        let project_id = project.update(&mut cx, |project, cx| {
4251                            project.add_worktree(&worktree, cx);
4252                            project.shared_remote_id()
4253                        });
4254
4255                        if let Some(project_id) = project_id {
4256                            worktree
4257                                .update(&mut cx, |worktree, cx| {
4258                                    worktree.as_local_mut().unwrap().share(project_id, cx)
4259                                })
4260                                .await
4261                                .log_err();
4262                        }
4263
4264                        Ok(worktree)
4265                    }
4266                    .map_err(|err| Arc::new(err))
4267                })
4268                .shared()
4269            })
4270            .clone();
4271        cx.foreground().spawn(async move {
4272            match task.await {
4273                Ok(worktree) => Ok(worktree),
4274                Err(err) => Err(anyhow!("{}", err)),
4275            }
4276        })
4277    }
4278
4279    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4280        self.worktrees.retain(|worktree| {
4281            if let Some(worktree) = worktree.upgrade(cx) {
4282                let id = worktree.read(cx).id();
4283                if id == id_to_remove {
4284                    cx.emit(Event::WorktreeRemoved(id));
4285                    false
4286                } else {
4287                    true
4288                }
4289            } else {
4290                false
4291            }
4292        });
4293        self.metadata_changed(true, cx);
4294        cx.notify();
4295    }
4296
4297    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4298        cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
4299        if worktree.read(cx).is_local() {
4300            cx.subscribe(&worktree, |this, worktree, _, cx| {
4301                this.update_local_worktree_buffers(worktree, cx);
4302            })
4303            .detach();
4304        }
4305
4306        let push_strong_handle = {
4307            let worktree = worktree.read(cx);
4308            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4309        };
4310        if push_strong_handle {
4311            self.worktrees
4312                .push(WorktreeHandle::Strong(worktree.clone()));
4313        } else {
4314            self.worktrees
4315                .push(WorktreeHandle::Weak(worktree.downgrade()));
4316        }
4317
4318        self.metadata_changed(true, cx);
4319        cx.observe_release(&worktree, |this, worktree, cx| {
4320            this.remove_worktree(worktree.id(), cx);
4321            cx.notify();
4322        })
4323        .detach();
4324
4325        cx.emit(Event::WorktreeAdded);
4326        cx.notify();
4327    }
4328
4329    fn update_local_worktree_buffers(
4330        &mut self,
4331        worktree_handle: ModelHandle<Worktree>,
4332        cx: &mut ModelContext<Self>,
4333    ) {
4334        let snapshot = worktree_handle.read(cx).snapshot();
4335        let mut buffers_to_delete = Vec::new();
4336        let mut renamed_buffers = Vec::new();
4337        for (buffer_id, buffer) in &self.opened_buffers {
4338            if let Some(buffer) = buffer.upgrade(cx) {
4339                buffer.update(cx, |buffer, cx| {
4340                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4341                        if old_file.worktree != worktree_handle {
4342                            return;
4343                        }
4344
4345                        let new_file = if let Some(entry) = old_file
4346                            .entry_id
4347                            .and_then(|entry_id| snapshot.entry_for_id(entry_id))
4348                        {
4349                            File {
4350                                is_local: true,
4351                                entry_id: Some(entry.id),
4352                                mtime: entry.mtime,
4353                                path: entry.path.clone(),
4354                                worktree: worktree_handle.clone(),
4355                            }
4356                        } else if let Some(entry) =
4357                            snapshot.entry_for_path(old_file.path().as_ref())
4358                        {
4359                            File {
4360                                is_local: true,
4361                                entry_id: Some(entry.id),
4362                                mtime: entry.mtime,
4363                                path: entry.path.clone(),
4364                                worktree: worktree_handle.clone(),
4365                            }
4366                        } else {
4367                            File {
4368                                is_local: true,
4369                                entry_id: None,
4370                                path: old_file.path().clone(),
4371                                mtime: old_file.mtime(),
4372                                worktree: worktree_handle.clone(),
4373                            }
4374                        };
4375
4376                        let old_path = old_file.abs_path(cx);
4377                        if new_file.abs_path(cx) != old_path {
4378                            renamed_buffers.push((cx.handle(), old_path));
4379                        }
4380
4381                        if let Some(project_id) = self.shared_remote_id() {
4382                            self.client
4383                                .send(proto::UpdateBufferFile {
4384                                    project_id,
4385                                    buffer_id: *buffer_id as u64,
4386                                    file: Some(new_file.to_proto()),
4387                                })
4388                                .log_err();
4389                        }
4390                        buffer.file_updated(Arc::new(new_file), cx).detach();
4391                    }
4392                });
4393            } else {
4394                buffers_to_delete.push(*buffer_id);
4395            }
4396        }
4397
4398        for buffer_id in buffers_to_delete {
4399            self.opened_buffers.remove(&buffer_id);
4400        }
4401
4402        for (buffer, old_path) in renamed_buffers {
4403            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4404            self.assign_language_to_buffer(&buffer, cx);
4405            self.register_buffer_with_language_server(&buffer, cx);
4406        }
4407    }
4408
4409    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4410        let new_active_entry = entry.and_then(|project_path| {
4411            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4412            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4413            Some(entry.id)
4414        });
4415        if new_active_entry != self.active_entry {
4416            self.active_entry = new_active_entry;
4417            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4418        }
4419    }
4420
4421    pub fn language_servers_running_disk_based_diagnostics<'a>(
4422        &'a self,
4423    ) -> impl 'a + Iterator<Item = usize> {
4424        self.language_server_statuses
4425            .iter()
4426            .filter_map(|(id, status)| {
4427                if status.has_pending_diagnostic_updates {
4428                    Some(*id)
4429                } else {
4430                    None
4431                }
4432            })
4433    }
4434
4435    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4436        let mut summary = DiagnosticSummary::default();
4437        for (_, path_summary) in self.diagnostic_summaries(cx) {
4438            summary.error_count += path_summary.error_count;
4439            summary.warning_count += path_summary.warning_count;
4440        }
4441        summary
4442    }
4443
4444    pub fn diagnostic_summaries<'a>(
4445        &'a self,
4446        cx: &'a AppContext,
4447    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4448        self.visible_worktrees(cx).flat_map(move |worktree| {
4449            let worktree = worktree.read(cx);
4450            let worktree_id = worktree.id();
4451            worktree
4452                .diagnostic_summaries()
4453                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4454        })
4455    }
4456
4457    pub fn disk_based_diagnostics_started(
4458        &mut self,
4459        language_server_id: usize,
4460        cx: &mut ModelContext<Self>,
4461    ) {
4462        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4463    }
4464
4465    pub fn disk_based_diagnostics_finished(
4466        &mut self,
4467        language_server_id: usize,
4468        cx: &mut ModelContext<Self>,
4469    ) {
4470        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4471    }
4472
4473    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4474        self.active_entry
4475    }
4476
4477    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<ProjectEntryId> {
4478        self.worktree_for_id(path.worktree_id, cx)?
4479            .read(cx)
4480            .entry_for_path(&path.path)
4481            .map(|entry| entry.id)
4482    }
4483
4484    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4485        let worktree = self.worktree_for_entry(entry_id, cx)?;
4486        let worktree = worktree.read(cx);
4487        let worktree_id = worktree.id();
4488        let path = worktree.entry_for_id(entry_id)?.path.clone();
4489        Some(ProjectPath { worktree_id, path })
4490    }
4491
4492    // RPC message handlers
4493
4494    async fn handle_request_join_project(
4495        this: ModelHandle<Self>,
4496        message: TypedEnvelope<proto::RequestJoinProject>,
4497        _: Arc<Client>,
4498        mut cx: AsyncAppContext,
4499    ) -> Result<()> {
4500        let user_id = message.payload.requester_id;
4501        if this.read_with(&cx, |project, _| {
4502            project.collaborators.values().any(|c| c.user.id == user_id)
4503        }) {
4504            this.update(&mut cx, |this, cx| {
4505                this.respond_to_join_request(user_id, true, cx)
4506            });
4507        } else {
4508            let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4509            let user = user_store
4510                .update(&mut cx, |store, cx| store.fetch_user(user_id, cx))
4511                .await?;
4512            this.update(&mut cx, |_, cx| cx.emit(Event::ContactRequestedJoin(user)));
4513        }
4514        Ok(())
4515    }
4516
4517    async fn handle_unregister_project(
4518        this: ModelHandle<Self>,
4519        _: TypedEnvelope<proto::UnregisterProject>,
4520        _: Arc<Client>,
4521        mut cx: AsyncAppContext,
4522    ) -> Result<()> {
4523        this.update(&mut cx, |this, cx| this.removed_from_project(cx));
4524        Ok(())
4525    }
4526
4527    async fn handle_project_unshared(
4528        this: ModelHandle<Self>,
4529        _: TypedEnvelope<proto::ProjectUnshared>,
4530        _: Arc<Client>,
4531        mut cx: AsyncAppContext,
4532    ) -> Result<()> {
4533        this.update(&mut cx, |this, cx| this.unshared(cx));
4534        Ok(())
4535    }
4536
4537    async fn handle_add_collaborator(
4538        this: ModelHandle<Self>,
4539        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4540        _: Arc<Client>,
4541        mut cx: AsyncAppContext,
4542    ) -> Result<()> {
4543        let user_store = this.read_with(&cx, |this, _| this.user_store.clone());
4544        let collaborator = envelope
4545            .payload
4546            .collaborator
4547            .take()
4548            .ok_or_else(|| anyhow!("empty collaborator"))?;
4549
4550        let collaborator = Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
4551        this.update(&mut cx, |this, cx| {
4552            this.collaborators
4553                .insert(collaborator.peer_id, collaborator);
4554            cx.notify();
4555        });
4556
4557        Ok(())
4558    }
4559
4560    async fn handle_remove_collaborator(
4561        this: ModelHandle<Self>,
4562        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4563        _: Arc<Client>,
4564        mut cx: AsyncAppContext,
4565    ) -> Result<()> {
4566        this.update(&mut cx, |this, cx| {
4567            let peer_id = PeerId(envelope.payload.peer_id);
4568            let replica_id = this
4569                .collaborators
4570                .remove(&peer_id)
4571                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4572                .replica_id;
4573            for (_, buffer) in &this.opened_buffers {
4574                if let Some(buffer) = buffer.upgrade(cx) {
4575                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4576                }
4577            }
4578
4579            cx.emit(Event::CollaboratorLeft(peer_id));
4580            cx.notify();
4581            Ok(())
4582        })
4583    }
4584
4585    async fn handle_join_project_request_cancelled(
4586        this: ModelHandle<Self>,
4587        envelope: TypedEnvelope<proto::JoinProjectRequestCancelled>,
4588        _: Arc<Client>,
4589        mut cx: AsyncAppContext,
4590    ) -> Result<()> {
4591        let user = this
4592            .update(&mut cx, |this, cx| {
4593                this.user_store.update(cx, |user_store, cx| {
4594                    user_store.fetch_user(envelope.payload.requester_id, cx)
4595                })
4596            })
4597            .await?;
4598
4599        this.update(&mut cx, |_, cx| {
4600            cx.emit(Event::ContactCancelledJoinRequest(user));
4601        });
4602
4603        Ok(())
4604    }
4605
4606    async fn handle_update_project(
4607        this: ModelHandle<Self>,
4608        envelope: TypedEnvelope<proto::UpdateProject>,
4609        client: Arc<Client>,
4610        mut cx: AsyncAppContext,
4611    ) -> Result<()> {
4612        this.update(&mut cx, |this, cx| {
4613            let replica_id = this.replica_id();
4614            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4615
4616            let mut old_worktrees_by_id = this
4617                .worktrees
4618                .drain(..)
4619                .filter_map(|worktree| {
4620                    let worktree = worktree.upgrade(cx)?;
4621                    Some((worktree.read(cx).id(), worktree))
4622                })
4623                .collect::<HashMap<_, _>>();
4624
4625            for worktree in envelope.payload.worktrees {
4626                if let Some(old_worktree) =
4627                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4628                {
4629                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4630                } else {
4631                    let worktree =
4632                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4633                    this.add_worktree(&worktree, cx);
4634                }
4635            }
4636
4637            this.metadata_changed(true, cx);
4638            for (id, _) in old_worktrees_by_id {
4639                cx.emit(Event::WorktreeRemoved(id));
4640            }
4641
4642            Ok(())
4643        })
4644    }
4645
4646    async fn handle_update_worktree(
4647        this: ModelHandle<Self>,
4648        envelope: TypedEnvelope<proto::UpdateWorktree>,
4649        _: Arc<Client>,
4650        mut cx: AsyncAppContext,
4651    ) -> Result<()> {
4652        this.update(&mut cx, |this, cx| {
4653            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4654            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4655                worktree.update(cx, |worktree, _| {
4656                    let worktree = worktree.as_remote_mut().unwrap();
4657                    worktree.update_from_remote(envelope.payload);
4658                });
4659            }
4660            Ok(())
4661        })
4662    }
4663
4664    async fn handle_create_project_entry(
4665        this: ModelHandle<Self>,
4666        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4667        _: Arc<Client>,
4668        mut cx: AsyncAppContext,
4669    ) -> Result<proto::ProjectEntryResponse> {
4670        let worktree = this.update(&mut cx, |this, cx| {
4671            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4672            this.worktree_for_id(worktree_id, cx)
4673                .ok_or_else(|| anyhow!("worktree not found"))
4674        })?;
4675        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4676        let entry = worktree
4677            .update(&mut cx, |worktree, cx| {
4678                let worktree = worktree.as_local_mut().unwrap();
4679                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4680                worktree.create_entry(path, envelope.payload.is_directory, cx)
4681            })
4682            .await?;
4683        Ok(proto::ProjectEntryResponse {
4684            entry: Some((&entry).into()),
4685            worktree_scan_id: worktree_scan_id as u64,
4686        })
4687    }
4688
4689    async fn handle_rename_project_entry(
4690        this: ModelHandle<Self>,
4691        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4692        _: Arc<Client>,
4693        mut cx: AsyncAppContext,
4694    ) -> Result<proto::ProjectEntryResponse> {
4695        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4696        let worktree = this.read_with(&cx, |this, cx| {
4697            this.worktree_for_entry(entry_id, cx)
4698                .ok_or_else(|| anyhow!("worktree not found"))
4699        })?;
4700        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4701        let entry = worktree
4702            .update(&mut cx, |worktree, cx| {
4703                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4704                worktree
4705                    .as_local_mut()
4706                    .unwrap()
4707                    .rename_entry(entry_id, new_path, cx)
4708                    .ok_or_else(|| anyhow!("invalid entry"))
4709            })?
4710            .await?;
4711        Ok(proto::ProjectEntryResponse {
4712            entry: Some((&entry).into()),
4713            worktree_scan_id: worktree_scan_id as u64,
4714        })
4715    }
4716
4717    async fn handle_copy_project_entry(
4718        this: ModelHandle<Self>,
4719        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4720        _: Arc<Client>,
4721        mut cx: AsyncAppContext,
4722    ) -> Result<proto::ProjectEntryResponse> {
4723        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4724        let worktree = this.read_with(&cx, |this, cx| {
4725            this.worktree_for_entry(entry_id, cx)
4726                .ok_or_else(|| anyhow!("worktree not found"))
4727        })?;
4728        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4729        let entry = worktree
4730            .update(&mut cx, |worktree, cx| {
4731                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4732                worktree
4733                    .as_local_mut()
4734                    .unwrap()
4735                    .copy_entry(entry_id, new_path, cx)
4736                    .ok_or_else(|| anyhow!("invalid entry"))
4737            })?
4738            .await?;
4739        Ok(proto::ProjectEntryResponse {
4740            entry: Some((&entry).into()),
4741            worktree_scan_id: worktree_scan_id as u64,
4742        })
4743    }
4744
4745    async fn handle_delete_project_entry(
4746        this: ModelHandle<Self>,
4747        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4748        _: Arc<Client>,
4749        mut cx: AsyncAppContext,
4750    ) -> Result<proto::ProjectEntryResponse> {
4751        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4752        let worktree = this.read_with(&cx, |this, cx| {
4753            this.worktree_for_entry(entry_id, cx)
4754                .ok_or_else(|| anyhow!("worktree not found"))
4755        })?;
4756        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4757        worktree
4758            .update(&mut cx, |worktree, cx| {
4759                worktree
4760                    .as_local_mut()
4761                    .unwrap()
4762                    .delete_entry(entry_id, cx)
4763                    .ok_or_else(|| anyhow!("invalid entry"))
4764            })?
4765            .await?;
4766        Ok(proto::ProjectEntryResponse {
4767            entry: None,
4768            worktree_scan_id: worktree_scan_id as u64,
4769        })
4770    }
4771
4772    async fn handle_update_diagnostic_summary(
4773        this: ModelHandle<Self>,
4774        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4775        _: Arc<Client>,
4776        mut cx: AsyncAppContext,
4777    ) -> Result<()> {
4778        this.update(&mut cx, |this, cx| {
4779            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4780            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4781                if let Some(summary) = envelope.payload.summary {
4782                    let project_path = ProjectPath {
4783                        worktree_id,
4784                        path: Path::new(&summary.path).into(),
4785                    };
4786                    worktree.update(cx, |worktree, _| {
4787                        worktree
4788                            .as_remote_mut()
4789                            .unwrap()
4790                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4791                    });
4792                    cx.emit(Event::DiagnosticsUpdated {
4793                        language_server_id: summary.language_server_id as usize,
4794                        path: project_path,
4795                    });
4796                }
4797            }
4798            Ok(())
4799        })
4800    }
4801
4802    async fn handle_start_language_server(
4803        this: ModelHandle<Self>,
4804        envelope: TypedEnvelope<proto::StartLanguageServer>,
4805        _: Arc<Client>,
4806        mut cx: AsyncAppContext,
4807    ) -> Result<()> {
4808        let server = envelope
4809            .payload
4810            .server
4811            .ok_or_else(|| anyhow!("invalid server"))?;
4812        this.update(&mut cx, |this, cx| {
4813            this.language_server_statuses.insert(
4814                server.id as usize,
4815                LanguageServerStatus {
4816                    name: server.name,
4817                    pending_work: Default::default(),
4818                    has_pending_diagnostic_updates: false,
4819                    progress_tokens: Default::default(),
4820                },
4821            );
4822            cx.notify();
4823        });
4824        Ok(())
4825    }
4826
4827    async fn handle_update_language_server(
4828        this: ModelHandle<Self>,
4829        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4830        _: Arc<Client>,
4831        mut cx: AsyncAppContext,
4832    ) -> Result<()> {
4833        let language_server_id = envelope.payload.language_server_id as usize;
4834        match envelope
4835            .payload
4836            .variant
4837            .ok_or_else(|| anyhow!("invalid variant"))?
4838        {
4839            proto::update_language_server::Variant::WorkStart(payload) => {
4840                this.update(&mut cx, |this, cx| {
4841                    this.on_lsp_work_start(
4842                        language_server_id,
4843                        payload.token,
4844                        LanguageServerProgress {
4845                            message: payload.message,
4846                            percentage: payload.percentage.map(|p| p as usize),
4847                            last_update_at: Instant::now(),
4848                        },
4849                        cx,
4850                    );
4851                })
4852            }
4853            proto::update_language_server::Variant::WorkProgress(payload) => {
4854                this.update(&mut cx, |this, cx| {
4855                    this.on_lsp_work_progress(
4856                        language_server_id,
4857                        payload.token,
4858                        LanguageServerProgress {
4859                            message: payload.message,
4860                            percentage: payload.percentage.map(|p| p as usize),
4861                            last_update_at: Instant::now(),
4862                        },
4863                        cx,
4864                    );
4865                })
4866            }
4867            proto::update_language_server::Variant::WorkEnd(payload) => {
4868                this.update(&mut cx, |this, cx| {
4869                    this.on_lsp_work_end(language_server_id, payload.token, cx);
4870                })
4871            }
4872            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4873                this.update(&mut cx, |this, cx| {
4874                    this.disk_based_diagnostics_started(language_server_id, cx);
4875                })
4876            }
4877            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4878                this.update(&mut cx, |this, cx| {
4879                    this.disk_based_diagnostics_finished(language_server_id, cx)
4880                });
4881            }
4882        }
4883
4884        Ok(())
4885    }
4886
4887    async fn handle_update_buffer(
4888        this: ModelHandle<Self>,
4889        envelope: TypedEnvelope<proto::UpdateBuffer>,
4890        _: Arc<Client>,
4891        mut cx: AsyncAppContext,
4892    ) -> Result<()> {
4893        this.update(&mut cx, |this, cx| {
4894            let payload = envelope.payload.clone();
4895            let buffer_id = payload.buffer_id;
4896            let ops = payload
4897                .operations
4898                .into_iter()
4899                .map(|op| language::proto::deserialize_operation(op))
4900                .collect::<Result<Vec<_>, _>>()?;
4901            let is_remote = this.is_remote();
4902            match this.opened_buffers.entry(buffer_id) {
4903                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
4904                    OpenBuffer::Strong(buffer) => {
4905                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
4906                    }
4907                    OpenBuffer::Loading(operations) => operations.extend_from_slice(&ops),
4908                    OpenBuffer::Weak(_) => {}
4909                },
4910                hash_map::Entry::Vacant(e) => {
4911                    assert!(
4912                        is_remote,
4913                        "received buffer update from {:?}",
4914                        envelope.original_sender_id
4915                    );
4916                    e.insert(OpenBuffer::Loading(ops));
4917                }
4918            }
4919            Ok(())
4920        })
4921    }
4922
4923    async fn handle_update_buffer_file(
4924        this: ModelHandle<Self>,
4925        envelope: TypedEnvelope<proto::UpdateBufferFile>,
4926        _: Arc<Client>,
4927        mut cx: AsyncAppContext,
4928    ) -> Result<()> {
4929        this.update(&mut cx, |this, cx| {
4930            let payload = envelope.payload.clone();
4931            let buffer_id = payload.buffer_id;
4932            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
4933            let worktree = this
4934                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
4935                .ok_or_else(|| anyhow!("no such worktree"))?;
4936            let file = File::from_proto(file, worktree.clone(), cx)?;
4937            let buffer = this
4938                .opened_buffers
4939                .get_mut(&buffer_id)
4940                .and_then(|b| b.upgrade(cx))
4941                .ok_or_else(|| anyhow!("no such buffer"))?;
4942            buffer.update(cx, |buffer, cx| {
4943                buffer.file_updated(Arc::new(file), cx).detach();
4944            });
4945            Ok(())
4946        })
4947    }
4948
4949    async fn handle_save_buffer(
4950        this: ModelHandle<Self>,
4951        envelope: TypedEnvelope<proto::SaveBuffer>,
4952        _: Arc<Client>,
4953        mut cx: AsyncAppContext,
4954    ) -> Result<proto::BufferSaved> {
4955        let buffer_id = envelope.payload.buffer_id;
4956        let requested_version = deserialize_version(envelope.payload.version);
4957
4958        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
4959            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
4960            let buffer = this
4961                .opened_buffers
4962                .get(&buffer_id)
4963                .and_then(|buffer| buffer.upgrade(cx))
4964                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
4965            Ok::<_, anyhow::Error>((project_id, buffer))
4966        })?;
4967        buffer
4968            .update(&mut cx, |buffer, _| {
4969                buffer.wait_for_version(requested_version)
4970            })
4971            .await;
4972
4973        let (saved_version, fingerprint, mtime) =
4974            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
4975        Ok(proto::BufferSaved {
4976            project_id,
4977            buffer_id,
4978            version: serialize_version(&saved_version),
4979            mtime: Some(mtime.into()),
4980            fingerprint,
4981        })
4982    }
4983
4984    async fn handle_reload_buffers(
4985        this: ModelHandle<Self>,
4986        envelope: TypedEnvelope<proto::ReloadBuffers>,
4987        _: Arc<Client>,
4988        mut cx: AsyncAppContext,
4989    ) -> Result<proto::ReloadBuffersResponse> {
4990        let sender_id = envelope.original_sender_id()?;
4991        let reload = this.update(&mut cx, |this, cx| {
4992            let mut buffers = HashSet::default();
4993            for buffer_id in &envelope.payload.buffer_ids {
4994                buffers.insert(
4995                    this.opened_buffers
4996                        .get(buffer_id)
4997                        .and_then(|buffer| buffer.upgrade(cx))
4998                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
4999                );
5000            }
5001            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5002        })?;
5003
5004        let project_transaction = reload.await?;
5005        let project_transaction = this.update(&mut cx, |this, cx| {
5006            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5007        });
5008        Ok(proto::ReloadBuffersResponse {
5009            transaction: Some(project_transaction),
5010        })
5011    }
5012
5013    async fn handle_format_buffers(
5014        this: ModelHandle<Self>,
5015        envelope: TypedEnvelope<proto::FormatBuffers>,
5016        _: Arc<Client>,
5017        mut cx: AsyncAppContext,
5018    ) -> Result<proto::FormatBuffersResponse> {
5019        let sender_id = envelope.original_sender_id()?;
5020        let format = this.update(&mut cx, |this, cx| {
5021            let mut buffers = HashSet::default();
5022            for buffer_id in &envelope.payload.buffer_ids {
5023                buffers.insert(
5024                    this.opened_buffers
5025                        .get(buffer_id)
5026                        .and_then(|buffer| buffer.upgrade(cx))
5027                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5028                );
5029            }
5030            Ok::<_, anyhow::Error>(this.format(buffers, false, cx))
5031        })?;
5032
5033        let project_transaction = format.await?;
5034        let project_transaction = this.update(&mut cx, |this, cx| {
5035            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5036        });
5037        Ok(proto::FormatBuffersResponse {
5038            transaction: Some(project_transaction),
5039        })
5040    }
5041
5042    async fn handle_get_completions(
5043        this: ModelHandle<Self>,
5044        envelope: TypedEnvelope<proto::GetCompletions>,
5045        _: Arc<Client>,
5046        mut cx: AsyncAppContext,
5047    ) -> Result<proto::GetCompletionsResponse> {
5048        let position = envelope
5049            .payload
5050            .position
5051            .and_then(language::proto::deserialize_anchor)
5052            .ok_or_else(|| anyhow!("invalid position"))?;
5053        let version = deserialize_version(envelope.payload.version);
5054        let buffer = this.read_with(&cx, |this, cx| {
5055            this.opened_buffers
5056                .get(&envelope.payload.buffer_id)
5057                .and_then(|buffer| buffer.upgrade(cx))
5058                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5059        })?;
5060        buffer
5061            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5062            .await;
5063        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5064        let completions = this
5065            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5066            .await?;
5067
5068        Ok(proto::GetCompletionsResponse {
5069            completions: completions
5070                .iter()
5071                .map(language::proto::serialize_completion)
5072                .collect(),
5073            version: serialize_version(&version),
5074        })
5075    }
5076
5077    async fn handle_apply_additional_edits_for_completion(
5078        this: ModelHandle<Self>,
5079        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5080        _: Arc<Client>,
5081        mut cx: AsyncAppContext,
5082    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5083        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5084            let buffer = this
5085                .opened_buffers
5086                .get(&envelope.payload.buffer_id)
5087                .and_then(|buffer| buffer.upgrade(cx))
5088                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5089            let language = buffer.read(cx).language();
5090            let completion = language::proto::deserialize_completion(
5091                envelope
5092                    .payload
5093                    .completion
5094                    .ok_or_else(|| anyhow!("invalid completion"))?,
5095                language,
5096            )?;
5097            Ok::<_, anyhow::Error>(
5098                this.apply_additional_edits_for_completion(buffer, completion, false, cx),
5099            )
5100        })?;
5101
5102        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5103            transaction: apply_additional_edits
5104                .await?
5105                .as_ref()
5106                .map(language::proto::serialize_transaction),
5107        })
5108    }
5109
5110    async fn handle_get_code_actions(
5111        this: ModelHandle<Self>,
5112        envelope: TypedEnvelope<proto::GetCodeActions>,
5113        _: Arc<Client>,
5114        mut cx: AsyncAppContext,
5115    ) -> Result<proto::GetCodeActionsResponse> {
5116        let start = envelope
5117            .payload
5118            .start
5119            .and_then(language::proto::deserialize_anchor)
5120            .ok_or_else(|| anyhow!("invalid start"))?;
5121        let end = envelope
5122            .payload
5123            .end
5124            .and_then(language::proto::deserialize_anchor)
5125            .ok_or_else(|| anyhow!("invalid end"))?;
5126        let buffer = this.update(&mut cx, |this, cx| {
5127            this.opened_buffers
5128                .get(&envelope.payload.buffer_id)
5129                .and_then(|buffer| buffer.upgrade(cx))
5130                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5131        })?;
5132        buffer
5133            .update(&mut cx, |buffer, _| {
5134                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5135            })
5136            .await;
5137
5138        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5139        let code_actions = this.update(&mut cx, |this, cx| {
5140            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5141        })?;
5142
5143        Ok(proto::GetCodeActionsResponse {
5144            actions: code_actions
5145                .await?
5146                .iter()
5147                .map(language::proto::serialize_code_action)
5148                .collect(),
5149            version: serialize_version(&version),
5150        })
5151    }
5152
5153    async fn handle_apply_code_action(
5154        this: ModelHandle<Self>,
5155        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5156        _: Arc<Client>,
5157        mut cx: AsyncAppContext,
5158    ) -> Result<proto::ApplyCodeActionResponse> {
5159        let sender_id = envelope.original_sender_id()?;
5160        let action = language::proto::deserialize_code_action(
5161            envelope
5162                .payload
5163                .action
5164                .ok_or_else(|| anyhow!("invalid action"))?,
5165        )?;
5166        let apply_code_action = this.update(&mut cx, |this, cx| {
5167            let buffer = this
5168                .opened_buffers
5169                .get(&envelope.payload.buffer_id)
5170                .and_then(|buffer| buffer.upgrade(cx))
5171                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5172            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5173        })?;
5174
5175        let project_transaction = apply_code_action.await?;
5176        let project_transaction = this.update(&mut cx, |this, cx| {
5177            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5178        });
5179        Ok(proto::ApplyCodeActionResponse {
5180            transaction: Some(project_transaction),
5181        })
5182    }
5183
5184    async fn handle_lsp_command<T: LspCommand>(
5185        this: ModelHandle<Self>,
5186        envelope: TypedEnvelope<T::ProtoRequest>,
5187        _: Arc<Client>,
5188        mut cx: AsyncAppContext,
5189    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5190    where
5191        <T::LspRequest as lsp::request::Request>::Result: Send,
5192    {
5193        let sender_id = envelope.original_sender_id()?;
5194        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5195        let buffer_handle = this.read_with(&cx, |this, _| {
5196            this.opened_buffers
5197                .get(&buffer_id)
5198                .and_then(|buffer| buffer.upgrade(&cx))
5199                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5200        })?;
5201        let request = T::from_proto(
5202            envelope.payload,
5203            this.clone(),
5204            buffer_handle.clone(),
5205            cx.clone(),
5206        )
5207        .await?;
5208        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5209        let response = this
5210            .update(&mut cx, |this, cx| {
5211                this.request_lsp(buffer_handle, request, cx)
5212            })
5213            .await?;
5214        this.update(&mut cx, |this, cx| {
5215            Ok(T::response_to_proto(
5216                response,
5217                this,
5218                sender_id,
5219                &buffer_version,
5220                cx,
5221            ))
5222        })
5223    }
5224
5225    async fn handle_get_project_symbols(
5226        this: ModelHandle<Self>,
5227        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5228        _: Arc<Client>,
5229        mut cx: AsyncAppContext,
5230    ) -> Result<proto::GetProjectSymbolsResponse> {
5231        let symbols = this
5232            .update(&mut cx, |this, cx| {
5233                this.symbols(&envelope.payload.query, cx)
5234            })
5235            .await?;
5236
5237        Ok(proto::GetProjectSymbolsResponse {
5238            symbols: symbols.iter().map(serialize_symbol).collect(),
5239        })
5240    }
5241
5242    async fn handle_search_project(
5243        this: ModelHandle<Self>,
5244        envelope: TypedEnvelope<proto::SearchProject>,
5245        _: Arc<Client>,
5246        mut cx: AsyncAppContext,
5247    ) -> Result<proto::SearchProjectResponse> {
5248        let peer_id = envelope.original_sender_id()?;
5249        let query = SearchQuery::from_proto(envelope.payload)?;
5250        let result = this
5251            .update(&mut cx, |this, cx| this.search(query, cx))
5252            .await?;
5253
5254        this.update(&mut cx, |this, cx| {
5255            let mut locations = Vec::new();
5256            for (buffer, ranges) in result {
5257                for range in ranges {
5258                    let start = serialize_anchor(&range.start);
5259                    let end = serialize_anchor(&range.end);
5260                    let buffer = this.serialize_buffer_for_peer(&buffer, peer_id, cx);
5261                    locations.push(proto::Location {
5262                        buffer: Some(buffer),
5263                        start: Some(start),
5264                        end: Some(end),
5265                    });
5266                }
5267            }
5268            Ok(proto::SearchProjectResponse { locations })
5269        })
5270    }
5271
5272    async fn handle_open_buffer_for_symbol(
5273        this: ModelHandle<Self>,
5274        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5275        _: Arc<Client>,
5276        mut cx: AsyncAppContext,
5277    ) -> Result<proto::OpenBufferForSymbolResponse> {
5278        let peer_id = envelope.original_sender_id()?;
5279        let symbol = envelope
5280            .payload
5281            .symbol
5282            .ok_or_else(|| anyhow!("invalid symbol"))?;
5283        let symbol = this.read_with(&cx, |this, _| {
5284            let symbol = this.deserialize_symbol(symbol)?;
5285            let signature = this.symbol_signature(symbol.worktree_id, &symbol.path);
5286            if signature == symbol.signature {
5287                Ok(symbol)
5288            } else {
5289                Err(anyhow!("invalid symbol signature"))
5290            }
5291        })?;
5292        let buffer = this
5293            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5294            .await?;
5295
5296        Ok(proto::OpenBufferForSymbolResponse {
5297            buffer: Some(this.update(&mut cx, |this, cx| {
5298                this.serialize_buffer_for_peer(&buffer, peer_id, cx)
5299            })),
5300        })
5301    }
5302
5303    fn symbol_signature(&self, worktree_id: WorktreeId, path: &Path) -> [u8; 32] {
5304        let mut hasher = Sha256::new();
5305        hasher.update(worktree_id.to_proto().to_be_bytes());
5306        hasher.update(path.to_string_lossy().as_bytes());
5307        hasher.update(self.nonce.to_be_bytes());
5308        hasher.finalize().as_slice().try_into().unwrap()
5309    }
5310
5311    async fn handle_open_buffer_by_id(
5312        this: ModelHandle<Self>,
5313        envelope: TypedEnvelope<proto::OpenBufferById>,
5314        _: Arc<Client>,
5315        mut cx: AsyncAppContext,
5316    ) -> Result<proto::OpenBufferResponse> {
5317        let peer_id = envelope.original_sender_id()?;
5318        let buffer = this
5319            .update(&mut cx, |this, cx| {
5320                this.open_buffer_by_id(envelope.payload.id, cx)
5321            })
5322            .await?;
5323        this.update(&mut cx, |this, cx| {
5324            Ok(proto::OpenBufferResponse {
5325                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5326            })
5327        })
5328    }
5329
5330    async fn handle_open_buffer_by_path(
5331        this: ModelHandle<Self>,
5332        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5333        _: Arc<Client>,
5334        mut cx: AsyncAppContext,
5335    ) -> Result<proto::OpenBufferResponse> {
5336        let peer_id = envelope.original_sender_id()?;
5337        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5338        let open_buffer = this.update(&mut cx, |this, cx| {
5339            this.open_buffer(
5340                ProjectPath {
5341                    worktree_id,
5342                    path: PathBuf::from(envelope.payload.path).into(),
5343                },
5344                cx,
5345            )
5346        });
5347
5348        let buffer = open_buffer.await?;
5349        this.update(&mut cx, |this, cx| {
5350            Ok(proto::OpenBufferResponse {
5351                buffer: Some(this.serialize_buffer_for_peer(&buffer, peer_id, cx)),
5352            })
5353        })
5354    }
5355
5356    fn serialize_project_transaction_for_peer(
5357        &mut self,
5358        project_transaction: ProjectTransaction,
5359        peer_id: PeerId,
5360        cx: &AppContext,
5361    ) -> proto::ProjectTransaction {
5362        let mut serialized_transaction = proto::ProjectTransaction {
5363            buffers: Default::default(),
5364            transactions: Default::default(),
5365        };
5366        for (buffer, transaction) in project_transaction.0 {
5367            serialized_transaction
5368                .buffers
5369                .push(self.serialize_buffer_for_peer(&buffer, peer_id, cx));
5370            serialized_transaction
5371                .transactions
5372                .push(language::proto::serialize_transaction(&transaction));
5373        }
5374        serialized_transaction
5375    }
5376
5377    fn deserialize_project_transaction(
5378        &mut self,
5379        message: proto::ProjectTransaction,
5380        push_to_history: bool,
5381        cx: &mut ModelContext<Self>,
5382    ) -> Task<Result<ProjectTransaction>> {
5383        cx.spawn(|this, mut cx| async move {
5384            let mut project_transaction = ProjectTransaction::default();
5385            for (buffer, transaction) in message.buffers.into_iter().zip(message.transactions) {
5386                let buffer = this
5387                    .update(&mut cx, |this, cx| this.deserialize_buffer(buffer, cx))
5388                    .await?;
5389                let transaction = language::proto::deserialize_transaction(transaction)?;
5390                project_transaction.0.insert(buffer, transaction);
5391            }
5392
5393            for (buffer, transaction) in &project_transaction.0 {
5394                buffer
5395                    .update(&mut cx, |buffer, _| {
5396                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5397                    })
5398                    .await;
5399
5400                if push_to_history {
5401                    buffer.update(&mut cx, |buffer, _| {
5402                        buffer.push_transaction(transaction.clone(), Instant::now());
5403                    });
5404                }
5405            }
5406
5407            Ok(project_transaction)
5408        })
5409    }
5410
5411    fn serialize_buffer_for_peer(
5412        &mut self,
5413        buffer: &ModelHandle<Buffer>,
5414        peer_id: PeerId,
5415        cx: &AppContext,
5416    ) -> proto::Buffer {
5417        let buffer_id = buffer.read(cx).remote_id();
5418        let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5419        if shared_buffers.insert(buffer_id) {
5420            proto::Buffer {
5421                variant: Some(proto::buffer::Variant::State(buffer.read(cx).to_proto())),
5422            }
5423        } else {
5424            proto::Buffer {
5425                variant: Some(proto::buffer::Variant::Id(buffer_id)),
5426            }
5427        }
5428    }
5429
5430    fn deserialize_buffer(
5431        &mut self,
5432        buffer: proto::Buffer,
5433        cx: &mut ModelContext<Self>,
5434    ) -> Task<Result<ModelHandle<Buffer>>> {
5435        let replica_id = self.replica_id();
5436
5437        let opened_buffer_tx = self.opened_buffer.0.clone();
5438        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5439        cx.spawn(|this, mut cx| async move {
5440            match buffer.variant.ok_or_else(|| anyhow!("missing buffer"))? {
5441                proto::buffer::Variant::Id(id) => {
5442                    let buffer = loop {
5443                        let buffer = this.read_with(&cx, |this, cx| {
5444                            this.opened_buffers
5445                                .get(&id)
5446                                .and_then(|buffer| buffer.upgrade(cx))
5447                        });
5448                        if let Some(buffer) = buffer {
5449                            break buffer;
5450                        }
5451                        opened_buffer_rx
5452                            .next()
5453                            .await
5454                            .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5455                    };
5456                    Ok(buffer)
5457                }
5458                proto::buffer::Variant::State(mut buffer) => {
5459                    let mut buffer_worktree = None;
5460                    let mut buffer_file = None;
5461                    if let Some(file) = buffer.file.take() {
5462                        this.read_with(&cx, |this, cx| {
5463                            let worktree_id = WorktreeId::from_proto(file.worktree_id);
5464                            let worktree =
5465                                this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5466                                    anyhow!("no worktree found for id {}", file.worktree_id)
5467                                })?;
5468                            buffer_file =
5469                                Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5470                                    as Arc<dyn language::File>);
5471                            buffer_worktree = Some(worktree);
5472                            Ok::<_, anyhow::Error>(())
5473                        })?;
5474                    }
5475
5476                    let buffer = cx.add_model(|cx| {
5477                        Buffer::from_proto(replica_id, buffer, buffer_file, cx).unwrap()
5478                    });
5479
5480                    this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
5481
5482                    *opened_buffer_tx.borrow_mut().borrow_mut() = ();
5483                    Ok(buffer)
5484                }
5485            }
5486        })
5487    }
5488
5489    fn deserialize_symbol(&self, serialized_symbol: proto::Symbol) -> Result<Symbol> {
5490        let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5491        let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5492        let start = serialized_symbol
5493            .start
5494            .ok_or_else(|| anyhow!("invalid start"))?;
5495        let end = serialized_symbol
5496            .end
5497            .ok_or_else(|| anyhow!("invalid end"))?;
5498        let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5499        let path = PathBuf::from(serialized_symbol.path);
5500        let language = self.languages.select_language(&path);
5501        Ok(Symbol {
5502            source_worktree_id,
5503            worktree_id,
5504            language_server_name: LanguageServerName(serialized_symbol.language_server_name.into()),
5505            label: language
5506                .and_then(|language| language.label_for_symbol(&serialized_symbol.name, kind))
5507                .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None)),
5508            name: serialized_symbol.name,
5509            path,
5510            range: PointUtf16::new(start.row, start.column)..PointUtf16::new(end.row, end.column),
5511            kind,
5512            signature: serialized_symbol
5513                .signature
5514                .try_into()
5515                .map_err(|_| anyhow!("invalid signature"))?,
5516        })
5517    }
5518
5519    async fn handle_buffer_saved(
5520        this: ModelHandle<Self>,
5521        envelope: TypedEnvelope<proto::BufferSaved>,
5522        _: Arc<Client>,
5523        mut cx: AsyncAppContext,
5524    ) -> Result<()> {
5525        let version = deserialize_version(envelope.payload.version);
5526        let mtime = envelope
5527            .payload
5528            .mtime
5529            .ok_or_else(|| anyhow!("missing mtime"))?
5530            .into();
5531
5532        this.update(&mut cx, |this, cx| {
5533            let buffer = this
5534                .opened_buffers
5535                .get(&envelope.payload.buffer_id)
5536                .and_then(|buffer| buffer.upgrade(cx));
5537            if let Some(buffer) = buffer {
5538                buffer.update(cx, |buffer, cx| {
5539                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5540                });
5541            }
5542            Ok(())
5543        })
5544    }
5545
5546    async fn handle_buffer_reloaded(
5547        this: ModelHandle<Self>,
5548        envelope: TypedEnvelope<proto::BufferReloaded>,
5549        _: Arc<Client>,
5550        mut cx: AsyncAppContext,
5551    ) -> Result<()> {
5552        let payload = envelope.payload;
5553        let version = deserialize_version(payload.version);
5554        let line_ending = deserialize_line_ending(
5555            proto::LineEnding::from_i32(payload.line_ending)
5556                .ok_or_else(|| anyhow!("missing line ending"))?,
5557        );
5558        let mtime = payload
5559            .mtime
5560            .ok_or_else(|| anyhow!("missing mtime"))?
5561            .into();
5562        this.update(&mut cx, |this, cx| {
5563            let buffer = this
5564                .opened_buffers
5565                .get(&payload.buffer_id)
5566                .and_then(|buffer| buffer.upgrade(cx));
5567            if let Some(buffer) = buffer {
5568                buffer.update(cx, |buffer, cx| {
5569                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5570                });
5571            }
5572            Ok(())
5573        })
5574    }
5575
5576    pub fn match_paths<'a>(
5577        &self,
5578        query: &'a str,
5579        include_ignored: bool,
5580        smart_case: bool,
5581        max_results: usize,
5582        cancel_flag: &'a AtomicBool,
5583        cx: &AppContext,
5584    ) -> impl 'a + Future<Output = Vec<PathMatch>> {
5585        let worktrees = self
5586            .worktrees(cx)
5587            .filter(|worktree| worktree.read(cx).is_visible())
5588            .collect::<Vec<_>>();
5589        let include_root_name = worktrees.len() > 1;
5590        let candidate_sets = worktrees
5591            .into_iter()
5592            .map(|worktree| CandidateSet {
5593                snapshot: worktree.read(cx).snapshot(),
5594                include_ignored,
5595                include_root_name,
5596            })
5597            .collect::<Vec<_>>();
5598
5599        let background = cx.background().clone();
5600        async move {
5601            fuzzy::match_paths(
5602                candidate_sets.as_slice(),
5603                query,
5604                smart_case,
5605                max_results,
5606                cancel_flag,
5607                background,
5608            )
5609            .await
5610        }
5611    }
5612
5613    fn edits_from_lsp(
5614        &mut self,
5615        buffer: &ModelHandle<Buffer>,
5616        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5617        version: Option<i32>,
5618        cx: &mut ModelContext<Self>,
5619    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5620        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5621        cx.background().spawn(async move {
5622            let snapshot = snapshot?;
5623            let mut lsp_edits = lsp_edits
5624                .into_iter()
5625                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5626                .collect::<Vec<_>>();
5627            lsp_edits.sort_by_key(|(range, _)| range.start);
5628
5629            let mut lsp_edits = lsp_edits.into_iter().peekable();
5630            let mut edits = Vec::new();
5631            while let Some((mut range, mut new_text)) = lsp_edits.next() {
5632                // Combine any LSP edits that are adjacent.
5633                //
5634                // Also, combine LSP edits that are separated from each other by only
5635                // a newline. This is important because for some code actions,
5636                // Rust-analyzer rewrites the entire buffer via a series of edits that
5637                // are separated by unchanged newline characters.
5638                //
5639                // In order for the diffing logic below to work properly, any edits that
5640                // cancel each other out must be combined into one.
5641                while let Some((next_range, next_text)) = lsp_edits.peek() {
5642                    if next_range.start > range.end {
5643                        if next_range.start.row > range.end.row + 1
5644                            || next_range.start.column > 0
5645                            || snapshot.clip_point_utf16(
5646                                PointUtf16::new(range.end.row, u32::MAX),
5647                                Bias::Left,
5648                            ) > range.end
5649                        {
5650                            break;
5651                        }
5652                        new_text.push('\n');
5653                    }
5654                    range.end = next_range.end;
5655                    new_text.push_str(&next_text);
5656                    lsp_edits.next();
5657                }
5658
5659                if snapshot.clip_point_utf16(range.start, Bias::Left) != range.start
5660                    || snapshot.clip_point_utf16(range.end, Bias::Left) != range.end
5661                {
5662                    return Err(anyhow!("invalid edits received from language server"));
5663                }
5664
5665                // For multiline edits, perform a diff of the old and new text so that
5666                // we can identify the changes more precisely, preserving the locations
5667                // of any anchors positioned in the unchanged regions.
5668                if range.end.row > range.start.row {
5669                    let mut offset = range.start.to_offset(&snapshot);
5670                    let old_text = snapshot.text_for_range(range).collect::<String>();
5671
5672                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5673                    let mut moved_since_edit = true;
5674                    for change in diff.iter_all_changes() {
5675                        let tag = change.tag();
5676                        let value = change.value();
5677                        match tag {
5678                            ChangeTag::Equal => {
5679                                offset += value.len();
5680                                moved_since_edit = true;
5681                            }
5682                            ChangeTag::Delete => {
5683                                let start = snapshot.anchor_after(offset);
5684                                let end = snapshot.anchor_before(offset + value.len());
5685                                if moved_since_edit {
5686                                    edits.push((start..end, String::new()));
5687                                } else {
5688                                    edits.last_mut().unwrap().0.end = end;
5689                                }
5690                                offset += value.len();
5691                                moved_since_edit = false;
5692                            }
5693                            ChangeTag::Insert => {
5694                                if moved_since_edit {
5695                                    let anchor = snapshot.anchor_after(offset);
5696                                    edits.push((anchor.clone()..anchor, value.to_string()));
5697                                } else {
5698                                    edits.last_mut().unwrap().1.push_str(value);
5699                                }
5700                                moved_since_edit = false;
5701                            }
5702                        }
5703                    }
5704                } else if range.end == range.start {
5705                    let anchor = snapshot.anchor_after(range.start);
5706                    edits.push((anchor.clone()..anchor, new_text));
5707                } else {
5708                    let edit_start = snapshot.anchor_after(range.start);
5709                    let edit_end = snapshot.anchor_before(range.end);
5710                    edits.push((edit_start..edit_end, new_text));
5711                }
5712            }
5713
5714            Ok(edits)
5715        })
5716    }
5717
5718    fn buffer_snapshot_for_lsp_version(
5719        &mut self,
5720        buffer: &ModelHandle<Buffer>,
5721        version: Option<i32>,
5722        cx: &AppContext,
5723    ) -> Result<TextBufferSnapshot> {
5724        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5725
5726        if let Some(version) = version {
5727            let buffer_id = buffer.read(cx).remote_id();
5728            let snapshots = self
5729                .buffer_snapshots
5730                .get_mut(&buffer_id)
5731                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5732            let mut found_snapshot = None;
5733            snapshots.retain(|(snapshot_version, snapshot)| {
5734                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5735                    false
5736                } else {
5737                    if *snapshot_version == version {
5738                        found_snapshot = Some(snapshot.clone());
5739                    }
5740                    true
5741                }
5742            });
5743
5744            found_snapshot.ok_or_else(|| {
5745                anyhow!(
5746                    "snapshot not found for buffer {} at version {}",
5747                    buffer_id,
5748                    version
5749                )
5750            })
5751        } else {
5752            Ok((buffer.read(cx)).text_snapshot())
5753        }
5754    }
5755
5756    fn language_server_for_buffer(
5757        &self,
5758        buffer: &Buffer,
5759        cx: &AppContext,
5760    ) -> Option<(&Arc<dyn LspAdapter>, &Arc<LanguageServer>)> {
5761        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5762            let worktree_id = file.worktree_id(cx);
5763            let key = (worktree_id, language.lsp_adapter()?.name());
5764
5765            if let Some(server_id) = self.language_server_ids.get(&key) {
5766                if let Some(LanguageServerState::Running { adapter, server }) =
5767                    self.language_servers.get(&server_id)
5768                {
5769                    return Some((adapter, server));
5770                }
5771            }
5772        }
5773
5774        None
5775    }
5776}
5777
5778impl ProjectStore {
5779    pub fn new(db: Arc<Db>) -> Self {
5780        Self {
5781            db,
5782            projects: Default::default(),
5783        }
5784    }
5785
5786    pub fn projects<'a>(
5787        &'a self,
5788        cx: &'a AppContext,
5789    ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5790        self.projects
5791            .iter()
5792            .filter_map(|project| project.upgrade(cx))
5793    }
5794
5795    fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5796        if let Err(ix) = self
5797            .projects
5798            .binary_search_by_key(&project.id(), WeakModelHandle::id)
5799        {
5800            self.projects.insert(ix, project);
5801        }
5802        cx.notify();
5803    }
5804
5805    fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
5806        let mut did_change = false;
5807        self.projects.retain(|project| {
5808            if project.is_upgradable(cx) {
5809                true
5810            } else {
5811                did_change = true;
5812                false
5813            }
5814        });
5815        if did_change {
5816            cx.notify();
5817        }
5818    }
5819}
5820
5821impl WorktreeHandle {
5822    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5823        match self {
5824            WorktreeHandle::Strong(handle) => Some(handle.clone()),
5825            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5826        }
5827    }
5828}
5829
5830impl OpenBuffer {
5831    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5832        match self {
5833            OpenBuffer::Strong(handle) => Some(handle.clone()),
5834            OpenBuffer::Weak(handle) => handle.upgrade(cx),
5835            OpenBuffer::Loading(_) => None,
5836        }
5837    }
5838}
5839
5840struct CandidateSet {
5841    snapshot: Snapshot,
5842    include_ignored: bool,
5843    include_root_name: bool,
5844}
5845
5846impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
5847    type Candidates = CandidateSetIter<'a>;
5848
5849    fn id(&self) -> usize {
5850        self.snapshot.id().to_usize()
5851    }
5852
5853    fn len(&self) -> usize {
5854        if self.include_ignored {
5855            self.snapshot.file_count()
5856        } else {
5857            self.snapshot.visible_file_count()
5858        }
5859    }
5860
5861    fn prefix(&self) -> Arc<str> {
5862        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5863            self.snapshot.root_name().into()
5864        } else if self.include_root_name {
5865            format!("{}/", self.snapshot.root_name()).into()
5866        } else {
5867            "".into()
5868        }
5869    }
5870
5871    fn candidates(&'a self, start: usize) -> Self::Candidates {
5872        CandidateSetIter {
5873            traversal: self.snapshot.files(self.include_ignored, start),
5874        }
5875    }
5876}
5877
5878struct CandidateSetIter<'a> {
5879    traversal: Traversal<'a>,
5880}
5881
5882impl<'a> Iterator for CandidateSetIter<'a> {
5883    type Item = PathMatchCandidate<'a>;
5884
5885    fn next(&mut self) -> Option<Self::Item> {
5886        self.traversal.next().map(|entry| {
5887            if let EntryKind::File(char_bag) = entry.kind {
5888                PathMatchCandidate {
5889                    path: &entry.path,
5890                    char_bag,
5891                }
5892            } else {
5893                unreachable!()
5894            }
5895        })
5896    }
5897}
5898
5899impl Entity for ProjectStore {
5900    type Event = ();
5901}
5902
5903impl Entity for Project {
5904    type Event = Event;
5905
5906    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
5907        self.project_store.update(cx, ProjectStore::prune_projects);
5908
5909        match &self.client_state {
5910            ProjectClientState::Local { remote_id_rx, .. } => {
5911                if let Some(project_id) = *remote_id_rx.borrow() {
5912                    self.client
5913                        .send(proto::UnregisterProject { project_id })
5914                        .log_err();
5915                }
5916            }
5917            ProjectClientState::Remote { remote_id, .. } => {
5918                self.client
5919                    .send(proto::LeaveProject {
5920                        project_id: *remote_id,
5921                    })
5922                    .log_err();
5923            }
5924        }
5925    }
5926
5927    fn app_will_quit(
5928        &mut self,
5929        _: &mut MutableAppContext,
5930    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
5931        let shutdown_futures = self
5932            .language_servers
5933            .drain()
5934            .map(|(_, server_state)| async {
5935                match server_state {
5936                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
5937                    LanguageServerState::Starting(starting_server) => {
5938                        starting_server.await?.shutdown()?.await
5939                    }
5940                }
5941            })
5942            .collect::<Vec<_>>();
5943
5944        Some(
5945            async move {
5946                futures::future::join_all(shutdown_futures).await;
5947            }
5948            .boxed(),
5949        )
5950    }
5951}
5952
5953impl Collaborator {
5954    fn from_proto(
5955        message: proto::Collaborator,
5956        user_store: &ModelHandle<UserStore>,
5957        cx: &mut AsyncAppContext,
5958    ) -> impl Future<Output = Result<Self>> {
5959        let user = user_store.update(cx, |user_store, cx| {
5960            user_store.fetch_user(message.user_id, cx)
5961        });
5962
5963        async move {
5964            Ok(Self {
5965                peer_id: PeerId(message.peer_id),
5966                user: user.await?,
5967                replica_id: message.replica_id as ReplicaId,
5968            })
5969        }
5970    }
5971}
5972
5973impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5974    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5975        Self {
5976            worktree_id,
5977            path: path.as_ref().into(),
5978        }
5979    }
5980}
5981
5982impl From<lsp::CreateFileOptions> for fs::CreateOptions {
5983    fn from(options: lsp::CreateFileOptions) -> Self {
5984        Self {
5985            overwrite: options.overwrite.unwrap_or(false),
5986            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5987        }
5988    }
5989}
5990
5991impl From<lsp::RenameFileOptions> for fs::RenameOptions {
5992    fn from(options: lsp::RenameFileOptions) -> Self {
5993        Self {
5994            overwrite: options.overwrite.unwrap_or(false),
5995            ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5996        }
5997    }
5998}
5999
6000impl From<lsp::DeleteFileOptions> for fs::RemoveOptions {
6001    fn from(options: lsp::DeleteFileOptions) -> Self {
6002        Self {
6003            recursive: options.recursive.unwrap_or(false),
6004            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
6005        }
6006    }
6007}
6008
6009fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6010    proto::Symbol {
6011        source_worktree_id: symbol.source_worktree_id.to_proto(),
6012        worktree_id: symbol.worktree_id.to_proto(),
6013        language_server_name: symbol.language_server_name.0.to_string(),
6014        name: symbol.name.clone(),
6015        kind: unsafe { mem::transmute(symbol.kind) },
6016        path: symbol.path.to_string_lossy().to_string(),
6017        start: Some(proto::Point {
6018            row: symbol.range.start.row,
6019            column: symbol.range.start.column,
6020        }),
6021        end: Some(proto::Point {
6022            row: symbol.range.end.row,
6023            column: symbol.range.end.column,
6024        }),
6025        signature: symbol.signature.to_vec(),
6026    }
6027}
6028
6029fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6030    let mut path_components = path.components();
6031    let mut base_components = base.components();
6032    let mut components: Vec<Component> = Vec::new();
6033    loop {
6034        match (path_components.next(), base_components.next()) {
6035            (None, None) => break,
6036            (Some(a), None) => {
6037                components.push(a);
6038                components.extend(path_components.by_ref());
6039                break;
6040            }
6041            (None, _) => components.push(Component::ParentDir),
6042            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6043            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6044            (Some(a), Some(_)) => {
6045                components.push(Component::ParentDir);
6046                for _ in base_components {
6047                    components.push(Component::ParentDir);
6048                }
6049                components.push(a);
6050                components.extend(path_components.by_ref());
6051                break;
6052            }
6053        }
6054    }
6055    components.iter().map(|c| c.as_os_str()).collect()
6056}
6057
6058impl Item for Buffer {
6059    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6060        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6061    }
6062}