project.rs

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