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