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 =
2266            Some(token.as_ref()) == disk_based_diagnostics_progress_token.as_deref();
2267
2268        match progress {
2269            lsp::WorkDoneProgress::Begin(report) => {
2270                if is_disk_based_diagnostics_progress {
2271                    language_server_status.has_pending_diagnostic_updates = true;
2272                    self.disk_based_diagnostics_started(server_id, cx);
2273                    self.broadcast_language_server_update(
2274                        server_id,
2275                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2276                            proto::LspDiskBasedDiagnosticsUpdating {},
2277                        ),
2278                    );
2279                } else {
2280                    self.on_lsp_work_start(
2281                        server_id,
2282                        token.clone(),
2283                        LanguageServerProgress {
2284                            message: report.message.clone(),
2285                            percentage: report.percentage.map(|p| p as usize),
2286                            last_update_at: Instant::now(),
2287                        },
2288                        cx,
2289                    );
2290                    self.broadcast_language_server_update(
2291                        server_id,
2292                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2293                            token,
2294                            message: report.message,
2295                            percentage: report.percentage.map(|p| p as u32),
2296                        }),
2297                    );
2298                }
2299            }
2300            lsp::WorkDoneProgress::Report(report) => {
2301                if !is_disk_based_diagnostics_progress {
2302                    self.on_lsp_work_progress(
2303                        server_id,
2304                        token.clone(),
2305                        LanguageServerProgress {
2306                            message: report.message.clone(),
2307                            percentage: report.percentage.map(|p| p as usize),
2308                            last_update_at: Instant::now(),
2309                        },
2310                        cx,
2311                    );
2312                    self.broadcast_language_server_update(
2313                        server_id,
2314                        proto::update_language_server::Variant::WorkProgress(
2315                            proto::LspWorkProgress {
2316                                token,
2317                                message: report.message,
2318                                percentage: report.percentage.map(|p| p as u32),
2319                            },
2320                        ),
2321                    );
2322                }
2323            }
2324            lsp::WorkDoneProgress::End(_) => {
2325                language_server_status.progress_tokens.remove(&token);
2326
2327                if is_disk_based_diagnostics_progress {
2328                    language_server_status.has_pending_diagnostic_updates = false;
2329                    self.disk_based_diagnostics_finished(server_id, cx);
2330                    self.broadcast_language_server_update(
2331                        server_id,
2332                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2333                            proto::LspDiskBasedDiagnosticsUpdated {},
2334                        ),
2335                    );
2336                } else {
2337                    self.on_lsp_work_end(server_id, token.clone(), cx);
2338                    self.broadcast_language_server_update(
2339                        server_id,
2340                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2341                            token,
2342                        }),
2343                    );
2344                }
2345            }
2346        }
2347    }
2348
2349    fn on_lsp_work_start(
2350        &mut self,
2351        language_server_id: usize,
2352        token: String,
2353        progress: LanguageServerProgress,
2354        cx: &mut ModelContext<Self>,
2355    ) {
2356        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2357            status.pending_work.insert(token, progress);
2358            cx.notify();
2359        }
2360    }
2361
2362    fn on_lsp_work_progress(
2363        &mut self,
2364        language_server_id: usize,
2365        token: String,
2366        progress: LanguageServerProgress,
2367        cx: &mut ModelContext<Self>,
2368    ) {
2369        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2370            let entry = status
2371                .pending_work
2372                .entry(token)
2373                .or_insert(LanguageServerProgress {
2374                    message: Default::default(),
2375                    percentage: Default::default(),
2376                    last_update_at: progress.last_update_at,
2377                });
2378            if progress.message.is_some() {
2379                entry.message = progress.message;
2380            }
2381            if progress.percentage.is_some() {
2382                entry.percentage = progress.percentage;
2383            }
2384            entry.last_update_at = progress.last_update_at;
2385            cx.notify();
2386        }
2387    }
2388
2389    fn on_lsp_work_end(
2390        &mut self,
2391        language_server_id: usize,
2392        token: String,
2393        cx: &mut ModelContext<Self>,
2394    ) {
2395        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2396            status.pending_work.remove(&token);
2397            cx.notify();
2398        }
2399    }
2400
2401    async fn on_lsp_workspace_edit(
2402        this: WeakModelHandle<Self>,
2403        params: lsp::ApplyWorkspaceEditParams,
2404        server_id: usize,
2405        adapter: Arc<CachedLspAdapter>,
2406        language_server: Arc<LanguageServer>,
2407        mut cx: AsyncAppContext,
2408    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2409        let this = this
2410            .upgrade(&cx)
2411            .ok_or_else(|| anyhow!("project project closed"))?;
2412        let transaction = Self::deserialize_workspace_edit(
2413            this.clone(),
2414            params.edit,
2415            true,
2416            adapter.clone(),
2417            language_server.clone(),
2418            &mut cx,
2419        )
2420        .await
2421        .log_err();
2422        this.update(&mut cx, |this, _| {
2423            if let Some(transaction) = transaction {
2424                this.last_workspace_edits_by_language_server
2425                    .insert(server_id, transaction);
2426            }
2427        });
2428        Ok(lsp::ApplyWorkspaceEditResponse {
2429            applied: true,
2430            failed_change: None,
2431            failure_reason: None,
2432        })
2433    }
2434
2435    fn broadcast_language_server_update(
2436        &self,
2437        language_server_id: usize,
2438        event: proto::update_language_server::Variant,
2439    ) {
2440        if let Some(project_id) = self.remote_id() {
2441            self.client
2442                .send(proto::UpdateLanguageServer {
2443                    project_id,
2444                    language_server_id: language_server_id as u64,
2445                    variant: Some(event),
2446                })
2447                .log_err();
2448        }
2449    }
2450
2451    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2452        for server_state in self.language_servers.values() {
2453            if let LanguageServerState::Running { server, .. } = server_state {
2454                server
2455                    .notify::<lsp::notification::DidChangeConfiguration>(
2456                        lsp::DidChangeConfigurationParams {
2457                            settings: settings.clone(),
2458                        },
2459                    )
2460                    .ok();
2461            }
2462        }
2463        *self.language_server_settings.lock() = settings;
2464    }
2465
2466    pub fn language_server_statuses(
2467        &self,
2468    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2469        self.language_server_statuses.values()
2470    }
2471
2472    pub fn update_diagnostics(
2473        &mut self,
2474        language_server_id: usize,
2475        params: lsp::PublishDiagnosticsParams,
2476        disk_based_sources: &[String],
2477        cx: &mut ModelContext<Self>,
2478    ) -> Result<()> {
2479        let abs_path = params
2480            .uri
2481            .to_file_path()
2482            .map_err(|_| anyhow!("URI is not a file"))?;
2483        let mut diagnostics = Vec::default();
2484        let mut primary_diagnostic_group_ids = HashMap::default();
2485        let mut sources_by_group_id = HashMap::default();
2486        let mut supporting_diagnostics = HashMap::default();
2487        for diagnostic in &params.diagnostics {
2488            let source = diagnostic.source.as_ref();
2489            let code = diagnostic.code.as_ref().map(|code| match code {
2490                lsp::NumberOrString::Number(code) => code.to_string(),
2491                lsp::NumberOrString::String(code) => code.clone(),
2492            });
2493            let range = range_from_lsp(diagnostic.range);
2494            let is_supporting = diagnostic
2495                .related_information
2496                .as_ref()
2497                .map_or(false, |infos| {
2498                    infos.iter().any(|info| {
2499                        primary_diagnostic_group_ids.contains_key(&(
2500                            source,
2501                            code.clone(),
2502                            range_from_lsp(info.location.range),
2503                        ))
2504                    })
2505                });
2506
2507            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2508                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2509            });
2510
2511            if is_supporting {
2512                supporting_diagnostics.insert(
2513                    (source, code.clone(), range),
2514                    (diagnostic.severity, is_unnecessary),
2515                );
2516            } else {
2517                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2518                let is_disk_based =
2519                    source.map_or(false, |source| disk_based_sources.contains(source));
2520
2521                sources_by_group_id.insert(group_id, source);
2522                primary_diagnostic_group_ids
2523                    .insert((source, code.clone(), range.clone()), group_id);
2524
2525                diagnostics.push(DiagnosticEntry {
2526                    range,
2527                    diagnostic: Diagnostic {
2528                        code: code.clone(),
2529                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2530                        message: diagnostic.message.clone(),
2531                        group_id,
2532                        is_primary: true,
2533                        is_valid: true,
2534                        is_disk_based,
2535                        is_unnecessary,
2536                    },
2537                });
2538                if let Some(infos) = &diagnostic.related_information {
2539                    for info in infos {
2540                        if info.location.uri == params.uri && !info.message.is_empty() {
2541                            let range = range_from_lsp(info.location.range);
2542                            diagnostics.push(DiagnosticEntry {
2543                                range,
2544                                diagnostic: Diagnostic {
2545                                    code: code.clone(),
2546                                    severity: DiagnosticSeverity::INFORMATION,
2547                                    message: info.message.clone(),
2548                                    group_id,
2549                                    is_primary: false,
2550                                    is_valid: true,
2551                                    is_disk_based,
2552                                    is_unnecessary: false,
2553                                },
2554                            });
2555                        }
2556                    }
2557                }
2558            }
2559        }
2560
2561        for entry in &mut diagnostics {
2562            let diagnostic = &mut entry.diagnostic;
2563            if !diagnostic.is_primary {
2564                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2565                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2566                    source,
2567                    diagnostic.code.clone(),
2568                    entry.range.clone(),
2569                )) {
2570                    if let Some(severity) = severity {
2571                        diagnostic.severity = severity;
2572                    }
2573                    diagnostic.is_unnecessary = is_unnecessary;
2574                }
2575            }
2576        }
2577
2578        self.update_diagnostic_entries(
2579            language_server_id,
2580            abs_path,
2581            params.version,
2582            diagnostics,
2583            cx,
2584        )?;
2585        Ok(())
2586    }
2587
2588    pub fn update_diagnostic_entries(
2589        &mut self,
2590        language_server_id: usize,
2591        abs_path: PathBuf,
2592        version: Option<i32>,
2593        diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2594        cx: &mut ModelContext<Project>,
2595    ) -> Result<(), anyhow::Error> {
2596        let (worktree, relative_path) = self
2597            .find_local_worktree(&abs_path, cx)
2598            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2599
2600        let project_path = ProjectPath {
2601            worktree_id: worktree.read(cx).id(),
2602            path: relative_path.into(),
2603        };
2604        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2605            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2606        }
2607
2608        let updated = worktree.update(cx, |worktree, cx| {
2609            worktree
2610                .as_local_mut()
2611                .ok_or_else(|| anyhow!("not a local worktree"))?
2612                .update_diagnostics(
2613                    language_server_id,
2614                    project_path.path.clone(),
2615                    diagnostics,
2616                    cx,
2617                )
2618        })?;
2619        if updated {
2620            cx.emit(Event::DiagnosticsUpdated {
2621                language_server_id,
2622                path: project_path,
2623            });
2624        }
2625        Ok(())
2626    }
2627
2628    fn update_buffer_diagnostics(
2629        &mut self,
2630        buffer: &ModelHandle<Buffer>,
2631        mut diagnostics: Vec<DiagnosticEntry<PointUtf16>>,
2632        version: Option<i32>,
2633        cx: &mut ModelContext<Self>,
2634    ) -> Result<()> {
2635        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2636            Ordering::Equal
2637                .then_with(|| b.is_primary.cmp(&a.is_primary))
2638                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2639                .then_with(|| a.severity.cmp(&b.severity))
2640                .then_with(|| a.message.cmp(&b.message))
2641        }
2642
2643        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2644
2645        diagnostics.sort_unstable_by(|a, b| {
2646            Ordering::Equal
2647                .then_with(|| a.range.start.cmp(&b.range.start))
2648                .then_with(|| b.range.end.cmp(&a.range.end))
2649                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2650        });
2651
2652        let mut sanitized_diagnostics = Vec::new();
2653        let edits_since_save = Patch::new(
2654            snapshot
2655                .edits_since::<PointUtf16>(buffer.read(cx).saved_version())
2656                .collect(),
2657        );
2658        for entry in diagnostics {
2659            let start;
2660            let end;
2661            if entry.diagnostic.is_disk_based {
2662                // Some diagnostics are based on files on disk instead of buffers'
2663                // current contents. Adjust these diagnostics' ranges to reflect
2664                // any unsaved edits.
2665                start = edits_since_save.old_to_new(entry.range.start);
2666                end = edits_since_save.old_to_new(entry.range.end);
2667            } else {
2668                start = entry.range.start;
2669                end = entry.range.end;
2670            }
2671
2672            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2673                ..snapshot.clip_point_utf16(end, Bias::Right);
2674
2675            // Expand empty ranges by one character
2676            if range.start == range.end {
2677                range.end.column += 1;
2678                range.end = snapshot.clip_point_utf16(range.end, Bias::Right);
2679                if range.start == range.end && range.end.column > 0 {
2680                    range.start.column -= 1;
2681                    range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
2682                }
2683            }
2684
2685            sanitized_diagnostics.push(DiagnosticEntry {
2686                range,
2687                diagnostic: entry.diagnostic,
2688            });
2689        }
2690        drop(edits_since_save);
2691
2692        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2693        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2694        Ok(())
2695    }
2696
2697    pub fn reload_buffers(
2698        &self,
2699        buffers: HashSet<ModelHandle<Buffer>>,
2700        push_to_history: bool,
2701        cx: &mut ModelContext<Self>,
2702    ) -> Task<Result<ProjectTransaction>> {
2703        let mut local_buffers = Vec::new();
2704        let mut remote_buffers = None;
2705        for buffer_handle in buffers {
2706            let buffer = buffer_handle.read(cx);
2707            if buffer.is_dirty() {
2708                if let Some(file) = File::from_dyn(buffer.file()) {
2709                    if file.is_local() {
2710                        local_buffers.push(buffer_handle);
2711                    } else {
2712                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2713                    }
2714                }
2715            }
2716        }
2717
2718        let remote_buffers = self.remote_id().zip(remote_buffers);
2719        let client = self.client.clone();
2720
2721        cx.spawn(|this, mut cx| async move {
2722            let mut project_transaction = ProjectTransaction::default();
2723
2724            if let Some((project_id, remote_buffers)) = remote_buffers {
2725                let response = client
2726                    .request(proto::ReloadBuffers {
2727                        project_id,
2728                        buffer_ids: remote_buffers
2729                            .iter()
2730                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2731                            .collect(),
2732                    })
2733                    .await?
2734                    .transaction
2735                    .ok_or_else(|| anyhow!("missing transaction"))?;
2736                project_transaction = this
2737                    .update(&mut cx, |this, cx| {
2738                        this.deserialize_project_transaction(response, push_to_history, cx)
2739                    })
2740                    .await?;
2741            }
2742
2743            for buffer in local_buffers {
2744                let transaction = buffer
2745                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2746                    .await?;
2747                buffer.update(&mut cx, |buffer, cx| {
2748                    if let Some(transaction) = transaction {
2749                        if !push_to_history {
2750                            buffer.forget_transaction(transaction.id);
2751                        }
2752                        project_transaction.0.insert(cx.handle(), transaction);
2753                    }
2754                });
2755            }
2756
2757            Ok(project_transaction)
2758        })
2759    }
2760
2761    pub fn format(
2762        &self,
2763        buffers: HashSet<ModelHandle<Buffer>>,
2764        push_to_history: bool,
2765        trigger: FormatTrigger,
2766        cx: &mut ModelContext<Project>,
2767    ) -> Task<Result<ProjectTransaction>> {
2768        let mut local_buffers = Vec::new();
2769        let mut remote_buffers = None;
2770        for buffer_handle in buffers {
2771            let buffer = buffer_handle.read(cx);
2772            if let Some(file) = File::from_dyn(buffer.file()) {
2773                if let Some(buffer_abs_path) = file.as_local().map(|f| f.abs_path(cx)) {
2774                    if let Some((_, server)) = self.language_server_for_buffer(buffer, cx) {
2775                        local_buffers.push((buffer_handle, buffer_abs_path, server.clone()));
2776                    }
2777                } else {
2778                    remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2779                }
2780            } else {
2781                return Task::ready(Ok(Default::default()));
2782            }
2783        }
2784
2785        let remote_buffers = self.remote_id().zip(remote_buffers);
2786        let client = self.client.clone();
2787
2788        cx.spawn(|this, mut cx| async move {
2789            let mut project_transaction = ProjectTransaction::default();
2790
2791            if let Some((project_id, remote_buffers)) = remote_buffers {
2792                let response = client
2793                    .request(proto::FormatBuffers {
2794                        project_id,
2795                        trigger: trigger as i32,
2796                        buffer_ids: remote_buffers
2797                            .iter()
2798                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2799                            .collect(),
2800                    })
2801                    .await?
2802                    .transaction
2803                    .ok_or_else(|| anyhow!("missing transaction"))?;
2804                project_transaction = this
2805                    .update(&mut cx, |this, cx| {
2806                        this.deserialize_project_transaction(response, push_to_history, cx)
2807                    })
2808                    .await?;
2809            }
2810
2811            // Do not allow multiple concurrent formatting requests for the
2812            // same buffer.
2813            this.update(&mut cx, |this, _| {
2814                local_buffers
2815                    .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2816            });
2817            let _cleanup = defer({
2818                let this = this.clone();
2819                let mut cx = cx.clone();
2820                let local_buffers = &local_buffers;
2821                move || {
2822                    this.update(&mut cx, |this, _| {
2823                        for (buffer, _, _) in local_buffers {
2824                            this.buffers_being_formatted.remove(&buffer.id());
2825                        }
2826                    });
2827                }
2828            });
2829
2830            for (buffer, buffer_abs_path, language_server) in &local_buffers {
2831                let (format_on_save, formatter, tab_size) = buffer.read_with(&cx, |buffer, cx| {
2832                    let settings = cx.global::<Settings>();
2833                    let language_name = buffer.language().map(|language| language.name());
2834                    (
2835                        settings.format_on_save(language_name.as_deref()),
2836                        settings.formatter(language_name.as_deref()),
2837                        settings.tab_size(language_name.as_deref()),
2838                    )
2839                });
2840
2841                let transaction = match (formatter, format_on_save) {
2842                    (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => continue,
2843
2844                    (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2845                    | (_, FormatOnSave::LanguageServer) => Self::format_via_lsp(
2846                        &this,
2847                        &buffer,
2848                        &buffer_abs_path,
2849                        &language_server,
2850                        tab_size,
2851                        &mut cx,
2852                    )
2853                    .await
2854                    .context("failed to format via language server")?,
2855
2856                    (
2857                        Formatter::External { command, arguments },
2858                        FormatOnSave::On | FormatOnSave::Off,
2859                    )
2860                    | (_, FormatOnSave::External { command, arguments }) => {
2861                        Self::format_via_external_command(
2862                            &buffer,
2863                            &buffer_abs_path,
2864                            &command,
2865                            &arguments,
2866                            &mut cx,
2867                        )
2868                        .await
2869                        .context(format!(
2870                            "failed to format via external command {:?}",
2871                            command
2872                        ))?
2873                    }
2874                };
2875
2876                if let Some(transaction) = transaction {
2877                    if !push_to_history {
2878                        buffer.update(&mut cx, |buffer, _| {
2879                            buffer.forget_transaction(transaction.id)
2880                        });
2881                    }
2882                    project_transaction.0.insert(buffer.clone(), transaction);
2883                }
2884            }
2885
2886            Ok(project_transaction)
2887        })
2888    }
2889
2890    async fn format_via_lsp(
2891        this: &ModelHandle<Self>,
2892        buffer: &ModelHandle<Buffer>,
2893        abs_path: &Path,
2894        language_server: &Arc<LanguageServer>,
2895        tab_size: NonZeroU32,
2896        cx: &mut AsyncAppContext,
2897    ) -> Result<Option<Transaction>> {
2898        let text_document =
2899            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
2900        let capabilities = &language_server.capabilities();
2901        let lsp_edits = if capabilities
2902            .document_formatting_provider
2903            .as_ref()
2904            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2905        {
2906            language_server
2907                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2908                    text_document,
2909                    options: lsp::FormattingOptions {
2910                        tab_size: tab_size.into(),
2911                        insert_spaces: true,
2912                        insert_final_newline: Some(true),
2913                        ..Default::default()
2914                    },
2915                    work_done_progress_params: Default::default(),
2916                })
2917                .await?
2918        } else if capabilities
2919            .document_range_formatting_provider
2920            .as_ref()
2921            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2922        {
2923            let buffer_start = lsp::Position::new(0, 0);
2924            let buffer_end =
2925                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
2926            language_server
2927                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
2928                    text_document,
2929                    range: lsp::Range::new(buffer_start, buffer_end),
2930                    options: lsp::FormattingOptions {
2931                        tab_size: tab_size.into(),
2932                        insert_spaces: true,
2933                        insert_final_newline: Some(true),
2934                        ..Default::default()
2935                    },
2936                    work_done_progress_params: Default::default(),
2937                })
2938                .await?
2939        } else {
2940            None
2941        };
2942
2943        if let Some(lsp_edits) = lsp_edits {
2944            let edits = this
2945                .update(cx, |this, cx| {
2946                    this.edits_from_lsp(buffer, lsp_edits, None, cx)
2947                })
2948                .await?;
2949            buffer.update(cx, |buffer, cx| {
2950                buffer.finalize_last_transaction();
2951                buffer.start_transaction();
2952                for (range, text) in edits {
2953                    buffer.edit([(range, text)], None, cx);
2954                }
2955                if buffer.end_transaction(cx).is_some() {
2956                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
2957                    Ok(Some(transaction))
2958                } else {
2959                    Ok(None)
2960                }
2961            })
2962        } else {
2963            Ok(None)
2964        }
2965    }
2966
2967    async fn format_via_external_command(
2968        buffer: &ModelHandle<Buffer>,
2969        buffer_abs_path: &Path,
2970        command: &str,
2971        arguments: &[String],
2972        cx: &mut AsyncAppContext,
2973    ) -> Result<Option<Transaction>> {
2974        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
2975            let file = File::from_dyn(buffer.file())?;
2976            let worktree = file.worktree.read(cx).as_local()?;
2977            let mut worktree_path = worktree.abs_path().to_path_buf();
2978            if worktree.root_entry()?.is_file() {
2979                worktree_path.pop();
2980            }
2981            Some(worktree_path)
2982        });
2983
2984        if let Some(working_dir_path) = working_dir_path {
2985            let mut child =
2986                smol::process::Command::new(command)
2987                    .args(arguments.iter().map(|arg| {
2988                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
2989                    }))
2990                    .current_dir(&working_dir_path)
2991                    .stdin(smol::process::Stdio::piped())
2992                    .stdout(smol::process::Stdio::piped())
2993                    .stderr(smol::process::Stdio::piped())
2994                    .spawn()?;
2995            let stdin = child
2996                .stdin
2997                .as_mut()
2998                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
2999            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3000            for chunk in text.chunks() {
3001                stdin.write_all(chunk.as_bytes()).await?;
3002            }
3003            stdin.flush().await?;
3004
3005            let output = child.output().await?;
3006            if !output.status.success() {
3007                return Err(anyhow!(
3008                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3009                    output.status.code(),
3010                    String::from_utf8_lossy(&output.stdout),
3011                    String::from_utf8_lossy(&output.stderr),
3012                ));
3013            }
3014
3015            let stdout = String::from_utf8(output.stdout)?;
3016            let diff = buffer
3017                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3018                .await;
3019            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3020        } else {
3021            Ok(None)
3022        }
3023    }
3024
3025    pub fn definition<T: ToPointUtf16>(
3026        &self,
3027        buffer: &ModelHandle<Buffer>,
3028        position: T,
3029        cx: &mut ModelContext<Self>,
3030    ) -> Task<Result<Vec<LocationLink>>> {
3031        let position = position.to_point_utf16(buffer.read(cx));
3032        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3033    }
3034
3035    pub fn type_definition<T: ToPointUtf16>(
3036        &self,
3037        buffer: &ModelHandle<Buffer>,
3038        position: T,
3039        cx: &mut ModelContext<Self>,
3040    ) -> Task<Result<Vec<LocationLink>>> {
3041        let position = position.to_point_utf16(buffer.read(cx));
3042        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3043    }
3044
3045    pub fn references<T: ToPointUtf16>(
3046        &self,
3047        buffer: &ModelHandle<Buffer>,
3048        position: T,
3049        cx: &mut ModelContext<Self>,
3050    ) -> Task<Result<Vec<Location>>> {
3051        let position = position.to_point_utf16(buffer.read(cx));
3052        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3053    }
3054
3055    pub fn document_highlights<T: ToPointUtf16>(
3056        &self,
3057        buffer: &ModelHandle<Buffer>,
3058        position: T,
3059        cx: &mut ModelContext<Self>,
3060    ) -> Task<Result<Vec<DocumentHighlight>>> {
3061        let position = position.to_point_utf16(buffer.read(cx));
3062        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3063    }
3064
3065    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3066        if self.is_local() {
3067            let mut requests = Vec::new();
3068            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3069                let worktree_id = *worktree_id;
3070                if let Some(worktree) = self
3071                    .worktree_for_id(worktree_id, cx)
3072                    .and_then(|worktree| worktree.read(cx).as_local())
3073                {
3074                    if let Some(LanguageServerState::Running {
3075                        adapter,
3076                        language,
3077                        server,
3078                    }) = self.language_servers.get(server_id)
3079                    {
3080                        let adapter = adapter.clone();
3081                        let language = language.clone();
3082                        let worktree_abs_path = worktree.abs_path().clone();
3083                        requests.push(
3084                            server
3085                                .request::<lsp::request::WorkspaceSymbol>(
3086                                    lsp::WorkspaceSymbolParams {
3087                                        query: query.to_string(),
3088                                        ..Default::default()
3089                                    },
3090                                )
3091                                .log_err()
3092                                .map(move |response| {
3093                                    (
3094                                        adapter,
3095                                        language,
3096                                        worktree_id,
3097                                        worktree_abs_path,
3098                                        response.unwrap_or_default(),
3099                                    )
3100                                }),
3101                        );
3102                    }
3103                }
3104            }
3105
3106            cx.spawn_weak(|this, cx| async move {
3107                let responses = futures::future::join_all(requests).await;
3108                let this = if let Some(this) = this.upgrade(&cx) {
3109                    this
3110                } else {
3111                    return Ok(Default::default());
3112                };
3113                let symbols = this.read_with(&cx, |this, cx| {
3114                    let mut symbols = Vec::new();
3115                    for (
3116                        adapter,
3117                        adapter_language,
3118                        source_worktree_id,
3119                        worktree_abs_path,
3120                        response,
3121                    ) in responses
3122                    {
3123                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3124                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3125                            let mut worktree_id = source_worktree_id;
3126                            let path;
3127                            if let Some((worktree, rel_path)) =
3128                                this.find_local_worktree(&abs_path, cx)
3129                            {
3130                                worktree_id = worktree.read(cx).id();
3131                                path = rel_path;
3132                            } else {
3133                                path = relativize_path(&worktree_abs_path, &abs_path);
3134                            }
3135
3136                            let project_path = ProjectPath {
3137                                worktree_id,
3138                                path: path.into(),
3139                            };
3140                            let signature = this.symbol_signature(&project_path);
3141                            let language = this
3142                                .languages
3143                                .select_language(&project_path.path)
3144                                .unwrap_or(adapter_language.clone());
3145                            let language_server_name = adapter.name.clone();
3146                            Some(async move {
3147                                let label = language
3148                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3149                                    .await;
3150
3151                                Symbol {
3152                                    language_server_name,
3153                                    source_worktree_id,
3154                                    path: project_path,
3155                                    label: label.unwrap_or_else(|| {
3156                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3157                                    }),
3158                                    kind: lsp_symbol.kind,
3159                                    name: lsp_symbol.name,
3160                                    range: range_from_lsp(lsp_symbol.location.range),
3161                                    signature,
3162                                }
3163                            })
3164                        }));
3165                    }
3166                    symbols
3167                });
3168                Ok(futures::future::join_all(symbols).await)
3169            })
3170        } else if let Some(project_id) = self.remote_id() {
3171            let request = self.client.request(proto::GetProjectSymbols {
3172                project_id,
3173                query: query.to_string(),
3174            });
3175            cx.spawn_weak(|this, cx| async move {
3176                let response = request.await?;
3177                let mut symbols = Vec::new();
3178                if let Some(this) = this.upgrade(&cx) {
3179                    let new_symbols = this.read_with(&cx, |this, _| {
3180                        response
3181                            .symbols
3182                            .into_iter()
3183                            .map(|symbol| this.deserialize_symbol(symbol))
3184                            .collect::<Vec<_>>()
3185                    });
3186                    symbols = futures::future::join_all(new_symbols)
3187                        .await
3188                        .into_iter()
3189                        .filter_map(|symbol| symbol.log_err())
3190                        .collect::<Vec<_>>();
3191                }
3192                Ok(symbols)
3193            })
3194        } else {
3195            Task::ready(Ok(Default::default()))
3196        }
3197    }
3198
3199    pub fn open_buffer_for_symbol(
3200        &mut self,
3201        symbol: &Symbol,
3202        cx: &mut ModelContext<Self>,
3203    ) -> Task<Result<ModelHandle<Buffer>>> {
3204        if self.is_local() {
3205            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3206                symbol.source_worktree_id,
3207                symbol.language_server_name.clone(),
3208            )) {
3209                *id
3210            } else {
3211                return Task::ready(Err(anyhow!(
3212                    "language server for worktree and language not found"
3213                )));
3214            };
3215
3216            let worktree_abs_path = if let Some(worktree_abs_path) = self
3217                .worktree_for_id(symbol.path.worktree_id, cx)
3218                .and_then(|worktree| worktree.read(cx).as_local())
3219                .map(|local_worktree| local_worktree.abs_path())
3220            {
3221                worktree_abs_path
3222            } else {
3223                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3224            };
3225            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3226            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3227                uri
3228            } else {
3229                return Task::ready(Err(anyhow!("invalid symbol path")));
3230            };
3231
3232            self.open_local_buffer_via_lsp(
3233                symbol_uri,
3234                language_server_id,
3235                symbol.language_server_name.clone(),
3236                cx,
3237            )
3238        } else if let Some(project_id) = self.remote_id() {
3239            let request = self.client.request(proto::OpenBufferForSymbol {
3240                project_id,
3241                symbol: Some(serialize_symbol(symbol)),
3242            });
3243            cx.spawn(|this, mut cx| async move {
3244                let response = request.await?;
3245                this.update(&mut cx, |this, cx| {
3246                    this.wait_for_buffer(response.buffer_id, cx)
3247                })
3248                .await
3249            })
3250        } else {
3251            Task::ready(Err(anyhow!("project does not have a remote id")))
3252        }
3253    }
3254
3255    pub fn hover<T: ToPointUtf16>(
3256        &self,
3257        buffer: &ModelHandle<Buffer>,
3258        position: T,
3259        cx: &mut ModelContext<Self>,
3260    ) -> Task<Result<Option<Hover>>> {
3261        let position = position.to_point_utf16(buffer.read(cx));
3262        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3263    }
3264
3265    pub fn completions<T: ToPointUtf16>(
3266        &self,
3267        source_buffer_handle: &ModelHandle<Buffer>,
3268        position: T,
3269        cx: &mut ModelContext<Self>,
3270    ) -> Task<Result<Vec<Completion>>> {
3271        let source_buffer_handle = source_buffer_handle.clone();
3272        let source_buffer = source_buffer_handle.read(cx);
3273        let buffer_id = source_buffer.remote_id();
3274        let language = source_buffer.language().cloned();
3275        let worktree;
3276        let buffer_abs_path;
3277        if let Some(file) = File::from_dyn(source_buffer.file()) {
3278            worktree = file.worktree.clone();
3279            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3280        } else {
3281            return Task::ready(Ok(Default::default()));
3282        };
3283
3284        let position = position.to_point_utf16(source_buffer);
3285        let anchor = source_buffer.anchor_after(position);
3286
3287        if worktree.read(cx).as_local().is_some() {
3288            let buffer_abs_path = buffer_abs_path.unwrap();
3289            let lang_server =
3290                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3291                    server.clone()
3292                } else {
3293                    return Task::ready(Ok(Default::default()));
3294                };
3295
3296            cx.spawn(|_, cx| async move {
3297                let completions = lang_server
3298                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3299                        text_document_position: lsp::TextDocumentPositionParams::new(
3300                            lsp::TextDocumentIdentifier::new(
3301                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3302                            ),
3303                            point_to_lsp(position),
3304                        ),
3305                        context: Default::default(),
3306                        work_done_progress_params: Default::default(),
3307                        partial_result_params: Default::default(),
3308                    })
3309                    .await
3310                    .context("lsp completion request failed")?;
3311
3312                let completions = if let Some(completions) = completions {
3313                    match completions {
3314                        lsp::CompletionResponse::Array(completions) => completions,
3315                        lsp::CompletionResponse::List(list) => list.items,
3316                    }
3317                } else {
3318                    Default::default()
3319                };
3320
3321                let completions = source_buffer_handle.read_with(&cx, |this, _| {
3322                    let snapshot = this.snapshot();
3323                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3324                    let mut range_for_token = None;
3325                    completions.into_iter().filter_map(move |lsp_completion| {
3326                        // For now, we can only handle additional edits if they are returned
3327                        // when resolving the completion, not if they are present initially.
3328                        if lsp_completion
3329                            .additional_text_edits
3330                            .as_ref()
3331                            .map_or(false, |edits| !edits.is_empty())
3332                        {
3333                            return None;
3334                        }
3335
3336                        let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref() {
3337                            // If the language server provides a range to overwrite, then
3338                            // check that the range is valid.
3339                            Some(lsp::CompletionTextEdit::Edit(edit)) => {
3340                                let range = range_from_lsp(edit.range);
3341                                let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3342                                let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3343                                if start != range.start || end != range.end {
3344                                    log::info!("completion out of expected range");
3345                                    return None;
3346                                }
3347                                (
3348                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3349                                    edit.new_text.clone(),
3350                                )
3351                            }
3352                            // If the language server does not provide a range, then infer
3353                            // the range based on the syntax tree.
3354                            None => {
3355                                if position != clipped_position {
3356                                    log::info!("completion out of expected range");
3357                                    return None;
3358                                }
3359                                let Range { start, end } = range_for_token
3360                                    .get_or_insert_with(|| {
3361                                        let offset = position.to_offset(&snapshot);
3362                                        let (range, kind) = snapshot.surrounding_word(offset);
3363                                        if kind == Some(CharKind::Word) {
3364                                            range
3365                                        } else {
3366                                            offset..offset
3367                                        }
3368                                    })
3369                                    .clone();
3370                                let text = lsp_completion
3371                                    .insert_text
3372                                    .as_ref()
3373                                    .unwrap_or(&lsp_completion.label)
3374                                    .clone();
3375                                (
3376                                    snapshot.anchor_before(start)..snapshot.anchor_after(end),
3377                                    text,
3378                                )
3379                            }
3380                            Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3381                                log::info!("unsupported insert/replace completion");
3382                                return None;
3383                            }
3384                        };
3385
3386                        LineEnding::normalize(&mut new_text);
3387                        let language = language.clone();
3388                        Some(async move {
3389                            let label = if let Some(language) = language {
3390                                language.label_for_completion(&lsp_completion).await
3391                            } else {
3392                                None
3393                            };
3394                            Completion {
3395                                old_range,
3396                                new_text,
3397                                label: label.unwrap_or_else(|| {
3398                                    CodeLabel::plain(
3399                                        lsp_completion.label.clone(),
3400                                        lsp_completion.filter_text.as_deref(),
3401                                    )
3402                                }),
3403                                lsp_completion,
3404                            }
3405                        })
3406                    })
3407                });
3408
3409                Ok(futures::future::join_all(completions).await)
3410            })
3411        } else if let Some(project_id) = self.remote_id() {
3412            let rpc = self.client.clone();
3413            let message = proto::GetCompletions {
3414                project_id,
3415                buffer_id,
3416                position: Some(language::proto::serialize_anchor(&anchor)),
3417                version: serialize_version(&source_buffer.version()),
3418            };
3419            cx.spawn_weak(|_, mut cx| async move {
3420                let response = rpc.request(message).await?;
3421
3422                source_buffer_handle
3423                    .update(&mut cx, |buffer, _| {
3424                        buffer.wait_for_version(deserialize_version(response.version))
3425                    })
3426                    .await;
3427
3428                let completions = response.completions.into_iter().map(|completion| {
3429                    language::proto::deserialize_completion(completion, language.clone())
3430                });
3431                futures::future::try_join_all(completions).await
3432            })
3433        } else {
3434            Task::ready(Ok(Default::default()))
3435        }
3436    }
3437
3438    pub fn apply_additional_edits_for_completion(
3439        &self,
3440        buffer_handle: ModelHandle<Buffer>,
3441        completion: Completion,
3442        push_to_history: bool,
3443        cx: &mut ModelContext<Self>,
3444    ) -> Task<Result<Option<Transaction>>> {
3445        let buffer = buffer_handle.read(cx);
3446        let buffer_id = buffer.remote_id();
3447
3448        if self.is_local() {
3449            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3450            {
3451                server.clone()
3452            } else {
3453                return Task::ready(Ok(Default::default()));
3454            };
3455
3456            cx.spawn(|this, mut cx| async move {
3457                let resolved_completion = lang_server
3458                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3459                    .await?;
3460                if let Some(edits) = resolved_completion.additional_text_edits {
3461                    let edits = this
3462                        .update(&mut cx, |this, cx| {
3463                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3464                        })
3465                        .await?;
3466                    buffer_handle.update(&mut cx, |buffer, cx| {
3467                        buffer.finalize_last_transaction();
3468                        buffer.start_transaction();
3469                        for (range, text) in edits {
3470                            buffer.edit([(range, text)], None, cx);
3471                        }
3472                        let transaction = if buffer.end_transaction(cx).is_some() {
3473                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3474                            if !push_to_history {
3475                                buffer.forget_transaction(transaction.id);
3476                            }
3477                            Some(transaction)
3478                        } else {
3479                            None
3480                        };
3481                        Ok(transaction)
3482                    })
3483                } else {
3484                    Ok(None)
3485                }
3486            })
3487        } else if let Some(project_id) = self.remote_id() {
3488            let client = self.client.clone();
3489            cx.spawn(|_, mut cx| async move {
3490                let response = client
3491                    .request(proto::ApplyCompletionAdditionalEdits {
3492                        project_id,
3493                        buffer_id,
3494                        completion: Some(language::proto::serialize_completion(&completion)),
3495                    })
3496                    .await?;
3497
3498                if let Some(transaction) = response.transaction {
3499                    let transaction = language::proto::deserialize_transaction(transaction)?;
3500                    buffer_handle
3501                        .update(&mut cx, |buffer, _| {
3502                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3503                        })
3504                        .await;
3505                    if push_to_history {
3506                        buffer_handle.update(&mut cx, |buffer, _| {
3507                            buffer.push_transaction(transaction.clone(), Instant::now());
3508                        });
3509                    }
3510                    Ok(Some(transaction))
3511                } else {
3512                    Ok(None)
3513                }
3514            })
3515        } else {
3516            Task::ready(Err(anyhow!("project does not have a remote id")))
3517        }
3518    }
3519
3520    pub fn code_actions<T: Clone + ToOffset>(
3521        &self,
3522        buffer_handle: &ModelHandle<Buffer>,
3523        range: Range<T>,
3524        cx: &mut ModelContext<Self>,
3525    ) -> Task<Result<Vec<CodeAction>>> {
3526        let buffer_handle = buffer_handle.clone();
3527        let buffer = buffer_handle.read(cx);
3528        let snapshot = buffer.snapshot();
3529        let relevant_diagnostics = snapshot
3530            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3531            .map(|entry| entry.to_lsp_diagnostic_stub())
3532            .collect();
3533        let buffer_id = buffer.remote_id();
3534        let worktree;
3535        let buffer_abs_path;
3536        if let Some(file) = File::from_dyn(buffer.file()) {
3537            worktree = file.worktree.clone();
3538            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3539        } else {
3540            return Task::ready(Ok(Default::default()));
3541        };
3542        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3543
3544        if worktree.read(cx).as_local().is_some() {
3545            let buffer_abs_path = buffer_abs_path.unwrap();
3546            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3547            {
3548                server.clone()
3549            } else {
3550                return Task::ready(Ok(Default::default()));
3551            };
3552
3553            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3554            cx.foreground().spawn(async move {
3555                if lang_server.capabilities().code_action_provider.is_none() {
3556                    return Ok(Default::default());
3557                }
3558
3559                Ok(lang_server
3560                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3561                        text_document: lsp::TextDocumentIdentifier::new(
3562                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3563                        ),
3564                        range: lsp_range,
3565                        work_done_progress_params: Default::default(),
3566                        partial_result_params: Default::default(),
3567                        context: lsp::CodeActionContext {
3568                            diagnostics: relevant_diagnostics,
3569                            only: Some(vec![
3570                                lsp::CodeActionKind::QUICKFIX,
3571                                lsp::CodeActionKind::REFACTOR,
3572                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3573                                lsp::CodeActionKind::SOURCE,
3574                            ]),
3575                        },
3576                    })
3577                    .await?
3578                    .unwrap_or_default()
3579                    .into_iter()
3580                    .filter_map(|entry| {
3581                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3582                            Some(CodeAction {
3583                                range: range.clone(),
3584                                lsp_action,
3585                            })
3586                        } else {
3587                            None
3588                        }
3589                    })
3590                    .collect())
3591            })
3592        } else if let Some(project_id) = self.remote_id() {
3593            let rpc = self.client.clone();
3594            let version = buffer.version();
3595            cx.spawn_weak(|_, mut cx| async move {
3596                let response = rpc
3597                    .request(proto::GetCodeActions {
3598                        project_id,
3599                        buffer_id,
3600                        start: Some(language::proto::serialize_anchor(&range.start)),
3601                        end: Some(language::proto::serialize_anchor(&range.end)),
3602                        version: serialize_version(&version),
3603                    })
3604                    .await?;
3605
3606                buffer_handle
3607                    .update(&mut cx, |buffer, _| {
3608                        buffer.wait_for_version(deserialize_version(response.version))
3609                    })
3610                    .await;
3611
3612                response
3613                    .actions
3614                    .into_iter()
3615                    .map(language::proto::deserialize_code_action)
3616                    .collect()
3617            })
3618        } else {
3619            Task::ready(Ok(Default::default()))
3620        }
3621    }
3622
3623    pub fn apply_code_action(
3624        &self,
3625        buffer_handle: ModelHandle<Buffer>,
3626        mut action: CodeAction,
3627        push_to_history: bool,
3628        cx: &mut ModelContext<Self>,
3629    ) -> Task<Result<ProjectTransaction>> {
3630        if self.is_local() {
3631            let buffer = buffer_handle.read(cx);
3632            let (lsp_adapter, lang_server) =
3633                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3634                    (adapter.clone(), server.clone())
3635                } else {
3636                    return Task::ready(Ok(Default::default()));
3637                };
3638            let range = action.range.to_point_utf16(buffer);
3639
3640            cx.spawn(|this, mut cx| async move {
3641                if let Some(lsp_range) = action
3642                    .lsp_action
3643                    .data
3644                    .as_mut()
3645                    .and_then(|d| d.get_mut("codeActionParams"))
3646                    .and_then(|d| d.get_mut("range"))
3647                {
3648                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3649                    action.lsp_action = lang_server
3650                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3651                        .await?;
3652                } else {
3653                    let actions = this
3654                        .update(&mut cx, |this, cx| {
3655                            this.code_actions(&buffer_handle, action.range, cx)
3656                        })
3657                        .await?;
3658                    action.lsp_action = actions
3659                        .into_iter()
3660                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3661                        .ok_or_else(|| anyhow!("code action is outdated"))?
3662                        .lsp_action;
3663                }
3664
3665                if let Some(edit) = action.lsp_action.edit {
3666                    if edit.changes.is_some() || edit.document_changes.is_some() {
3667                        return Self::deserialize_workspace_edit(
3668                            this,
3669                            edit,
3670                            push_to_history,
3671                            lsp_adapter.clone(),
3672                            lang_server.clone(),
3673                            &mut cx,
3674                        )
3675                        .await;
3676                    }
3677                }
3678
3679                if let Some(command) = action.lsp_action.command {
3680                    this.update(&mut cx, |this, _| {
3681                        this.last_workspace_edits_by_language_server
3682                            .remove(&lang_server.server_id());
3683                    });
3684                    lang_server
3685                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3686                            command: command.command,
3687                            arguments: command.arguments.unwrap_or_default(),
3688                            ..Default::default()
3689                        })
3690                        .await?;
3691                    return Ok(this.update(&mut cx, |this, _| {
3692                        this.last_workspace_edits_by_language_server
3693                            .remove(&lang_server.server_id())
3694                            .unwrap_or_default()
3695                    }));
3696                }
3697
3698                Ok(ProjectTransaction::default())
3699            })
3700        } else if let Some(project_id) = self.remote_id() {
3701            let client = self.client.clone();
3702            let request = proto::ApplyCodeAction {
3703                project_id,
3704                buffer_id: buffer_handle.read(cx).remote_id(),
3705                action: Some(language::proto::serialize_code_action(&action)),
3706            };
3707            cx.spawn(|this, mut cx| async move {
3708                let response = client
3709                    .request(request)
3710                    .await?
3711                    .transaction
3712                    .ok_or_else(|| anyhow!("missing transaction"))?;
3713                this.update(&mut cx, |this, cx| {
3714                    this.deserialize_project_transaction(response, push_to_history, cx)
3715                })
3716                .await
3717            })
3718        } else {
3719            Task::ready(Err(anyhow!("project does not have a remote id")))
3720        }
3721    }
3722
3723    async fn deserialize_workspace_edit(
3724        this: ModelHandle<Self>,
3725        edit: lsp::WorkspaceEdit,
3726        push_to_history: bool,
3727        lsp_adapter: Arc<CachedLspAdapter>,
3728        language_server: Arc<LanguageServer>,
3729        cx: &mut AsyncAppContext,
3730    ) -> Result<ProjectTransaction> {
3731        let fs = this.read_with(cx, |this, _| this.fs.clone());
3732        let mut operations = Vec::new();
3733        if let Some(document_changes) = edit.document_changes {
3734            match document_changes {
3735                lsp::DocumentChanges::Edits(edits) => {
3736                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3737                }
3738                lsp::DocumentChanges::Operations(ops) => operations = ops,
3739            }
3740        } else if let Some(changes) = edit.changes {
3741            operations.extend(changes.into_iter().map(|(uri, edits)| {
3742                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3743                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3744                        uri,
3745                        version: None,
3746                    },
3747                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3748                })
3749            }));
3750        }
3751
3752        let mut project_transaction = ProjectTransaction::default();
3753        for operation in operations {
3754            match operation {
3755                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3756                    let abs_path = op
3757                        .uri
3758                        .to_file_path()
3759                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3760
3761                    if let Some(parent_path) = abs_path.parent() {
3762                        fs.create_dir(parent_path).await?;
3763                    }
3764                    if abs_path.ends_with("/") {
3765                        fs.create_dir(&abs_path).await?;
3766                    } else {
3767                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3768                            .await?;
3769                    }
3770                }
3771                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3772                    let source_abs_path = op
3773                        .old_uri
3774                        .to_file_path()
3775                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3776                    let target_abs_path = op
3777                        .new_uri
3778                        .to_file_path()
3779                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3780                    fs.rename(
3781                        &source_abs_path,
3782                        &target_abs_path,
3783                        op.options.map(Into::into).unwrap_or_default(),
3784                    )
3785                    .await?;
3786                }
3787                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3788                    let abs_path = op
3789                        .uri
3790                        .to_file_path()
3791                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3792                    let options = op.options.map(Into::into).unwrap_or_default();
3793                    if abs_path.ends_with("/") {
3794                        fs.remove_dir(&abs_path, options).await?;
3795                    } else {
3796                        fs.remove_file(&abs_path, options).await?;
3797                    }
3798                }
3799                lsp::DocumentChangeOperation::Edit(op) => {
3800                    let buffer_to_edit = this
3801                        .update(cx, |this, cx| {
3802                            this.open_local_buffer_via_lsp(
3803                                op.text_document.uri,
3804                                language_server.server_id(),
3805                                lsp_adapter.name.clone(),
3806                                cx,
3807                            )
3808                        })
3809                        .await?;
3810
3811                    let edits = this
3812                        .update(cx, |this, cx| {
3813                            let edits = op.edits.into_iter().map(|edit| match edit {
3814                                lsp::OneOf::Left(edit) => edit,
3815                                lsp::OneOf::Right(edit) => edit.text_edit,
3816                            });
3817                            this.edits_from_lsp(
3818                                &buffer_to_edit,
3819                                edits,
3820                                op.text_document.version,
3821                                cx,
3822                            )
3823                        })
3824                        .await?;
3825
3826                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3827                        buffer.finalize_last_transaction();
3828                        buffer.start_transaction();
3829                        for (range, text) in edits {
3830                            buffer.edit([(range, text)], None, cx);
3831                        }
3832                        let transaction = if buffer.end_transaction(cx).is_some() {
3833                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3834                            if !push_to_history {
3835                                buffer.forget_transaction(transaction.id);
3836                            }
3837                            Some(transaction)
3838                        } else {
3839                            None
3840                        };
3841
3842                        transaction
3843                    });
3844                    if let Some(transaction) = transaction {
3845                        project_transaction.0.insert(buffer_to_edit, transaction);
3846                    }
3847                }
3848            }
3849        }
3850
3851        Ok(project_transaction)
3852    }
3853
3854    pub fn prepare_rename<T: ToPointUtf16>(
3855        &self,
3856        buffer: ModelHandle<Buffer>,
3857        position: T,
3858        cx: &mut ModelContext<Self>,
3859    ) -> Task<Result<Option<Range<Anchor>>>> {
3860        let position = position.to_point_utf16(buffer.read(cx));
3861        self.request_lsp(buffer, PrepareRename { position }, cx)
3862    }
3863
3864    pub fn perform_rename<T: ToPointUtf16>(
3865        &self,
3866        buffer: ModelHandle<Buffer>,
3867        position: T,
3868        new_name: String,
3869        push_to_history: bool,
3870        cx: &mut ModelContext<Self>,
3871    ) -> Task<Result<ProjectTransaction>> {
3872        let position = position.to_point_utf16(buffer.read(cx));
3873        self.request_lsp(
3874            buffer,
3875            PerformRename {
3876                position,
3877                new_name,
3878                push_to_history,
3879            },
3880            cx,
3881        )
3882    }
3883
3884    #[allow(clippy::type_complexity)]
3885    pub fn search(
3886        &self,
3887        query: SearchQuery,
3888        cx: &mut ModelContext<Self>,
3889    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
3890        if self.is_local() {
3891            let snapshots = self
3892                .visible_worktrees(cx)
3893                .filter_map(|tree| {
3894                    let tree = tree.read(cx).as_local()?;
3895                    Some(tree.snapshot())
3896                })
3897                .collect::<Vec<_>>();
3898
3899            let background = cx.background().clone();
3900            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
3901            if path_count == 0 {
3902                return Task::ready(Ok(Default::default()));
3903            }
3904            let workers = background.num_cpus().min(path_count);
3905            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
3906            cx.background()
3907                .spawn({
3908                    let fs = self.fs.clone();
3909                    let background = cx.background().clone();
3910                    let query = query.clone();
3911                    async move {
3912                        let fs = &fs;
3913                        let query = &query;
3914                        let matching_paths_tx = &matching_paths_tx;
3915                        let paths_per_worker = (path_count + workers - 1) / workers;
3916                        let snapshots = &snapshots;
3917                        background
3918                            .scoped(|scope| {
3919                                for worker_ix in 0..workers {
3920                                    let worker_start_ix = worker_ix * paths_per_worker;
3921                                    let worker_end_ix = worker_start_ix + paths_per_worker;
3922                                    scope.spawn(async move {
3923                                        let mut snapshot_start_ix = 0;
3924                                        let mut abs_path = PathBuf::new();
3925                                        for snapshot in snapshots {
3926                                            let snapshot_end_ix =
3927                                                snapshot_start_ix + snapshot.visible_file_count();
3928                                            if worker_end_ix <= snapshot_start_ix {
3929                                                break;
3930                                            } else if worker_start_ix > snapshot_end_ix {
3931                                                snapshot_start_ix = snapshot_end_ix;
3932                                                continue;
3933                                            } else {
3934                                                let start_in_snapshot = worker_start_ix
3935                                                    .saturating_sub(snapshot_start_ix);
3936                                                let end_in_snapshot =
3937                                                    cmp::min(worker_end_ix, snapshot_end_ix)
3938                                                        - snapshot_start_ix;
3939
3940                                                for entry in snapshot
3941                                                    .files(false, start_in_snapshot)
3942                                                    .take(end_in_snapshot - start_in_snapshot)
3943                                                {
3944                                                    if matching_paths_tx.is_closed() {
3945                                                        break;
3946                                                    }
3947
3948                                                    abs_path.clear();
3949                                                    abs_path.push(&snapshot.abs_path());
3950                                                    abs_path.push(&entry.path);
3951                                                    let matches = if let Some(file) =
3952                                                        fs.open_sync(&abs_path).await.log_err()
3953                                                    {
3954                                                        query.detect(file).unwrap_or(false)
3955                                                    } else {
3956                                                        false
3957                                                    };
3958
3959                                                    if matches {
3960                                                        let project_path =
3961                                                            (snapshot.id(), entry.path.clone());
3962                                                        if matching_paths_tx
3963                                                            .send(project_path)
3964                                                            .await
3965                                                            .is_err()
3966                                                        {
3967                                                            break;
3968                                                        }
3969                                                    }
3970                                                }
3971
3972                                                snapshot_start_ix = snapshot_end_ix;
3973                                            }
3974                                        }
3975                                    });
3976                                }
3977                            })
3978                            .await;
3979                    }
3980                })
3981                .detach();
3982
3983            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
3984            let open_buffers = self
3985                .opened_buffers
3986                .values()
3987                .filter_map(|b| b.upgrade(cx))
3988                .collect::<HashSet<_>>();
3989            cx.spawn(|this, cx| async move {
3990                for buffer in &open_buffers {
3991                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
3992                    buffers_tx.send((buffer.clone(), snapshot)).await?;
3993                }
3994
3995                let open_buffers = Rc::new(RefCell::new(open_buffers));
3996                while let Some(project_path) = matching_paths_rx.next().await {
3997                    if buffers_tx.is_closed() {
3998                        break;
3999                    }
4000
4001                    let this = this.clone();
4002                    let open_buffers = open_buffers.clone();
4003                    let buffers_tx = buffers_tx.clone();
4004                    cx.spawn(|mut cx| async move {
4005                        if let Some(buffer) = this
4006                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4007                            .await
4008                            .log_err()
4009                        {
4010                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4011                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4012                                buffers_tx.send((buffer, snapshot)).await?;
4013                            }
4014                        }
4015
4016                        Ok::<_, anyhow::Error>(())
4017                    })
4018                    .detach();
4019                }
4020
4021                Ok::<_, anyhow::Error>(())
4022            })
4023            .detach_and_log_err(cx);
4024
4025            let background = cx.background().clone();
4026            cx.background().spawn(async move {
4027                let query = &query;
4028                let mut matched_buffers = Vec::new();
4029                for _ in 0..workers {
4030                    matched_buffers.push(HashMap::default());
4031                }
4032                background
4033                    .scoped(|scope| {
4034                        for worker_matched_buffers in matched_buffers.iter_mut() {
4035                            let mut buffers_rx = buffers_rx.clone();
4036                            scope.spawn(async move {
4037                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4038                                    let buffer_matches = query
4039                                        .search(snapshot.as_rope())
4040                                        .await
4041                                        .iter()
4042                                        .map(|range| {
4043                                            snapshot.anchor_before(range.start)
4044                                                ..snapshot.anchor_after(range.end)
4045                                        })
4046                                        .collect::<Vec<_>>();
4047                                    if !buffer_matches.is_empty() {
4048                                        worker_matched_buffers
4049                                            .insert(buffer.clone(), buffer_matches);
4050                                    }
4051                                }
4052                            });
4053                        }
4054                    })
4055                    .await;
4056                Ok(matched_buffers.into_iter().flatten().collect())
4057            })
4058        } else if let Some(project_id) = self.remote_id() {
4059            let request = self.client.request(query.to_proto(project_id));
4060            cx.spawn(|this, mut cx| async move {
4061                let response = request.await?;
4062                let mut result = HashMap::default();
4063                for location in response.locations {
4064                    let target_buffer = this
4065                        .update(&mut cx, |this, cx| {
4066                            this.wait_for_buffer(location.buffer_id, cx)
4067                        })
4068                        .await?;
4069                    let start = location
4070                        .start
4071                        .and_then(deserialize_anchor)
4072                        .ok_or_else(|| anyhow!("missing target start"))?;
4073                    let end = location
4074                        .end
4075                        .and_then(deserialize_anchor)
4076                        .ok_or_else(|| anyhow!("missing target end"))?;
4077                    result
4078                        .entry(target_buffer)
4079                        .or_insert(Vec::new())
4080                        .push(start..end)
4081                }
4082                Ok(result)
4083            })
4084        } else {
4085            Task::ready(Ok(Default::default()))
4086        }
4087    }
4088
4089    fn request_lsp<R: LspCommand>(
4090        &self,
4091        buffer_handle: ModelHandle<Buffer>,
4092        request: R,
4093        cx: &mut ModelContext<Self>,
4094    ) -> Task<Result<R::Response>>
4095    where
4096        <R::LspRequest as lsp::request::Request>::Result: Send,
4097    {
4098        let buffer = buffer_handle.read(cx);
4099        if self.is_local() {
4100            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4101            if let Some((file, language_server)) = file.zip(
4102                self.language_server_for_buffer(buffer, cx)
4103                    .map(|(_, server)| server.clone()),
4104            ) {
4105                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4106                return cx.spawn(|this, cx| async move {
4107                    if !request.check_capabilities(language_server.capabilities()) {
4108                        return Ok(Default::default());
4109                    }
4110
4111                    let response = language_server
4112                        .request::<R::LspRequest>(lsp_params)
4113                        .await
4114                        .context("lsp request failed")?;
4115                    request
4116                        .response_from_lsp(response, this, buffer_handle, cx)
4117                        .await
4118                });
4119            }
4120        } else if let Some(project_id) = self.remote_id() {
4121            let rpc = self.client.clone();
4122            let message = request.to_proto(project_id, buffer);
4123            return cx.spawn(|this, cx| async move {
4124                let response = rpc.request(message).await?;
4125                request
4126                    .response_from_proto(response, this, buffer_handle, cx)
4127                    .await
4128            });
4129        }
4130        Task::ready(Ok(Default::default()))
4131    }
4132
4133    pub fn find_or_create_local_worktree(
4134        &mut self,
4135        abs_path: impl AsRef<Path>,
4136        visible: bool,
4137        cx: &mut ModelContext<Self>,
4138    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4139        let abs_path = abs_path.as_ref();
4140        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4141            Task::ready(Ok((tree, relative_path)))
4142        } else {
4143            let worktree = self.create_local_worktree(abs_path, visible, cx);
4144            cx.foreground()
4145                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4146        }
4147    }
4148
4149    pub fn find_local_worktree(
4150        &self,
4151        abs_path: &Path,
4152        cx: &AppContext,
4153    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4154        for tree in &self.worktrees {
4155            if let Some(tree) = tree.upgrade(cx) {
4156                if let Some(relative_path) = tree
4157                    .read(cx)
4158                    .as_local()
4159                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4160                {
4161                    return Some((tree.clone(), relative_path.into()));
4162                }
4163            }
4164        }
4165        None
4166    }
4167
4168    pub fn is_shared(&self) -> bool {
4169        match &self.client_state {
4170            Some(ProjectClientState::Local { .. }) => true,
4171            _ => false,
4172        }
4173    }
4174
4175    fn create_local_worktree(
4176        &mut self,
4177        abs_path: impl AsRef<Path>,
4178        visible: bool,
4179        cx: &mut ModelContext<Self>,
4180    ) -> Task<Result<ModelHandle<Worktree>>> {
4181        let fs = self.fs.clone();
4182        let client = self.client.clone();
4183        let next_entry_id = self.next_entry_id.clone();
4184        let path: Arc<Path> = abs_path.as_ref().into();
4185        let task = self
4186            .loading_local_worktrees
4187            .entry(path.clone())
4188            .or_insert_with(|| {
4189                cx.spawn(|project, mut cx| {
4190                    async move {
4191                        let worktree = Worktree::local(
4192                            client.clone(),
4193                            path.clone(),
4194                            visible,
4195                            fs,
4196                            next_entry_id,
4197                            &mut cx,
4198                        )
4199                        .await;
4200                        project.update(&mut cx, |project, _| {
4201                            project.loading_local_worktrees.remove(&path);
4202                        });
4203                        let worktree = worktree?;
4204
4205                        let project_id = project.update(&mut cx, |project, cx| {
4206                            project.add_worktree(&worktree, cx);
4207                            project.remote_id()
4208                        });
4209
4210                        if let Some(project_id) = project_id {
4211                            worktree
4212                                .update(&mut cx, |worktree, cx| {
4213                                    worktree.as_local_mut().unwrap().share(project_id, cx)
4214                                })
4215                                .await
4216                                .log_err();
4217                        }
4218
4219                        Ok(worktree)
4220                    }
4221                    .map_err(Arc::new)
4222                })
4223                .shared()
4224            })
4225            .clone();
4226        cx.foreground().spawn(async move {
4227            match task.await {
4228                Ok(worktree) => Ok(worktree),
4229                Err(err) => Err(anyhow!("{}", err)),
4230            }
4231        })
4232    }
4233
4234    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4235        self.worktrees.retain(|worktree| {
4236            if let Some(worktree) = worktree.upgrade(cx) {
4237                let id = worktree.read(cx).id();
4238                if id == id_to_remove {
4239                    cx.emit(Event::WorktreeRemoved(id));
4240                    false
4241                } else {
4242                    true
4243                }
4244            } else {
4245                false
4246            }
4247        });
4248        self.metadata_changed(cx);
4249        cx.notify();
4250    }
4251
4252    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4253        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4254        if worktree.read(cx).is_local() {
4255            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4256                worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
4257                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4258                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4259                }
4260            })
4261            .detach();
4262        }
4263
4264        let push_strong_handle = {
4265            let worktree = worktree.read(cx);
4266            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4267        };
4268        if push_strong_handle {
4269            self.worktrees
4270                .push(WorktreeHandle::Strong(worktree.clone()));
4271        } else {
4272            self.worktrees
4273                .push(WorktreeHandle::Weak(worktree.downgrade()));
4274        }
4275
4276        self.metadata_changed(cx);
4277        cx.observe_release(worktree, |this, worktree, cx| {
4278            this.remove_worktree(worktree.id(), cx);
4279            cx.notify();
4280        })
4281        .detach();
4282
4283        cx.emit(Event::WorktreeAdded);
4284        cx.notify();
4285    }
4286
4287    fn update_local_worktree_buffers(
4288        &mut self,
4289        worktree_handle: ModelHandle<Worktree>,
4290        cx: &mut ModelContext<Self>,
4291    ) {
4292        let snapshot = worktree_handle.read(cx).snapshot();
4293        let mut buffers_to_delete = Vec::new();
4294        let mut renamed_buffers = Vec::new();
4295        for (buffer_id, buffer) in &self.opened_buffers {
4296            if let Some(buffer) = buffer.upgrade(cx) {
4297                buffer.update(cx, |buffer, cx| {
4298                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4299                        if old_file.worktree != worktree_handle {
4300                            return;
4301                        }
4302
4303                        let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4304                        {
4305                            File {
4306                                is_local: true,
4307                                entry_id: entry.id,
4308                                mtime: entry.mtime,
4309                                path: entry.path.clone(),
4310                                worktree: worktree_handle.clone(),
4311                                is_deleted: false,
4312                            }
4313                        } else if let Some(entry) =
4314                            snapshot.entry_for_path(old_file.path().as_ref())
4315                        {
4316                            File {
4317                                is_local: true,
4318                                entry_id: entry.id,
4319                                mtime: entry.mtime,
4320                                path: entry.path.clone(),
4321                                worktree: worktree_handle.clone(),
4322                                is_deleted: false,
4323                            }
4324                        } else {
4325                            File {
4326                                is_local: true,
4327                                entry_id: old_file.entry_id,
4328                                path: old_file.path().clone(),
4329                                mtime: old_file.mtime(),
4330                                worktree: worktree_handle.clone(),
4331                                is_deleted: true,
4332                            }
4333                        };
4334
4335                        let old_path = old_file.abs_path(cx);
4336                        if new_file.abs_path(cx) != old_path {
4337                            renamed_buffers.push((cx.handle(), old_path));
4338                        }
4339
4340                        if let Some(project_id) = self.remote_id() {
4341                            self.client
4342                                .send(proto::UpdateBufferFile {
4343                                    project_id,
4344                                    buffer_id: *buffer_id as u64,
4345                                    file: Some(new_file.to_proto()),
4346                                })
4347                                .log_err();
4348                        }
4349                        buffer.file_updated(Arc::new(new_file), cx).detach();
4350                    }
4351                });
4352            } else {
4353                buffers_to_delete.push(*buffer_id);
4354            }
4355        }
4356
4357        for buffer_id in buffers_to_delete {
4358            self.opened_buffers.remove(&buffer_id);
4359        }
4360
4361        for (buffer, old_path) in renamed_buffers {
4362            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4363            self.assign_language_to_buffer(&buffer, cx);
4364            self.register_buffer_with_language_server(&buffer, cx);
4365        }
4366    }
4367
4368    fn update_local_worktree_buffers_git_repos(
4369        &mut self,
4370        worktree: ModelHandle<Worktree>,
4371        repos: &[GitRepositoryEntry],
4372        cx: &mut ModelContext<Self>,
4373    ) {
4374        for (_, buffer) in &self.opened_buffers {
4375            if let Some(buffer) = buffer.upgrade(cx) {
4376                let file = match File::from_dyn(buffer.read(cx).file()) {
4377                    Some(file) => file,
4378                    None => continue,
4379                };
4380                if file.worktree != worktree {
4381                    continue;
4382                }
4383
4384                let path = file.path().clone();
4385
4386                let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4387                    Some(repo) => repo.clone(),
4388                    None => return,
4389                };
4390
4391                let relative_repo = match path.strip_prefix(repo.content_path) {
4392                    Ok(relative_repo) => relative_repo.to_owned(),
4393                    Err(_) => return,
4394                };
4395
4396                let remote_id = self.remote_id();
4397                let client = self.client.clone();
4398
4399                cx.spawn(|_, mut cx| async move {
4400                    let diff_base = cx
4401                        .background()
4402                        .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4403                        .await;
4404
4405                    let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4406                        buffer.update_diff_base(diff_base.clone(), cx);
4407                        buffer.remote_id()
4408                    });
4409
4410                    if let Some(project_id) = remote_id {
4411                        client
4412                            .send(proto::UpdateDiffBase {
4413                                project_id,
4414                                buffer_id: buffer_id as u64,
4415                                diff_base,
4416                            })
4417                            .log_err();
4418                    }
4419                })
4420                .detach();
4421            }
4422        }
4423    }
4424
4425    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4426        let new_active_entry = entry.and_then(|project_path| {
4427            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4428            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4429            Some(entry.id)
4430        });
4431        if new_active_entry != self.active_entry {
4432            self.active_entry = new_active_entry;
4433            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4434        }
4435    }
4436
4437    pub fn language_servers_running_disk_based_diagnostics(
4438        &self,
4439    ) -> impl Iterator<Item = usize> + '_ {
4440        self.language_server_statuses
4441            .iter()
4442            .filter_map(|(id, status)| {
4443                if status.has_pending_diagnostic_updates {
4444                    Some(*id)
4445                } else {
4446                    None
4447                }
4448            })
4449    }
4450
4451    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4452        let mut summary = DiagnosticSummary::default();
4453        for (_, path_summary) in self.diagnostic_summaries(cx) {
4454            summary.error_count += path_summary.error_count;
4455            summary.warning_count += path_summary.warning_count;
4456        }
4457        summary
4458    }
4459
4460    pub fn diagnostic_summaries<'a>(
4461        &'a self,
4462        cx: &'a AppContext,
4463    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4464        self.visible_worktrees(cx).flat_map(move |worktree| {
4465            let worktree = worktree.read(cx);
4466            let worktree_id = worktree.id();
4467            worktree
4468                .diagnostic_summaries()
4469                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4470        })
4471    }
4472
4473    pub fn disk_based_diagnostics_started(
4474        &mut self,
4475        language_server_id: usize,
4476        cx: &mut ModelContext<Self>,
4477    ) {
4478        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4479    }
4480
4481    pub fn disk_based_diagnostics_finished(
4482        &mut self,
4483        language_server_id: usize,
4484        cx: &mut ModelContext<Self>,
4485    ) {
4486        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4487    }
4488
4489    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4490        self.active_entry
4491    }
4492
4493    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4494        self.worktree_for_id(path.worktree_id, cx)?
4495            .read(cx)
4496            .entry_for_path(&path.path)
4497            .cloned()
4498    }
4499
4500    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4501        let worktree = self.worktree_for_entry(entry_id, cx)?;
4502        let worktree = worktree.read(cx);
4503        let worktree_id = worktree.id();
4504        let path = worktree.entry_for_id(entry_id)?.path.clone();
4505        Some(ProjectPath { worktree_id, path })
4506    }
4507
4508    // RPC message handlers
4509
4510    async fn handle_unshare_project(
4511        this: ModelHandle<Self>,
4512        _: TypedEnvelope<proto::UnshareProject>,
4513        _: Arc<Client>,
4514        mut cx: AsyncAppContext,
4515    ) -> Result<()> {
4516        this.update(&mut cx, |this, cx| {
4517            if this.is_local() {
4518                this.unshare(cx)?;
4519            } else {
4520                this.disconnected_from_host(cx);
4521            }
4522            Ok(())
4523        })
4524    }
4525
4526    async fn handle_add_collaborator(
4527        this: ModelHandle<Self>,
4528        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4529        _: Arc<Client>,
4530        mut cx: AsyncAppContext,
4531    ) -> Result<()> {
4532        let collaborator = envelope
4533            .payload
4534            .collaborator
4535            .take()
4536            .ok_or_else(|| anyhow!("empty collaborator"))?;
4537
4538        let collaborator = Collaborator::from_proto(collaborator);
4539        this.update(&mut cx, |this, cx| {
4540            this.collaborators
4541                .insert(collaborator.peer_id, collaborator);
4542            cx.notify();
4543        });
4544
4545        Ok(())
4546    }
4547
4548    async fn handle_remove_collaborator(
4549        this: ModelHandle<Self>,
4550        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4551        _: Arc<Client>,
4552        mut cx: AsyncAppContext,
4553    ) -> Result<()> {
4554        this.update(&mut cx, |this, cx| {
4555            let peer_id = PeerId(envelope.payload.peer_id);
4556            let replica_id = this
4557                .collaborators
4558                .remove(&peer_id)
4559                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4560                .replica_id;
4561            for buffer in this.opened_buffers.values() {
4562                if let Some(buffer) = buffer.upgrade(cx) {
4563                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4564                }
4565            }
4566            this.shared_buffers.remove(&peer_id);
4567
4568            cx.emit(Event::CollaboratorLeft(peer_id));
4569            cx.notify();
4570            Ok(())
4571        })
4572    }
4573
4574    async fn handle_update_project(
4575        this: ModelHandle<Self>,
4576        envelope: TypedEnvelope<proto::UpdateProject>,
4577        client: Arc<Client>,
4578        mut cx: AsyncAppContext,
4579    ) -> Result<()> {
4580        this.update(&mut cx, |this, cx| {
4581            let replica_id = this.replica_id();
4582            let remote_id = this.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
4583
4584            let mut old_worktrees_by_id = this
4585                .worktrees
4586                .drain(..)
4587                .filter_map(|worktree| {
4588                    let worktree = worktree.upgrade(cx)?;
4589                    Some((worktree.read(cx).id(), worktree))
4590                })
4591                .collect::<HashMap<_, _>>();
4592
4593            for worktree in envelope.payload.worktrees {
4594                if let Some(old_worktree) =
4595                    old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
4596                {
4597                    this.worktrees.push(WorktreeHandle::Strong(old_worktree));
4598                } else {
4599                    let worktree =
4600                        Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
4601                    this.add_worktree(&worktree, cx);
4602                }
4603            }
4604
4605            this.metadata_changed(cx);
4606            for (id, _) in old_worktrees_by_id {
4607                cx.emit(Event::WorktreeRemoved(id));
4608            }
4609
4610            Ok(())
4611        })
4612    }
4613
4614    async fn handle_update_worktree(
4615        this: ModelHandle<Self>,
4616        envelope: TypedEnvelope<proto::UpdateWorktree>,
4617        _: Arc<Client>,
4618        mut cx: AsyncAppContext,
4619    ) -> Result<()> {
4620        this.update(&mut cx, |this, cx| {
4621            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4622            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4623                worktree.update(cx, |worktree, _| {
4624                    let worktree = worktree.as_remote_mut().unwrap();
4625                    worktree.update_from_remote(envelope.payload);
4626                });
4627            }
4628            Ok(())
4629        })
4630    }
4631
4632    async fn handle_create_project_entry(
4633        this: ModelHandle<Self>,
4634        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4635        _: Arc<Client>,
4636        mut cx: AsyncAppContext,
4637    ) -> Result<proto::ProjectEntryResponse> {
4638        let worktree = this.update(&mut cx, |this, cx| {
4639            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4640            this.worktree_for_id(worktree_id, cx)
4641                .ok_or_else(|| anyhow!("worktree not found"))
4642        })?;
4643        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4644        let entry = worktree
4645            .update(&mut cx, |worktree, cx| {
4646                let worktree = worktree.as_local_mut().unwrap();
4647                let path = PathBuf::from(OsString::from_vec(envelope.payload.path));
4648                worktree.create_entry(path, envelope.payload.is_directory, cx)
4649            })
4650            .await?;
4651        Ok(proto::ProjectEntryResponse {
4652            entry: Some((&entry).into()),
4653            worktree_scan_id: worktree_scan_id as u64,
4654        })
4655    }
4656
4657    async fn handle_rename_project_entry(
4658        this: ModelHandle<Self>,
4659        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4660        _: Arc<Client>,
4661        mut cx: AsyncAppContext,
4662    ) -> Result<proto::ProjectEntryResponse> {
4663        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4664        let worktree = this.read_with(&cx, |this, cx| {
4665            this.worktree_for_entry(entry_id, cx)
4666                .ok_or_else(|| anyhow!("worktree not found"))
4667        })?;
4668        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4669        let entry = worktree
4670            .update(&mut cx, |worktree, cx| {
4671                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4672                worktree
4673                    .as_local_mut()
4674                    .unwrap()
4675                    .rename_entry(entry_id, new_path, cx)
4676                    .ok_or_else(|| anyhow!("invalid entry"))
4677            })?
4678            .await?;
4679        Ok(proto::ProjectEntryResponse {
4680            entry: Some((&entry).into()),
4681            worktree_scan_id: worktree_scan_id as u64,
4682        })
4683    }
4684
4685    async fn handle_copy_project_entry(
4686        this: ModelHandle<Self>,
4687        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4688        _: Arc<Client>,
4689        mut cx: AsyncAppContext,
4690    ) -> Result<proto::ProjectEntryResponse> {
4691        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4692        let worktree = this.read_with(&cx, |this, cx| {
4693            this.worktree_for_entry(entry_id, cx)
4694                .ok_or_else(|| anyhow!("worktree not found"))
4695        })?;
4696        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4697        let entry = worktree
4698            .update(&mut cx, |worktree, cx| {
4699                let new_path = PathBuf::from(OsString::from_vec(envelope.payload.new_path));
4700                worktree
4701                    .as_local_mut()
4702                    .unwrap()
4703                    .copy_entry(entry_id, new_path, cx)
4704                    .ok_or_else(|| anyhow!("invalid entry"))
4705            })?
4706            .await?;
4707        Ok(proto::ProjectEntryResponse {
4708            entry: Some((&entry).into()),
4709            worktree_scan_id: worktree_scan_id as u64,
4710        })
4711    }
4712
4713    async fn handle_delete_project_entry(
4714        this: ModelHandle<Self>,
4715        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4716        _: Arc<Client>,
4717        mut cx: AsyncAppContext,
4718    ) -> Result<proto::ProjectEntryResponse> {
4719        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4720        let worktree = this.read_with(&cx, |this, cx| {
4721            this.worktree_for_entry(entry_id, cx)
4722                .ok_or_else(|| anyhow!("worktree not found"))
4723        })?;
4724        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4725        worktree
4726            .update(&mut cx, |worktree, cx| {
4727                worktree
4728                    .as_local_mut()
4729                    .unwrap()
4730                    .delete_entry(entry_id, cx)
4731                    .ok_or_else(|| anyhow!("invalid entry"))
4732            })?
4733            .await?;
4734        Ok(proto::ProjectEntryResponse {
4735            entry: None,
4736            worktree_scan_id: worktree_scan_id as u64,
4737        })
4738    }
4739
4740    async fn handle_update_diagnostic_summary(
4741        this: ModelHandle<Self>,
4742        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4743        _: Arc<Client>,
4744        mut cx: AsyncAppContext,
4745    ) -> Result<()> {
4746        this.update(&mut cx, |this, cx| {
4747            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4748            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4749                if let Some(summary) = envelope.payload.summary {
4750                    let project_path = ProjectPath {
4751                        worktree_id,
4752                        path: Path::new(&summary.path).into(),
4753                    };
4754                    worktree.update(cx, |worktree, _| {
4755                        worktree
4756                            .as_remote_mut()
4757                            .unwrap()
4758                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4759                    });
4760                    cx.emit(Event::DiagnosticsUpdated {
4761                        language_server_id: summary.language_server_id as usize,
4762                        path: project_path,
4763                    });
4764                }
4765            }
4766            Ok(())
4767        })
4768    }
4769
4770    async fn handle_start_language_server(
4771        this: ModelHandle<Self>,
4772        envelope: TypedEnvelope<proto::StartLanguageServer>,
4773        _: Arc<Client>,
4774        mut cx: AsyncAppContext,
4775    ) -> Result<()> {
4776        let server = envelope
4777            .payload
4778            .server
4779            .ok_or_else(|| anyhow!("invalid server"))?;
4780        this.update(&mut cx, |this, cx| {
4781            this.language_server_statuses.insert(
4782                server.id as usize,
4783                LanguageServerStatus {
4784                    name: server.name,
4785                    pending_work: Default::default(),
4786                    has_pending_diagnostic_updates: false,
4787                    progress_tokens: Default::default(),
4788                },
4789            );
4790            cx.notify();
4791        });
4792        Ok(())
4793    }
4794
4795    async fn handle_update_language_server(
4796        this: ModelHandle<Self>,
4797        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4798        _: Arc<Client>,
4799        mut cx: AsyncAppContext,
4800    ) -> Result<()> {
4801        let language_server_id = envelope.payload.language_server_id as usize;
4802        match envelope
4803            .payload
4804            .variant
4805            .ok_or_else(|| anyhow!("invalid variant"))?
4806        {
4807            proto::update_language_server::Variant::WorkStart(payload) => {
4808                this.update(&mut cx, |this, cx| {
4809                    this.on_lsp_work_start(
4810                        language_server_id,
4811                        payload.token,
4812                        LanguageServerProgress {
4813                            message: payload.message,
4814                            percentage: payload.percentage.map(|p| p as usize),
4815                            last_update_at: Instant::now(),
4816                        },
4817                        cx,
4818                    );
4819                })
4820            }
4821            proto::update_language_server::Variant::WorkProgress(payload) => {
4822                this.update(&mut cx, |this, cx| {
4823                    this.on_lsp_work_progress(
4824                        language_server_id,
4825                        payload.token,
4826                        LanguageServerProgress {
4827                            message: payload.message,
4828                            percentage: payload.percentage.map(|p| p as usize),
4829                            last_update_at: Instant::now(),
4830                        },
4831                        cx,
4832                    );
4833                })
4834            }
4835            proto::update_language_server::Variant::WorkEnd(payload) => {
4836                this.update(&mut cx, |this, cx| {
4837                    this.on_lsp_work_end(language_server_id, payload.token, cx);
4838                })
4839            }
4840            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4841                this.update(&mut cx, |this, cx| {
4842                    this.disk_based_diagnostics_started(language_server_id, cx);
4843                })
4844            }
4845            proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4846                this.update(&mut cx, |this, cx| {
4847                    this.disk_based_diagnostics_finished(language_server_id, cx)
4848                });
4849            }
4850        }
4851
4852        Ok(())
4853    }
4854
4855    async fn handle_update_buffer(
4856        this: ModelHandle<Self>,
4857        envelope: TypedEnvelope<proto::UpdateBuffer>,
4858        _: Arc<Client>,
4859        mut cx: AsyncAppContext,
4860    ) -> Result<()> {
4861        this.update(&mut cx, |this, cx| {
4862            let payload = envelope.payload.clone();
4863            let buffer_id = payload.buffer_id;
4864            let ops = payload
4865                .operations
4866                .into_iter()
4867                .map(language::proto::deserialize_operation)
4868                .collect::<Result<Vec<_>, _>>()?;
4869            let is_remote = this.is_remote();
4870            match this.opened_buffers.entry(buffer_id) {
4871                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
4872                    OpenBuffer::Strong(buffer) => {
4873                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
4874                    }
4875                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
4876                    OpenBuffer::Weak(_) => {}
4877                },
4878                hash_map::Entry::Vacant(e) => {
4879                    assert!(
4880                        is_remote,
4881                        "received buffer update from {:?}",
4882                        envelope.original_sender_id
4883                    );
4884                    e.insert(OpenBuffer::Operations(ops));
4885                }
4886            }
4887            Ok(())
4888        })
4889    }
4890
4891    async fn handle_create_buffer_for_peer(
4892        this: ModelHandle<Self>,
4893        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4894        _: Arc<Client>,
4895        mut cx: AsyncAppContext,
4896    ) -> Result<()> {
4897        this.update(&mut cx, |this, cx| {
4898            match envelope
4899                .payload
4900                .variant
4901                .ok_or_else(|| anyhow!("missing variant"))?
4902            {
4903                proto::create_buffer_for_peer::Variant::State(mut state) => {
4904                    let mut buffer_file = None;
4905                    if let Some(file) = state.file.take() {
4906                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
4907                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
4908                            anyhow!("no worktree found for id {}", file.worktree_id)
4909                        })?;
4910                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
4911                            as Arc<dyn language::File>);
4912                    }
4913
4914                    let buffer_id = state.id;
4915                    let buffer = cx.add_model(|_| {
4916                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
4917                    });
4918                    this.incomplete_buffers.insert(buffer_id, buffer);
4919                }
4920                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
4921                    let buffer = this
4922                        .incomplete_buffers
4923                        .get(&chunk.buffer_id)
4924                        .ok_or_else(|| {
4925                            anyhow!(
4926                                "received chunk for buffer {} without initial state",
4927                                chunk.buffer_id
4928                            )
4929                        })?
4930                        .clone();
4931                    let operations = chunk
4932                        .operations
4933                        .into_iter()
4934                        .map(language::proto::deserialize_operation)
4935                        .collect::<Result<Vec<_>>>()?;
4936                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
4937
4938                    if chunk.is_last {
4939                        this.incomplete_buffers.remove(&chunk.buffer_id);
4940                        this.register_buffer(&buffer, cx)?;
4941                    }
4942                }
4943            }
4944
4945            Ok(())
4946        })
4947    }
4948
4949    async fn handle_update_diff_base(
4950        this: ModelHandle<Self>,
4951        envelope: TypedEnvelope<proto::UpdateDiffBase>,
4952        _: Arc<Client>,
4953        mut cx: AsyncAppContext,
4954    ) -> Result<()> {
4955        this.update(&mut cx, |this, cx| {
4956            let buffer_id = envelope.payload.buffer_id;
4957            let diff_base = envelope.payload.diff_base;
4958            let buffer = this
4959                .opened_buffers
4960                .get_mut(&buffer_id)
4961                .and_then(|b| b.upgrade(cx))
4962                .ok_or_else(|| anyhow!("No such buffer {}", buffer_id))?;
4963
4964            buffer.update(cx, |buffer, cx| buffer.update_diff_base(diff_base, cx));
4965
4966            Ok(())
4967        })
4968    }
4969
4970    async fn handle_update_buffer_file(
4971        this: ModelHandle<Self>,
4972        envelope: TypedEnvelope<proto::UpdateBufferFile>,
4973        _: Arc<Client>,
4974        mut cx: AsyncAppContext,
4975    ) -> Result<()> {
4976        this.update(&mut cx, |this, cx| {
4977            let payload = envelope.payload.clone();
4978            let buffer_id = payload.buffer_id;
4979            let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
4980            let worktree = this
4981                .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
4982                .ok_or_else(|| anyhow!("no such worktree"))?;
4983            let file = File::from_proto(file, worktree, cx)?;
4984            let buffer = this
4985                .opened_buffers
4986                .get_mut(&buffer_id)
4987                .and_then(|b| b.upgrade(cx))
4988                .ok_or_else(|| anyhow!("no such buffer"))?;
4989            buffer.update(cx, |buffer, cx| {
4990                buffer.file_updated(Arc::new(file), cx).detach();
4991            });
4992            Ok(())
4993        })
4994    }
4995
4996    async fn handle_save_buffer(
4997        this: ModelHandle<Self>,
4998        envelope: TypedEnvelope<proto::SaveBuffer>,
4999        _: Arc<Client>,
5000        mut cx: AsyncAppContext,
5001    ) -> Result<proto::BufferSaved> {
5002        let buffer_id = envelope.payload.buffer_id;
5003        let requested_version = deserialize_version(envelope.payload.version);
5004
5005        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5006            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5007            let buffer = this
5008                .opened_buffers
5009                .get(&buffer_id)
5010                .and_then(|buffer| buffer.upgrade(cx))
5011                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5012            Ok::<_, anyhow::Error>((project_id, buffer))
5013        })?;
5014        buffer
5015            .update(&mut cx, |buffer, _| {
5016                buffer.wait_for_version(requested_version)
5017            })
5018            .await;
5019
5020        let (saved_version, fingerprint, mtime) =
5021            buffer.update(&mut cx, |buffer, cx| buffer.save(cx)).await?;
5022        Ok(proto::BufferSaved {
5023            project_id,
5024            buffer_id,
5025            version: serialize_version(&saved_version),
5026            mtime: Some(mtime.into()),
5027            fingerprint,
5028        })
5029    }
5030
5031    async fn handle_reload_buffers(
5032        this: ModelHandle<Self>,
5033        envelope: TypedEnvelope<proto::ReloadBuffers>,
5034        _: Arc<Client>,
5035        mut cx: AsyncAppContext,
5036    ) -> Result<proto::ReloadBuffersResponse> {
5037        let sender_id = envelope.original_sender_id()?;
5038        let reload = this.update(&mut cx, |this, cx| {
5039            let mut buffers = HashSet::default();
5040            for buffer_id in &envelope.payload.buffer_ids {
5041                buffers.insert(
5042                    this.opened_buffers
5043                        .get(buffer_id)
5044                        .and_then(|buffer| buffer.upgrade(cx))
5045                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5046                );
5047            }
5048            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5049        })?;
5050
5051        let project_transaction = reload.await?;
5052        let project_transaction = this.update(&mut cx, |this, cx| {
5053            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5054        });
5055        Ok(proto::ReloadBuffersResponse {
5056            transaction: Some(project_transaction),
5057        })
5058    }
5059
5060    async fn handle_format_buffers(
5061        this: ModelHandle<Self>,
5062        envelope: TypedEnvelope<proto::FormatBuffers>,
5063        _: Arc<Client>,
5064        mut cx: AsyncAppContext,
5065    ) -> Result<proto::FormatBuffersResponse> {
5066        let sender_id = envelope.original_sender_id()?;
5067        let format = this.update(&mut cx, |this, cx| {
5068            let mut buffers = HashSet::default();
5069            for buffer_id in &envelope.payload.buffer_ids {
5070                buffers.insert(
5071                    this.opened_buffers
5072                        .get(buffer_id)
5073                        .and_then(|buffer| buffer.upgrade(cx))
5074                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5075                );
5076            }
5077            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5078            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5079        })?;
5080
5081        let project_transaction = format.await?;
5082        let project_transaction = this.update(&mut cx, |this, cx| {
5083            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5084        });
5085        Ok(proto::FormatBuffersResponse {
5086            transaction: Some(project_transaction),
5087        })
5088    }
5089
5090    async fn handle_get_completions(
5091        this: ModelHandle<Self>,
5092        envelope: TypedEnvelope<proto::GetCompletions>,
5093        _: Arc<Client>,
5094        mut cx: AsyncAppContext,
5095    ) -> Result<proto::GetCompletionsResponse> {
5096        let position = envelope
5097            .payload
5098            .position
5099            .and_then(language::proto::deserialize_anchor)
5100            .ok_or_else(|| anyhow!("invalid position"))?;
5101        let version = deserialize_version(envelope.payload.version);
5102        let buffer = this.read_with(&cx, |this, cx| {
5103            this.opened_buffers
5104                .get(&envelope.payload.buffer_id)
5105                .and_then(|buffer| buffer.upgrade(cx))
5106                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5107        })?;
5108        buffer
5109            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5110            .await;
5111        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5112        let completions = this
5113            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5114            .await?;
5115
5116        Ok(proto::GetCompletionsResponse {
5117            completions: completions
5118                .iter()
5119                .map(language::proto::serialize_completion)
5120                .collect(),
5121            version: serialize_version(&version),
5122        })
5123    }
5124
5125    async fn handle_apply_additional_edits_for_completion(
5126        this: ModelHandle<Self>,
5127        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5128        _: Arc<Client>,
5129        mut cx: AsyncAppContext,
5130    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5131        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5132            let buffer = this
5133                .opened_buffers
5134                .get(&envelope.payload.buffer_id)
5135                .and_then(|buffer| buffer.upgrade(cx))
5136                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5137            let language = buffer.read(cx).language();
5138            let completion = language::proto::deserialize_completion(
5139                envelope
5140                    .payload
5141                    .completion
5142                    .ok_or_else(|| anyhow!("invalid completion"))?,
5143                language.cloned(),
5144            );
5145            Ok::<_, anyhow::Error>((buffer, completion))
5146        })?;
5147
5148        let completion = completion.await?;
5149
5150        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5151            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5152        });
5153
5154        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5155            transaction: apply_additional_edits
5156                .await?
5157                .as_ref()
5158                .map(language::proto::serialize_transaction),
5159        })
5160    }
5161
5162    async fn handle_get_code_actions(
5163        this: ModelHandle<Self>,
5164        envelope: TypedEnvelope<proto::GetCodeActions>,
5165        _: Arc<Client>,
5166        mut cx: AsyncAppContext,
5167    ) -> Result<proto::GetCodeActionsResponse> {
5168        let start = envelope
5169            .payload
5170            .start
5171            .and_then(language::proto::deserialize_anchor)
5172            .ok_or_else(|| anyhow!("invalid start"))?;
5173        let end = envelope
5174            .payload
5175            .end
5176            .and_then(language::proto::deserialize_anchor)
5177            .ok_or_else(|| anyhow!("invalid end"))?;
5178        let buffer = this.update(&mut cx, |this, cx| {
5179            this.opened_buffers
5180                .get(&envelope.payload.buffer_id)
5181                .and_then(|buffer| buffer.upgrade(cx))
5182                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5183        })?;
5184        buffer
5185            .update(&mut cx, |buffer, _| {
5186                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5187            })
5188            .await;
5189
5190        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5191        let code_actions = this.update(&mut cx, |this, cx| {
5192            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5193        })?;
5194
5195        Ok(proto::GetCodeActionsResponse {
5196            actions: code_actions
5197                .await?
5198                .iter()
5199                .map(language::proto::serialize_code_action)
5200                .collect(),
5201            version: serialize_version(&version),
5202        })
5203    }
5204
5205    async fn handle_apply_code_action(
5206        this: ModelHandle<Self>,
5207        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5208        _: Arc<Client>,
5209        mut cx: AsyncAppContext,
5210    ) -> Result<proto::ApplyCodeActionResponse> {
5211        let sender_id = envelope.original_sender_id()?;
5212        let action = language::proto::deserialize_code_action(
5213            envelope
5214                .payload
5215                .action
5216                .ok_or_else(|| anyhow!("invalid action"))?,
5217        )?;
5218        let apply_code_action = this.update(&mut cx, |this, cx| {
5219            let buffer = this
5220                .opened_buffers
5221                .get(&envelope.payload.buffer_id)
5222                .and_then(|buffer| buffer.upgrade(cx))
5223                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5224            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5225        })?;
5226
5227        let project_transaction = apply_code_action.await?;
5228        let project_transaction = this.update(&mut cx, |this, cx| {
5229            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5230        });
5231        Ok(proto::ApplyCodeActionResponse {
5232            transaction: Some(project_transaction),
5233        })
5234    }
5235
5236    async fn handle_lsp_command<T: LspCommand>(
5237        this: ModelHandle<Self>,
5238        envelope: TypedEnvelope<T::ProtoRequest>,
5239        _: Arc<Client>,
5240        mut cx: AsyncAppContext,
5241    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5242    where
5243        <T::LspRequest as lsp::request::Request>::Result: Send,
5244    {
5245        let sender_id = envelope.original_sender_id()?;
5246        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5247        let buffer_handle = this.read_with(&cx, |this, _| {
5248            this.opened_buffers
5249                .get(&buffer_id)
5250                .and_then(|buffer| buffer.upgrade(&cx))
5251                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5252        })?;
5253        let request = T::from_proto(
5254            envelope.payload,
5255            this.clone(),
5256            buffer_handle.clone(),
5257            cx.clone(),
5258        )
5259        .await?;
5260        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5261        let response = this
5262            .update(&mut cx, |this, cx| {
5263                this.request_lsp(buffer_handle, request, cx)
5264            })
5265            .await?;
5266        this.update(&mut cx, |this, cx| {
5267            Ok(T::response_to_proto(
5268                response,
5269                this,
5270                sender_id,
5271                &buffer_version,
5272                cx,
5273            ))
5274        })
5275    }
5276
5277    async fn handle_get_project_symbols(
5278        this: ModelHandle<Self>,
5279        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5280        _: Arc<Client>,
5281        mut cx: AsyncAppContext,
5282    ) -> Result<proto::GetProjectSymbolsResponse> {
5283        let symbols = this
5284            .update(&mut cx, |this, cx| {
5285                this.symbols(&envelope.payload.query, cx)
5286            })
5287            .await?;
5288
5289        Ok(proto::GetProjectSymbolsResponse {
5290            symbols: symbols.iter().map(serialize_symbol).collect(),
5291        })
5292    }
5293
5294    async fn handle_search_project(
5295        this: ModelHandle<Self>,
5296        envelope: TypedEnvelope<proto::SearchProject>,
5297        _: Arc<Client>,
5298        mut cx: AsyncAppContext,
5299    ) -> Result<proto::SearchProjectResponse> {
5300        let peer_id = envelope.original_sender_id()?;
5301        let query = SearchQuery::from_proto(envelope.payload)?;
5302        let result = this
5303            .update(&mut cx, |this, cx| this.search(query, cx))
5304            .await?;
5305
5306        this.update(&mut cx, |this, cx| {
5307            let mut locations = Vec::new();
5308            for (buffer, ranges) in result {
5309                for range in ranges {
5310                    let start = serialize_anchor(&range.start);
5311                    let end = serialize_anchor(&range.end);
5312                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5313                    locations.push(proto::Location {
5314                        buffer_id,
5315                        start: Some(start),
5316                        end: Some(end),
5317                    });
5318                }
5319            }
5320            Ok(proto::SearchProjectResponse { locations })
5321        })
5322    }
5323
5324    async fn handle_open_buffer_for_symbol(
5325        this: ModelHandle<Self>,
5326        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5327        _: Arc<Client>,
5328        mut cx: AsyncAppContext,
5329    ) -> Result<proto::OpenBufferForSymbolResponse> {
5330        let peer_id = envelope.original_sender_id()?;
5331        let symbol = envelope
5332            .payload
5333            .symbol
5334            .ok_or_else(|| anyhow!("invalid symbol"))?;
5335        let symbol = this
5336            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5337            .await?;
5338        let symbol = this.read_with(&cx, |this, _| {
5339            let signature = this.symbol_signature(&symbol.path);
5340            if signature == symbol.signature {
5341                Ok(symbol)
5342            } else {
5343                Err(anyhow!("invalid symbol signature"))
5344            }
5345        })?;
5346        let buffer = this
5347            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5348            .await?;
5349
5350        Ok(proto::OpenBufferForSymbolResponse {
5351            buffer_id: this.update(&mut cx, |this, cx| {
5352                this.create_buffer_for_peer(&buffer, peer_id, cx)
5353            }),
5354        })
5355    }
5356
5357    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5358        let mut hasher = Sha256::new();
5359        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5360        hasher.update(project_path.path.to_string_lossy().as_bytes());
5361        hasher.update(self.nonce.to_be_bytes());
5362        hasher.finalize().as_slice().try_into().unwrap()
5363    }
5364
5365    async fn handle_open_buffer_by_id(
5366        this: ModelHandle<Self>,
5367        envelope: TypedEnvelope<proto::OpenBufferById>,
5368        _: Arc<Client>,
5369        mut cx: AsyncAppContext,
5370    ) -> Result<proto::OpenBufferResponse> {
5371        let peer_id = envelope.original_sender_id()?;
5372        let buffer = this
5373            .update(&mut cx, |this, cx| {
5374                this.open_buffer_by_id(envelope.payload.id, cx)
5375            })
5376            .await?;
5377        this.update(&mut cx, |this, cx| {
5378            Ok(proto::OpenBufferResponse {
5379                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5380            })
5381        })
5382    }
5383
5384    async fn handle_open_buffer_by_path(
5385        this: ModelHandle<Self>,
5386        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5387        _: Arc<Client>,
5388        mut cx: AsyncAppContext,
5389    ) -> Result<proto::OpenBufferResponse> {
5390        let peer_id = envelope.original_sender_id()?;
5391        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5392        let open_buffer = this.update(&mut cx, |this, cx| {
5393            this.open_buffer(
5394                ProjectPath {
5395                    worktree_id,
5396                    path: PathBuf::from(envelope.payload.path).into(),
5397                },
5398                cx,
5399            )
5400        });
5401
5402        let buffer = open_buffer.await?;
5403        this.update(&mut cx, |this, cx| {
5404            Ok(proto::OpenBufferResponse {
5405                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5406            })
5407        })
5408    }
5409
5410    fn serialize_project_transaction_for_peer(
5411        &mut self,
5412        project_transaction: ProjectTransaction,
5413        peer_id: PeerId,
5414        cx: &AppContext,
5415    ) -> proto::ProjectTransaction {
5416        let mut serialized_transaction = proto::ProjectTransaction {
5417            buffer_ids: Default::default(),
5418            transactions: Default::default(),
5419        };
5420        for (buffer, transaction) in project_transaction.0 {
5421            serialized_transaction
5422                .buffer_ids
5423                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5424            serialized_transaction
5425                .transactions
5426                .push(language::proto::serialize_transaction(&transaction));
5427        }
5428        serialized_transaction
5429    }
5430
5431    fn deserialize_project_transaction(
5432        &mut self,
5433        message: proto::ProjectTransaction,
5434        push_to_history: bool,
5435        cx: &mut ModelContext<Self>,
5436    ) -> Task<Result<ProjectTransaction>> {
5437        cx.spawn(|this, mut cx| async move {
5438            let mut project_transaction = ProjectTransaction::default();
5439            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5440            {
5441                let buffer = this
5442                    .update(&mut cx, |this, cx| this.wait_for_buffer(buffer_id, cx))
5443                    .await?;
5444                let transaction = language::proto::deserialize_transaction(transaction)?;
5445                project_transaction.0.insert(buffer, transaction);
5446            }
5447
5448            for (buffer, transaction) in &project_transaction.0 {
5449                buffer
5450                    .update(&mut cx, |buffer, _| {
5451                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5452                    })
5453                    .await;
5454
5455                if push_to_history {
5456                    buffer.update(&mut cx, |buffer, _| {
5457                        buffer.push_transaction(transaction.clone(), Instant::now());
5458                    });
5459                }
5460            }
5461
5462            Ok(project_transaction)
5463        })
5464    }
5465
5466    fn create_buffer_for_peer(
5467        &mut self,
5468        buffer: &ModelHandle<Buffer>,
5469        peer_id: PeerId,
5470        cx: &AppContext,
5471    ) -> u64 {
5472        let buffer_id = buffer.read(cx).remote_id();
5473        if let Some(project_id) = self.remote_id() {
5474            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5475            if shared_buffers.insert(buffer_id) {
5476                let buffer = buffer.read(cx);
5477                let state = buffer.to_proto();
5478                let operations = buffer.serialize_ops(cx);
5479                let client = self.client.clone();
5480                cx.background()
5481                    .spawn(
5482                        async move {
5483                            let mut operations = operations.await;
5484
5485                            client.send(proto::CreateBufferForPeer {
5486                                project_id,
5487                                peer_id: peer_id.0,
5488                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5489                            })?;
5490
5491                            loop {
5492                                #[cfg(any(test, feature = "test-support"))]
5493                                const CHUNK_SIZE: usize = 5;
5494
5495                                #[cfg(not(any(test, feature = "test-support")))]
5496                                const CHUNK_SIZE: usize = 100;
5497
5498                                let chunk = operations
5499                                    .drain(..cmp::min(CHUNK_SIZE, operations.len()))
5500                                    .collect();
5501                                let is_last = operations.is_empty();
5502                                client.send(proto::CreateBufferForPeer {
5503                                    project_id,
5504                                    peer_id: peer_id.0,
5505                                    variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5506                                        proto::BufferChunk {
5507                                            buffer_id,
5508                                            operations: chunk,
5509                                            is_last,
5510                                        },
5511                                    )),
5512                                })?;
5513
5514                                if is_last {
5515                                    break;
5516                                }
5517                            }
5518
5519                            Ok(())
5520                        }
5521                        .log_err(),
5522                    )
5523                    .detach();
5524            }
5525        }
5526
5527        buffer_id
5528    }
5529
5530    fn wait_for_buffer(
5531        &self,
5532        id: u64,
5533        cx: &mut ModelContext<Self>,
5534    ) -> Task<Result<ModelHandle<Buffer>>> {
5535        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5536        cx.spawn(|this, mut cx| async move {
5537            let buffer = loop {
5538                let buffer = this.read_with(&cx, |this, cx| {
5539                    this.opened_buffers
5540                        .get(&id)
5541                        .and_then(|buffer| buffer.upgrade(cx))
5542                });
5543                if let Some(buffer) = buffer {
5544                    break buffer;
5545                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5546                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5547                }
5548
5549                opened_buffer_rx
5550                    .next()
5551                    .await
5552                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5553            };
5554            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5555            Ok(buffer)
5556        })
5557    }
5558
5559    fn deserialize_symbol(
5560        &self,
5561        serialized_symbol: proto::Symbol,
5562    ) -> impl Future<Output = Result<Symbol>> {
5563        let languages = self.languages.clone();
5564        async move {
5565            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5566            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
5567            let start = serialized_symbol
5568                .start
5569                .ok_or_else(|| anyhow!("invalid start"))?;
5570            let end = serialized_symbol
5571                .end
5572                .ok_or_else(|| anyhow!("invalid end"))?;
5573            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
5574            let path = ProjectPath {
5575                worktree_id,
5576                path: PathBuf::from(serialized_symbol.path).into(),
5577            };
5578            let language = languages.select_language(&path.path);
5579            Ok(Symbol {
5580                language_server_name: LanguageServerName(
5581                    serialized_symbol.language_server_name.into(),
5582                ),
5583                source_worktree_id,
5584                path,
5585                label: {
5586                    match language {
5587                        Some(language) => {
5588                            language
5589                                .label_for_symbol(&serialized_symbol.name, kind)
5590                                .await
5591                        }
5592                        None => None,
5593                    }
5594                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
5595                },
5596
5597                name: serialized_symbol.name,
5598                range: PointUtf16::new(start.row, start.column)
5599                    ..PointUtf16::new(end.row, end.column),
5600                kind,
5601                signature: serialized_symbol
5602                    .signature
5603                    .try_into()
5604                    .map_err(|_| anyhow!("invalid signature"))?,
5605            })
5606        }
5607    }
5608
5609    async fn handle_buffer_saved(
5610        this: ModelHandle<Self>,
5611        envelope: TypedEnvelope<proto::BufferSaved>,
5612        _: Arc<Client>,
5613        mut cx: AsyncAppContext,
5614    ) -> Result<()> {
5615        let version = deserialize_version(envelope.payload.version);
5616        let mtime = envelope
5617            .payload
5618            .mtime
5619            .ok_or_else(|| anyhow!("missing mtime"))?
5620            .into();
5621
5622        this.update(&mut cx, |this, cx| {
5623            let buffer = this
5624                .opened_buffers
5625                .get(&envelope.payload.buffer_id)
5626                .and_then(|buffer| buffer.upgrade(cx));
5627            if let Some(buffer) = buffer {
5628                buffer.update(cx, |buffer, cx| {
5629                    buffer.did_save(version, envelope.payload.fingerprint, mtime, None, cx);
5630                });
5631            }
5632            Ok(())
5633        })
5634    }
5635
5636    async fn handle_buffer_reloaded(
5637        this: ModelHandle<Self>,
5638        envelope: TypedEnvelope<proto::BufferReloaded>,
5639        _: Arc<Client>,
5640        mut cx: AsyncAppContext,
5641    ) -> Result<()> {
5642        let payload = envelope.payload;
5643        let version = deserialize_version(payload.version);
5644        let line_ending = deserialize_line_ending(
5645            proto::LineEnding::from_i32(payload.line_ending)
5646                .ok_or_else(|| anyhow!("missing line ending"))?,
5647        );
5648        let mtime = payload
5649            .mtime
5650            .ok_or_else(|| anyhow!("missing mtime"))?
5651            .into();
5652        this.update(&mut cx, |this, cx| {
5653            let buffer = this
5654                .opened_buffers
5655                .get(&payload.buffer_id)
5656                .and_then(|buffer| buffer.upgrade(cx));
5657            if let Some(buffer) = buffer {
5658                buffer.update(cx, |buffer, cx| {
5659                    buffer.did_reload(version, payload.fingerprint, line_ending, mtime, cx);
5660                });
5661            }
5662            Ok(())
5663        })
5664    }
5665
5666    #[allow(clippy::type_complexity)]
5667    fn edits_from_lsp(
5668        &mut self,
5669        buffer: &ModelHandle<Buffer>,
5670        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
5671        version: Option<i32>,
5672        cx: &mut ModelContext<Self>,
5673    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
5674        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
5675        cx.background().spawn(async move {
5676            let snapshot = snapshot?;
5677            let mut lsp_edits = lsp_edits
5678                .into_iter()
5679                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
5680                .collect::<Vec<_>>();
5681            lsp_edits.sort_by_key(|(range, _)| range.start);
5682
5683            let mut lsp_edits = lsp_edits.into_iter().peekable();
5684            let mut edits = Vec::new();
5685            while let Some((mut range, mut new_text)) = lsp_edits.next() {
5686                // Clip invalid ranges provided by the language server.
5687                range.start = snapshot.clip_point_utf16(range.start, Bias::Left);
5688                range.end = snapshot.clip_point_utf16(range.end, Bias::Left);
5689
5690                // Combine any LSP edits that are adjacent.
5691                //
5692                // Also, combine LSP edits that are separated from each other by only
5693                // a newline. This is important because for some code actions,
5694                // Rust-analyzer rewrites the entire buffer via a series of edits that
5695                // are separated by unchanged newline characters.
5696                //
5697                // In order for the diffing logic below to work properly, any edits that
5698                // cancel each other out must be combined into one.
5699                while let Some((next_range, next_text)) = lsp_edits.peek() {
5700                    if next_range.start > range.end {
5701                        if next_range.start.row > range.end.row + 1
5702                            || next_range.start.column > 0
5703                            || snapshot.clip_point_utf16(
5704                                PointUtf16::new(range.end.row, u32::MAX),
5705                                Bias::Left,
5706                            ) > range.end
5707                        {
5708                            break;
5709                        }
5710                        new_text.push('\n');
5711                    }
5712                    range.end = next_range.end;
5713                    new_text.push_str(next_text);
5714                    lsp_edits.next();
5715                }
5716
5717                // For multiline edits, perform a diff of the old and new text so that
5718                // we can identify the changes more precisely, preserving the locations
5719                // of any anchors positioned in the unchanged regions.
5720                if range.end.row > range.start.row {
5721                    let mut offset = range.start.to_offset(&snapshot);
5722                    let old_text = snapshot.text_for_range(range).collect::<String>();
5723
5724                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
5725                    let mut moved_since_edit = true;
5726                    for change in diff.iter_all_changes() {
5727                        let tag = change.tag();
5728                        let value = change.value();
5729                        match tag {
5730                            ChangeTag::Equal => {
5731                                offset += value.len();
5732                                moved_since_edit = true;
5733                            }
5734                            ChangeTag::Delete => {
5735                                let start = snapshot.anchor_after(offset);
5736                                let end = snapshot.anchor_before(offset + value.len());
5737                                if moved_since_edit {
5738                                    edits.push((start..end, String::new()));
5739                                } else {
5740                                    edits.last_mut().unwrap().0.end = end;
5741                                }
5742                                offset += value.len();
5743                                moved_since_edit = false;
5744                            }
5745                            ChangeTag::Insert => {
5746                                if moved_since_edit {
5747                                    let anchor = snapshot.anchor_after(offset);
5748                                    edits.push((anchor..anchor, value.to_string()));
5749                                } else {
5750                                    edits.last_mut().unwrap().1.push_str(value);
5751                                }
5752                                moved_since_edit = false;
5753                            }
5754                        }
5755                    }
5756                } else if range.end == range.start {
5757                    let anchor = snapshot.anchor_after(range.start);
5758                    edits.push((anchor..anchor, new_text));
5759                } else {
5760                    let edit_start = snapshot.anchor_after(range.start);
5761                    let edit_end = snapshot.anchor_before(range.end);
5762                    edits.push((edit_start..edit_end, new_text));
5763                }
5764            }
5765
5766            Ok(edits)
5767        })
5768    }
5769
5770    fn buffer_snapshot_for_lsp_version(
5771        &mut self,
5772        buffer: &ModelHandle<Buffer>,
5773        version: Option<i32>,
5774        cx: &AppContext,
5775    ) -> Result<TextBufferSnapshot> {
5776        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
5777
5778        if let Some(version) = version {
5779            let buffer_id = buffer.read(cx).remote_id();
5780            let snapshots = self
5781                .buffer_snapshots
5782                .get_mut(&buffer_id)
5783                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
5784            let mut found_snapshot = None;
5785            snapshots.retain(|(snapshot_version, snapshot)| {
5786                if snapshot_version + OLD_VERSIONS_TO_RETAIN < version {
5787                    false
5788                } else {
5789                    if *snapshot_version == version {
5790                        found_snapshot = Some(snapshot.clone());
5791                    }
5792                    true
5793                }
5794            });
5795
5796            found_snapshot.ok_or_else(|| {
5797                anyhow!(
5798                    "snapshot not found for buffer {} at version {}",
5799                    buffer_id,
5800                    version
5801                )
5802            })
5803        } else {
5804            Ok((buffer.read(cx)).text_snapshot())
5805        }
5806    }
5807
5808    fn language_server_for_buffer(
5809        &self,
5810        buffer: &Buffer,
5811        cx: &AppContext,
5812    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
5813        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
5814            let name = language.lsp_adapter()?.name.clone();
5815            let worktree_id = file.worktree_id(cx);
5816            let key = (worktree_id, name);
5817
5818            if let Some(server_id) = self.language_server_ids.get(&key) {
5819                if let Some(LanguageServerState::Running {
5820                    adapter, server, ..
5821                }) = self.language_servers.get(server_id)
5822                {
5823                    return Some((adapter, server));
5824                }
5825            }
5826        }
5827
5828        None
5829    }
5830}
5831
5832impl ProjectStore {
5833    pub fn new() -> Self {
5834        Self {
5835            projects: Default::default(),
5836        }
5837    }
5838
5839    pub fn projects<'a>(
5840        &'a self,
5841        cx: &'a AppContext,
5842    ) -> impl 'a + Iterator<Item = ModelHandle<Project>> {
5843        self.projects
5844            .iter()
5845            .filter_map(|project| project.upgrade(cx))
5846    }
5847
5848    fn add_project(&mut self, project: WeakModelHandle<Project>, cx: &mut ModelContext<Self>) {
5849        if let Err(ix) = self
5850            .projects
5851            .binary_search_by_key(&project.id(), WeakModelHandle::id)
5852        {
5853            self.projects.insert(ix, project);
5854        }
5855        cx.notify();
5856    }
5857
5858    fn prune_projects(&mut self, cx: &mut ModelContext<Self>) {
5859        let mut did_change = false;
5860        self.projects.retain(|project| {
5861            if project.is_upgradable(cx) {
5862                true
5863            } else {
5864                did_change = true;
5865                false
5866            }
5867        });
5868        if did_change {
5869            cx.notify();
5870        }
5871    }
5872}
5873
5874impl WorktreeHandle {
5875    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
5876        match self {
5877            WorktreeHandle::Strong(handle) => Some(handle.clone()),
5878            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
5879        }
5880    }
5881}
5882
5883impl OpenBuffer {
5884    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
5885        match self {
5886            OpenBuffer::Strong(handle) => Some(handle.clone()),
5887            OpenBuffer::Weak(handle) => handle.upgrade(cx),
5888            OpenBuffer::Operations(_) => None,
5889        }
5890    }
5891}
5892
5893pub struct PathMatchCandidateSet {
5894    pub snapshot: Snapshot,
5895    pub include_ignored: bool,
5896    pub include_root_name: bool,
5897}
5898
5899impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5900    type Candidates = PathMatchCandidateSetIter<'a>;
5901
5902    fn id(&self) -> usize {
5903        self.snapshot.id().to_usize()
5904    }
5905
5906    fn len(&self) -> usize {
5907        if self.include_ignored {
5908            self.snapshot.file_count()
5909        } else {
5910            self.snapshot.visible_file_count()
5911        }
5912    }
5913
5914    fn prefix(&self) -> Arc<str> {
5915        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5916            self.snapshot.root_name().into()
5917        } else if self.include_root_name {
5918            format!("{}/", self.snapshot.root_name()).into()
5919        } else {
5920            "".into()
5921        }
5922    }
5923
5924    fn candidates(&'a self, start: usize) -> Self::Candidates {
5925        PathMatchCandidateSetIter {
5926            traversal: self.snapshot.files(self.include_ignored, start),
5927        }
5928    }
5929}
5930
5931pub struct PathMatchCandidateSetIter<'a> {
5932    traversal: Traversal<'a>,
5933}
5934
5935impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5936    type Item = fuzzy::PathMatchCandidate<'a>;
5937
5938    fn next(&mut self) -> Option<Self::Item> {
5939        self.traversal.next().map(|entry| {
5940            if let EntryKind::File(char_bag) = entry.kind {
5941                fuzzy::PathMatchCandidate {
5942                    path: &entry.path,
5943                    char_bag,
5944                }
5945            } else {
5946                unreachable!()
5947            }
5948        })
5949    }
5950}
5951
5952impl Entity for ProjectStore {
5953    type Event = ();
5954}
5955
5956impl Entity for Project {
5957    type Event = Event;
5958
5959    fn release(&mut self, cx: &mut gpui::MutableAppContext) {
5960        self.project_store.update(cx, ProjectStore::prune_projects);
5961
5962        match &self.client_state {
5963            Some(ProjectClientState::Local { remote_id, .. }) => {
5964                self.client
5965                    .send(proto::UnshareProject {
5966                        project_id: *remote_id,
5967                    })
5968                    .log_err();
5969            }
5970            Some(ProjectClientState::Remote { remote_id, .. }) => {
5971                self.client
5972                    .send(proto::LeaveProject {
5973                        project_id: *remote_id,
5974                    })
5975                    .log_err();
5976            }
5977            _ => {}
5978        }
5979    }
5980
5981    fn app_will_quit(
5982        &mut self,
5983        _: &mut MutableAppContext,
5984    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
5985        let shutdown_futures = self
5986            .language_servers
5987            .drain()
5988            .map(|(_, server_state)| async {
5989                match server_state {
5990                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
5991                    LanguageServerState::Starting(starting_server) => {
5992                        starting_server.await?.shutdown()?.await
5993                    }
5994                }
5995            })
5996            .collect::<Vec<_>>();
5997
5998        Some(
5999            async move {
6000                futures::future::join_all(shutdown_futures).await;
6001            }
6002            .boxed(),
6003        )
6004    }
6005}
6006
6007impl Collaborator {
6008    fn from_proto(message: proto::Collaborator) -> Self {
6009        Self {
6010            peer_id: PeerId(message.peer_id),
6011            replica_id: message.replica_id as ReplicaId,
6012        }
6013    }
6014}
6015
6016impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6017    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6018        Self {
6019            worktree_id,
6020            path: path.as_ref().into(),
6021        }
6022    }
6023}
6024
6025fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6026    proto::Symbol {
6027        language_server_name: symbol.language_server_name.0.to_string(),
6028        source_worktree_id: symbol.source_worktree_id.to_proto(),
6029        worktree_id: symbol.path.worktree_id.to_proto(),
6030        path: symbol.path.path.to_string_lossy().to_string(),
6031        name: symbol.name.clone(),
6032        kind: unsafe { mem::transmute(symbol.kind) },
6033        start: Some(proto::Point {
6034            row: symbol.range.start.row,
6035            column: symbol.range.start.column,
6036        }),
6037        end: Some(proto::Point {
6038            row: symbol.range.end.row,
6039            column: symbol.range.end.column,
6040        }),
6041        signature: symbol.signature.to_vec(),
6042    }
6043}
6044
6045fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6046    let mut path_components = path.components();
6047    let mut base_components = base.components();
6048    let mut components: Vec<Component> = Vec::new();
6049    loop {
6050        match (path_components.next(), base_components.next()) {
6051            (None, None) => break,
6052            (Some(a), None) => {
6053                components.push(a);
6054                components.extend(path_components.by_ref());
6055                break;
6056            }
6057            (None, _) => components.push(Component::ParentDir),
6058            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6059            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6060            (Some(a), Some(_)) => {
6061                components.push(Component::ParentDir);
6062                for _ in base_components {
6063                    components.push(Component::ParentDir);
6064                }
6065                components.push(a);
6066                components.extend(path_components.by_ref());
6067                break;
6068            }
6069        }
6070    }
6071    components.iter().map(|c| c.as_os_str()).collect()
6072}
6073
6074impl Item for Buffer {
6075    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6076        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6077    }
6078}