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