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