project.rs

   1mod ignore;
   2pub mod lsp_command;
   3pub mod lsp_ext_command;
   4mod prettier_support;
   5pub mod project_settings;
   6pub mod search;
   7pub mod terminals;
   8pub mod worktree;
   9
  10#[cfg(test)]
  11mod project_tests;
  12#[cfg(test)]
  13mod worktree_tests;
  14
  15use anyhow::{anyhow, Context as _, Result};
  16use client::{proto, Client, Collaborator, TypedEnvelope, UserStore};
  17use clock::ReplicaId;
  18use collections::{hash_map, BTreeMap, HashMap, HashSet, VecDeque};
  19use copilot::Copilot;
  20use futures::{
  21    channel::{
  22        mpsc::{self, UnboundedReceiver},
  23        oneshot,
  24    },
  25    future::{try_join_all, Shared},
  26    stream::FuturesUnordered,
  27    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
  28};
  29use globset::{Glob, GlobSet, GlobSetBuilder};
  30use gpui::{
  31    AnyModel, AppContext, AsyncAppContext, BackgroundExecutor, Context, Entity, EventEmitter,
  32    Model, ModelContext, Task, WeakModel,
  33};
  34use itertools::Itertools;
  35use language::{
  36    language_settings::{language_settings, FormatOnSave, Formatter, InlayHintKind},
  37    point_to_lsp,
  38    proto::{
  39        deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
  40        serialize_anchor, serialize_version, split_operations,
  41    },
  42    range_from_lsp, range_to_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, Capability,
  43    CodeAction, CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff,
  44    Event as BufferEvent, File as _, Language, LanguageRegistry, LanguageServerName, LocalFile,
  45    LspAdapterDelegate, OffsetRangeExt, Operation, Patch, PendingLanguageServer, PointUtf16,
  46    TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction, Unclipped,
  47};
  48use log::error;
  49use lsp::{
  50    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
  51    DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId, OneOf,
  52};
  53use lsp_command::*;
  54use node_runtime::NodeRuntime;
  55use parking_lot::Mutex;
  56use postage::watch;
  57use prettier_support::{DefaultPrettier, PrettierInstance};
  58use project_settings::{LspSettings, ProjectSettings};
  59use rand::prelude::*;
  60use search::SearchQuery;
  61use serde::Serialize;
  62use settings::{Settings, SettingsStore};
  63use sha2::{Digest, Sha256};
  64use similar::{ChangeTag, TextDiff};
  65use smol::channel::{Receiver, Sender};
  66use smol::lock::Semaphore;
  67use std::{
  68    cmp::{self, Ordering},
  69    convert::TryInto,
  70    hash::Hash,
  71    mem,
  72    num::NonZeroU32,
  73    ops::Range,
  74    path::{self, Component, Path, PathBuf},
  75    process::Stdio,
  76    str,
  77    sync::{
  78        atomic::{AtomicUsize, Ordering::SeqCst},
  79        Arc,
  80    },
  81    time::{Duration, Instant},
  82};
  83use terminals::Terminals;
  84use text::Anchor;
  85use util::{
  86    debug_panic, defer, http::HttpClient, merge_json_value_into,
  87    paths::LOCAL_SETTINGS_RELATIVE_PATH, post_inc, ResultExt, TryFutureExt as _,
  88};
  89
  90pub use fs::*;
  91#[cfg(any(test, feature = "test-support"))]
  92pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  93pub use worktree::*;
  94
  95const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  96
  97pub trait Item {
  98    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  99    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 100}
 101
 102// Language server state is stored across 3 collections:
 103//     language_servers =>
 104//         a mapping from unique server id to LanguageServerState which can either be a task for a
 105//         server in the process of starting, or a running server with adapter and language server arcs
 106//     language_server_ids => a mapping from worktreeId and server name to the unique server id
 107//     language_server_statuses => a mapping from unique server id to the current server status
 108//
 109// Multiple worktrees can map to the same language server for example when you jump to the definition
 110// of a file in the standard library. So language_server_ids is used to look up which server is active
 111// for a given worktree and language server name
 112//
 113// When starting a language server, first the id map is checked to make sure a server isn't already available
 114// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
 115// the Starting variant of LanguageServerState is stored in the language_servers map.
 116pub struct Project {
 117    worktrees: Vec<WorktreeHandle>,
 118    active_entry: Option<ProjectEntryId>,
 119    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 120    languages: Arc<LanguageRegistry>,
 121    supplementary_language_servers:
 122        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
 123    language_servers: HashMap<LanguageServerId, LanguageServerState>,
 124    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
 125    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
 126    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
 127    client: Arc<client::Client>,
 128    next_entry_id: Arc<AtomicUsize>,
 129    join_project_response_message_id: u32,
 130    next_diagnostic_group_id: usize,
 131    user_store: Model<UserStore>,
 132    fs: Arc<dyn Fs>,
 133    client_state: Option<ProjectClientState>,
 134    collaborators: HashMap<proto::PeerId, Collaborator>,
 135    client_subscriptions: Vec<client::Subscription>,
 136    _subscriptions: Vec<gpui::Subscription>,
 137    next_buffer_id: u64,
 138    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 139    shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
 140    #[allow(clippy::type_complexity)]
 141    loading_buffers_by_path: HashMap<
 142        ProjectPath,
 143        postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
 144    >,
 145    #[allow(clippy::type_complexity)]
 146    loading_local_worktrees:
 147        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
 148    opened_buffers: HashMap<u64, OpenBuffer>,
 149    local_buffer_ids_by_path: HashMap<ProjectPath, u64>,
 150    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, u64>,
 151    /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
 152    /// Used for re-issuing buffer requests when peers temporarily disconnect
 153    incomplete_remote_buffers: HashMap<u64, Option<Model<Buffer>>>,
 154    buffer_snapshots: HashMap<u64, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
 155    buffers_being_formatted: HashSet<u64>,
 156    buffers_needing_diff: HashSet<WeakModel<Buffer>>,
 157    git_diff_debouncer: DelayedDebounced,
 158    nonce: u128,
 159    _maintain_buffer_languages: Task<()>,
 160    _maintain_workspace_config: Task<Result<()>>,
 161    terminals: Terminals,
 162    copilot_lsp_subscription: Option<gpui::Subscription>,
 163    copilot_log_subscription: Option<lsp::Subscription>,
 164    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
 165    node: Option<Arc<dyn NodeRuntime>>,
 166    default_prettier: DefaultPrettier,
 167    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
 168    prettier_instances: HashMap<PathBuf, PrettierInstance>,
 169}
 170
 171struct DelayedDebounced {
 172    task: Option<Task<()>>,
 173    cancel_channel: Option<oneshot::Sender<()>>,
 174}
 175
 176pub enum LanguageServerToQuery {
 177    Primary,
 178    Other(LanguageServerId),
 179}
 180
 181impl DelayedDebounced {
 182    fn new() -> DelayedDebounced {
 183        DelayedDebounced {
 184            task: None,
 185            cancel_channel: None,
 186        }
 187    }
 188
 189    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ModelContext<Project>, func: F)
 190    where
 191        F: 'static + Send + FnOnce(&mut Project, &mut ModelContext<Project>) -> Task<()>,
 192    {
 193        if let Some(channel) = self.cancel_channel.take() {
 194            _ = channel.send(());
 195        }
 196
 197        let (sender, mut receiver) = oneshot::channel::<()>();
 198        self.cancel_channel = Some(sender);
 199
 200        let previous_task = self.task.take();
 201        self.task = Some(cx.spawn(move |project, mut cx| async move {
 202            let mut timer = cx.background_executor().timer(delay).fuse();
 203            if let Some(previous_task) = previous_task {
 204                previous_task.await;
 205            }
 206
 207            futures::select_biased! {
 208                _ = receiver => return,
 209                    _ = timer => {}
 210            }
 211
 212            if let Ok(task) = project.update(&mut cx, |project, cx| (func)(project, cx)) {
 213                task.await;
 214            }
 215        }));
 216    }
 217}
 218
 219struct LspBufferSnapshot {
 220    version: i32,
 221    snapshot: TextBufferSnapshot,
 222}
 223
 224/// Message ordered with respect to buffer operations
 225enum BufferOrderedMessage {
 226    Operation {
 227        buffer_id: u64,
 228        operation: proto::Operation,
 229    },
 230    LanguageServerUpdate {
 231        language_server_id: LanguageServerId,
 232        message: proto::update_language_server::Variant,
 233    },
 234    Resync,
 235}
 236
 237enum LocalProjectUpdate {
 238    WorktreesChanged,
 239    CreateBufferForPeer {
 240        peer_id: proto::PeerId,
 241        buffer_id: u64,
 242    },
 243}
 244
 245enum OpenBuffer {
 246    Strong(Model<Buffer>),
 247    Weak(WeakModel<Buffer>),
 248    Operations(Vec<Operation>),
 249}
 250
 251#[derive(Clone)]
 252enum WorktreeHandle {
 253    Strong(Model<Worktree>),
 254    Weak(WeakModel<Worktree>),
 255}
 256
 257enum ProjectClientState {
 258    Local {
 259        remote_id: u64,
 260        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
 261        _send_updates: Task<Result<()>>,
 262    },
 263    Remote {
 264        sharing_has_stopped: bool,
 265        capability: Capability,
 266        remote_id: u64,
 267        replica_id: ReplicaId,
 268    },
 269}
 270
 271#[derive(Clone, Debug, PartialEq)]
 272pub enum Event {
 273    LanguageServerAdded(LanguageServerId),
 274    LanguageServerRemoved(LanguageServerId),
 275    LanguageServerLog(LanguageServerId, String),
 276    Notification(String),
 277    ActiveEntryChanged(Option<ProjectEntryId>),
 278    ActivateProjectPanel,
 279    WorktreeAdded,
 280    WorktreeRemoved(WorktreeId),
 281    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 282    DiskBasedDiagnosticsStarted {
 283        language_server_id: LanguageServerId,
 284    },
 285    DiskBasedDiagnosticsFinished {
 286        language_server_id: LanguageServerId,
 287    },
 288    DiagnosticsUpdated {
 289        path: ProjectPath,
 290        language_server_id: LanguageServerId,
 291    },
 292    RemoteIdChanged(Option<u64>),
 293    DisconnectedFromHost,
 294    Closed,
 295    DeletedEntry(ProjectEntryId),
 296    CollaboratorUpdated {
 297        old_peer_id: proto::PeerId,
 298        new_peer_id: proto::PeerId,
 299    },
 300    CollaboratorJoined(proto::PeerId),
 301    CollaboratorLeft(proto::PeerId),
 302    RefreshInlayHints,
 303    RevealInProjectPanel(ProjectEntryId),
 304}
 305
 306pub enum LanguageServerState {
 307    Starting(Task<Option<Arc<LanguageServer>>>),
 308
 309    Running {
 310        language: Arc<Language>,
 311        adapter: Arc<CachedLspAdapter>,
 312        server: Arc<LanguageServer>,
 313        watched_paths: HashMap<WorktreeId, GlobSet>,
 314        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 315    },
 316}
 317
 318#[derive(Serialize)]
 319pub struct LanguageServerStatus {
 320    pub name: String,
 321    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 322    pub has_pending_diagnostic_updates: bool,
 323    progress_tokens: HashSet<String>,
 324}
 325
 326#[derive(Clone, Debug, Serialize)]
 327pub struct LanguageServerProgress {
 328    pub message: Option<String>,
 329    pub percentage: Option<usize>,
 330    #[serde(skip_serializing)]
 331    pub last_update_at: Instant,
 332}
 333
 334#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 335pub struct ProjectPath {
 336    pub worktree_id: WorktreeId,
 337    pub path: Arc<Path>,
 338}
 339
 340#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 341pub struct DiagnosticSummary {
 342    pub error_count: usize,
 343    pub warning_count: usize,
 344}
 345
 346#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 347pub struct Location {
 348    pub buffer: Model<Buffer>,
 349    pub range: Range<language::Anchor>,
 350}
 351
 352#[derive(Debug, Clone, PartialEq, Eq)]
 353pub struct InlayHint {
 354    pub position: language::Anchor,
 355    pub label: InlayHintLabel,
 356    pub kind: Option<InlayHintKind>,
 357    pub padding_left: bool,
 358    pub padding_right: bool,
 359    pub tooltip: Option<InlayHintTooltip>,
 360    pub resolve_state: ResolveState,
 361}
 362
 363#[derive(Debug, Clone, PartialEq, Eq)]
 364pub enum ResolveState {
 365    Resolved,
 366    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 367    Resolving,
 368}
 369
 370impl InlayHint {
 371    pub fn text(&self) -> String {
 372        match &self.label {
 373            InlayHintLabel::String(s) => s.to_owned(),
 374            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 375        }
 376    }
 377}
 378
 379#[derive(Debug, Clone, PartialEq, Eq)]
 380pub enum InlayHintLabel {
 381    String(String),
 382    LabelParts(Vec<InlayHintLabelPart>),
 383}
 384
 385#[derive(Debug, Clone, PartialEq, Eq)]
 386pub struct InlayHintLabelPart {
 387    pub value: String,
 388    pub tooltip: Option<InlayHintLabelPartTooltip>,
 389    pub location: Option<(LanguageServerId, lsp::Location)>,
 390}
 391
 392#[derive(Debug, Clone, PartialEq, Eq)]
 393pub enum InlayHintTooltip {
 394    String(String),
 395    MarkupContent(MarkupContent),
 396}
 397
 398#[derive(Debug, Clone, PartialEq, Eq)]
 399pub enum InlayHintLabelPartTooltip {
 400    String(String),
 401    MarkupContent(MarkupContent),
 402}
 403
 404#[derive(Debug, Clone, PartialEq, Eq)]
 405pub struct MarkupContent {
 406    pub kind: HoverBlockKind,
 407    pub value: String,
 408}
 409
 410#[derive(Debug, Clone)]
 411pub struct LocationLink {
 412    pub origin: Option<Location>,
 413    pub target: Location,
 414}
 415
 416#[derive(Debug)]
 417pub struct DocumentHighlight {
 418    pub range: Range<language::Anchor>,
 419    pub kind: DocumentHighlightKind,
 420}
 421
 422#[derive(Clone, Debug)]
 423pub struct Symbol {
 424    pub language_server_name: LanguageServerName,
 425    pub source_worktree_id: WorktreeId,
 426    pub path: ProjectPath,
 427    pub label: CodeLabel,
 428    pub name: String,
 429    pub kind: lsp::SymbolKind,
 430    pub range: Range<Unclipped<PointUtf16>>,
 431    pub signature: [u8; 32],
 432}
 433
 434#[derive(Clone, Debug, PartialEq)]
 435pub struct HoverBlock {
 436    pub text: String,
 437    pub kind: HoverBlockKind,
 438}
 439
 440#[derive(Clone, Debug, PartialEq, Eq)]
 441pub enum HoverBlockKind {
 442    PlainText,
 443    Markdown,
 444    Code { language: String },
 445}
 446
 447#[derive(Debug)]
 448pub struct Hover {
 449    pub contents: Vec<HoverBlock>,
 450    pub range: Option<Range<language::Anchor>>,
 451    pub language: Option<Arc<Language>>,
 452}
 453
 454impl Hover {
 455    pub fn is_empty(&self) -> bool {
 456        self.contents.iter().all(|block| block.text.is_empty())
 457    }
 458}
 459
 460#[derive(Default)]
 461pub struct ProjectTransaction(pub HashMap<Model<Buffer>, language::Transaction>);
 462
 463impl DiagnosticSummary {
 464    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 465        let mut this = Self {
 466            error_count: 0,
 467            warning_count: 0,
 468        };
 469
 470        for entry in diagnostics {
 471            if entry.diagnostic.is_primary {
 472                match entry.diagnostic.severity {
 473                    DiagnosticSeverity::ERROR => this.error_count += 1,
 474                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 475                    _ => {}
 476                }
 477            }
 478        }
 479
 480        this
 481    }
 482
 483    pub fn is_empty(&self) -> bool {
 484        self.error_count == 0 && self.warning_count == 0
 485    }
 486
 487    pub fn to_proto(
 488        &self,
 489        language_server_id: LanguageServerId,
 490        path: &Path,
 491    ) -> proto::DiagnosticSummary {
 492        proto::DiagnosticSummary {
 493            path: path.to_string_lossy().to_string(),
 494            language_server_id: language_server_id.0 as u64,
 495            error_count: self.error_count as u32,
 496            warning_count: self.warning_count as u32,
 497        }
 498    }
 499}
 500
 501#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 502pub struct ProjectEntryId(usize);
 503
 504impl ProjectEntryId {
 505    pub const MAX: Self = Self(usize::MAX);
 506
 507    pub fn new(counter: &AtomicUsize) -> Self {
 508        Self(counter.fetch_add(1, SeqCst))
 509    }
 510
 511    pub fn from_proto(id: u64) -> Self {
 512        Self(id as usize)
 513    }
 514
 515    pub fn to_proto(&self) -> u64 {
 516        self.0 as u64
 517    }
 518
 519    pub fn to_usize(&self) -> usize {
 520        self.0
 521    }
 522}
 523
 524#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 525pub enum FormatTrigger {
 526    Save,
 527    Manual,
 528}
 529
 530struct ProjectLspAdapterDelegate {
 531    project: Model<Project>,
 532    http_client: Arc<dyn HttpClient>,
 533}
 534
 535// Currently, formatting operations are represented differently depending on
 536// whether they come from a language server or an external command.
 537enum FormatOperation {
 538    Lsp(Vec<(Range<Anchor>, String)>),
 539    External(Diff),
 540    Prettier(Diff),
 541}
 542
 543impl FormatTrigger {
 544    fn from_proto(value: i32) -> FormatTrigger {
 545        match value {
 546            0 => FormatTrigger::Save,
 547            1 => FormatTrigger::Manual,
 548            _ => FormatTrigger::Save,
 549        }
 550    }
 551}
 552#[derive(Clone, Debug, PartialEq)]
 553enum SearchMatchCandidate {
 554    OpenBuffer {
 555        buffer: Model<Buffer>,
 556        // This might be an unnamed file without representation on filesystem
 557        path: Option<Arc<Path>>,
 558    },
 559    Path {
 560        worktree_id: WorktreeId,
 561        is_ignored: bool,
 562        path: Arc<Path>,
 563    },
 564}
 565
 566type SearchMatchCandidateIndex = usize;
 567impl SearchMatchCandidate {
 568    fn path(&self) -> Option<Arc<Path>> {
 569        match self {
 570            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
 571            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
 572        }
 573    }
 574}
 575
 576impl Project {
 577    pub fn init_settings(cx: &mut AppContext) {
 578        ProjectSettings::register(cx);
 579    }
 580
 581    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 582        Self::init_settings(cx);
 583
 584        client.add_model_message_handler(Self::handle_add_collaborator);
 585        client.add_model_message_handler(Self::handle_update_project_collaborator);
 586        client.add_model_message_handler(Self::handle_remove_collaborator);
 587        client.add_model_message_handler(Self::handle_buffer_reloaded);
 588        client.add_model_message_handler(Self::handle_buffer_saved);
 589        client.add_model_message_handler(Self::handle_start_language_server);
 590        client.add_model_message_handler(Self::handle_update_language_server);
 591        client.add_model_message_handler(Self::handle_update_project);
 592        client.add_model_message_handler(Self::handle_unshare_project);
 593        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 594        client.add_model_message_handler(Self::handle_update_buffer_file);
 595        client.add_model_request_handler(Self::handle_update_buffer);
 596        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 597        client.add_model_message_handler(Self::handle_update_worktree);
 598        client.add_model_message_handler(Self::handle_update_worktree_settings);
 599        client.add_model_request_handler(Self::handle_create_project_entry);
 600        client.add_model_request_handler(Self::handle_rename_project_entry);
 601        client.add_model_request_handler(Self::handle_copy_project_entry);
 602        client.add_model_request_handler(Self::handle_delete_project_entry);
 603        client.add_model_request_handler(Self::handle_expand_project_entry);
 604        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 605        client.add_model_request_handler(Self::handle_apply_code_action);
 606        client.add_model_request_handler(Self::handle_on_type_formatting);
 607        client.add_model_request_handler(Self::handle_inlay_hints);
 608        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
 609        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
 610        client.add_model_request_handler(Self::handle_reload_buffers);
 611        client.add_model_request_handler(Self::handle_synchronize_buffers);
 612        client.add_model_request_handler(Self::handle_format_buffers);
 613        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
 614        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
 615        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 616        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 617        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 618        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 619        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 620        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 621        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 622        client.add_model_request_handler(Self::handle_search_project);
 623        client.add_model_request_handler(Self::handle_get_project_symbols);
 624        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 625        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 626        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 627        client.add_model_request_handler(Self::handle_save_buffer);
 628        client.add_model_message_handler(Self::handle_update_diff_base);
 629        client.add_model_request_handler(Self::handle_lsp_command::<lsp_ext_command::ExpandMacro>);
 630    }
 631
 632    pub fn local(
 633        client: Arc<Client>,
 634        node: Arc<dyn NodeRuntime>,
 635        user_store: Model<UserStore>,
 636        languages: Arc<LanguageRegistry>,
 637        fs: Arc<dyn Fs>,
 638        cx: &mut AppContext,
 639    ) -> Model<Self> {
 640        cx.new_model(|cx: &mut ModelContext<Self>| {
 641            let (tx, rx) = mpsc::unbounded();
 642            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 643                .detach();
 644            let copilot_lsp_subscription =
 645                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 646            Self {
 647                worktrees: Default::default(),
 648                buffer_ordered_messages_tx: tx,
 649                collaborators: Default::default(),
 650                next_buffer_id: 0,
 651                opened_buffers: Default::default(),
 652                shared_buffers: Default::default(),
 653                incomplete_remote_buffers: Default::default(),
 654                loading_buffers_by_path: Default::default(),
 655                loading_local_worktrees: Default::default(),
 656                local_buffer_ids_by_path: Default::default(),
 657                local_buffer_ids_by_entry_id: Default::default(),
 658                buffer_snapshots: Default::default(),
 659                join_project_response_message_id: 0,
 660                client_state: None,
 661                opened_buffer: watch::channel(),
 662                client_subscriptions: Vec::new(),
 663                _subscriptions: vec![
 664                    cx.observe_global::<SettingsStore>(Self::on_settings_changed),
 665                    cx.on_release(Self::release),
 666                    cx.on_app_quit(Self::shutdown_language_servers),
 667                ],
 668                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 669                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 670                active_entry: None,
 671                languages,
 672                client,
 673                user_store,
 674                fs,
 675                next_entry_id: Default::default(),
 676                next_diagnostic_group_id: Default::default(),
 677                supplementary_language_servers: HashMap::default(),
 678                language_servers: Default::default(),
 679                language_server_ids: Default::default(),
 680                language_server_statuses: Default::default(),
 681                last_workspace_edits_by_language_server: Default::default(),
 682                buffers_being_formatted: Default::default(),
 683                buffers_needing_diff: Default::default(),
 684                git_diff_debouncer: DelayedDebounced::new(),
 685                nonce: StdRng::from_entropy().gen(),
 686                terminals: Terminals {
 687                    local_handles: Vec::new(),
 688                },
 689                copilot_lsp_subscription,
 690                copilot_log_subscription: None,
 691                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 692                node: Some(node),
 693                default_prettier: DefaultPrettier::default(),
 694                prettiers_per_worktree: HashMap::default(),
 695                prettier_instances: HashMap::default(),
 696            }
 697        })
 698    }
 699
 700    pub async fn remote(
 701        remote_id: u64,
 702        client: Arc<Client>,
 703        user_store: Model<UserStore>,
 704        languages: Arc<LanguageRegistry>,
 705        fs: Arc<dyn Fs>,
 706        role: proto::ChannelRole,
 707        mut cx: AsyncAppContext,
 708    ) -> Result<Model<Self>> {
 709        client.authenticate_and_connect(true, &cx).await?;
 710
 711        let subscription = client.subscribe_to_entity(remote_id)?;
 712        let response = client
 713            .request_envelope(proto::JoinProject {
 714                project_id: remote_id,
 715            })
 716            .await?;
 717        let this = cx.new_model(|cx| {
 718            let replica_id = response.payload.replica_id as ReplicaId;
 719
 720            let mut worktrees = Vec::new();
 721            for worktree in response.payload.worktrees {
 722                let worktree =
 723                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx);
 724                worktrees.push(worktree);
 725            }
 726
 727            let (tx, rx) = mpsc::unbounded();
 728            cx.spawn(move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 729                .detach();
 730            let copilot_lsp_subscription =
 731                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 732            let mut this = Self {
 733                worktrees: Vec::new(),
 734                buffer_ordered_messages_tx: tx,
 735                loading_buffers_by_path: Default::default(),
 736                next_buffer_id: 0,
 737                opened_buffer: watch::channel(),
 738                shared_buffers: Default::default(),
 739                incomplete_remote_buffers: Default::default(),
 740                loading_local_worktrees: Default::default(),
 741                local_buffer_ids_by_path: Default::default(),
 742                local_buffer_ids_by_entry_id: Default::default(),
 743                active_entry: None,
 744                collaborators: Default::default(),
 745                join_project_response_message_id: response.message_id,
 746                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 747                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 748                languages,
 749                user_store: user_store.clone(),
 750                fs,
 751                next_entry_id: Default::default(),
 752                next_diagnostic_group_id: Default::default(),
 753                client_subscriptions: Default::default(),
 754                _subscriptions: vec![
 755                    cx.on_release(Self::release),
 756                    cx.on_app_quit(Self::shutdown_language_servers),
 757                ],
 758                client: client.clone(),
 759                client_state: Some(ProjectClientState::Remote {
 760                    sharing_has_stopped: false,
 761                    capability: Capability::ReadWrite,
 762                    remote_id,
 763                    replica_id,
 764                }),
 765                supplementary_language_servers: HashMap::default(),
 766                language_servers: Default::default(),
 767                language_server_ids: Default::default(),
 768                language_server_statuses: response
 769                    .payload
 770                    .language_servers
 771                    .into_iter()
 772                    .map(|server| {
 773                        (
 774                            LanguageServerId(server.id as usize),
 775                            LanguageServerStatus {
 776                                name: server.name,
 777                                pending_work: Default::default(),
 778                                has_pending_diagnostic_updates: false,
 779                                progress_tokens: Default::default(),
 780                            },
 781                        )
 782                    })
 783                    .collect(),
 784                last_workspace_edits_by_language_server: Default::default(),
 785                opened_buffers: Default::default(),
 786                buffers_being_formatted: Default::default(),
 787                buffers_needing_diff: Default::default(),
 788                git_diff_debouncer: DelayedDebounced::new(),
 789                buffer_snapshots: Default::default(),
 790                nonce: StdRng::from_entropy().gen(),
 791                terminals: Terminals {
 792                    local_handles: Vec::new(),
 793                },
 794                copilot_lsp_subscription,
 795                copilot_log_subscription: None,
 796                current_lsp_settings: ProjectSettings::get_global(cx).lsp.clone(),
 797                node: None,
 798                default_prettier: DefaultPrettier::default(),
 799                prettiers_per_worktree: HashMap::default(),
 800                prettier_instances: HashMap::default(),
 801            };
 802            this.set_role(role);
 803            for worktree in worktrees {
 804                let _ = this.add_worktree(&worktree, cx);
 805            }
 806            this
 807        })?;
 808        let subscription = subscription.set_model(&this, &mut cx);
 809
 810        let user_ids = response
 811            .payload
 812            .collaborators
 813            .iter()
 814            .map(|peer| peer.user_id)
 815            .collect();
 816        user_store
 817            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
 818            .await?;
 819
 820        this.update(&mut cx, |this, cx| {
 821            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
 822            this.client_subscriptions.push(subscription);
 823            anyhow::Ok(())
 824        })??;
 825
 826        Ok(this)
 827    }
 828
 829    fn release(&mut self, cx: &mut AppContext) {
 830        match &self.client_state {
 831            Some(ProjectClientState::Local { .. }) => {
 832                let _ = self.unshare_internal(cx);
 833            }
 834            Some(ProjectClientState::Remote { remote_id, .. }) => {
 835                let _ = self.client.send(proto::LeaveProject {
 836                    project_id: *remote_id,
 837                });
 838                self.disconnected_from_host_internal(cx);
 839            }
 840            _ => {}
 841        }
 842    }
 843
 844    fn shutdown_language_servers(
 845        &mut self,
 846        _cx: &mut ModelContext<Self>,
 847    ) -> impl Future<Output = ()> {
 848        let shutdown_futures = self
 849            .language_servers
 850            .drain()
 851            .map(|(_, server_state)| async {
 852                use LanguageServerState::*;
 853                match server_state {
 854                    Running { server, .. } => server.shutdown()?.await,
 855                    Starting(task) => task.await?.shutdown()?.await,
 856                }
 857            })
 858            .collect::<Vec<_>>();
 859
 860        async move {
 861            futures::future::join_all(shutdown_futures).await;
 862        }
 863    }
 864
 865    #[cfg(any(test, feature = "test-support"))]
 866    pub async fn test(
 867        fs: Arc<dyn Fs>,
 868        root_paths: impl IntoIterator<Item = &Path>,
 869        cx: &mut gpui::TestAppContext,
 870    ) -> Model<Project> {
 871        let mut languages = LanguageRegistry::test();
 872        languages.set_executor(cx.executor());
 873        let http_client = util::http::FakeHttpClient::with_404_response();
 874        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 875        let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
 876        let project = cx.update(|cx| {
 877            Project::local(
 878                client,
 879                node_runtime::FakeNodeRuntime::new(),
 880                user_store,
 881                Arc::new(languages),
 882                fs,
 883                cx,
 884            )
 885        });
 886        for path in root_paths {
 887            let (tree, _) = project
 888                .update(cx, |project, cx| {
 889                    project.find_or_create_local_worktree(path, true, cx)
 890                })
 891                .await
 892                .unwrap();
 893            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 894                .await;
 895        }
 896        project
 897    }
 898
 899    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 900        let mut language_servers_to_start = Vec::new();
 901        let mut language_formatters_to_check = Vec::new();
 902        for buffer in self.opened_buffers.values() {
 903            if let Some(buffer) = buffer.upgrade() {
 904                let buffer = buffer.read(cx);
 905                let buffer_file = File::from_dyn(buffer.file());
 906                let buffer_language = buffer.language();
 907                let settings = language_settings(buffer_language, buffer.file(), cx);
 908                if let Some(language) = buffer_language {
 909                    if settings.enable_language_server {
 910                        if let Some(file) = buffer_file {
 911                            language_servers_to_start
 912                                .push((file.worktree.clone(), Arc::clone(language)));
 913                        }
 914                    }
 915                    language_formatters_to_check.push((
 916                        buffer_file.map(|f| f.worktree_id(cx)),
 917                        Arc::clone(language),
 918                        settings.clone(),
 919                    ));
 920                }
 921            }
 922        }
 923
 924        let mut language_servers_to_stop = Vec::new();
 925        let mut language_servers_to_restart = Vec::new();
 926        let languages = self.languages.to_vec();
 927
 928        let new_lsp_settings = ProjectSettings::get_global(cx).lsp.clone();
 929        let current_lsp_settings = &self.current_lsp_settings;
 930        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 931            let language = languages.iter().find_map(|l| {
 932                let adapter = l
 933                    .lsp_adapters()
 934                    .iter()
 935                    .find(|adapter| &adapter.name == started_lsp_name)?;
 936                Some((l, adapter))
 937            });
 938            if let Some((language, adapter)) = language {
 939                let worktree = self.worktree_for_id(*worktree_id, cx);
 940                let file = worktree.as_ref().and_then(|tree| {
 941                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 942                });
 943                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 944                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 945                } else if let Some(worktree) = worktree {
 946                    let server_name = &adapter.name.0;
 947                    match (
 948                        current_lsp_settings.get(server_name),
 949                        new_lsp_settings.get(server_name),
 950                    ) {
 951                        (None, None) => {}
 952                        (Some(_), None) | (None, Some(_)) => {
 953                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 954                        }
 955                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 956                            if current_lsp_settings != new_lsp_settings {
 957                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 958                            }
 959                        }
 960                    }
 961                }
 962            }
 963        }
 964        self.current_lsp_settings = new_lsp_settings;
 965
 966        // Stop all newly-disabled language servers.
 967        for (worktree_id, adapter_name) in language_servers_to_stop {
 968            self.stop_language_server(worktree_id, adapter_name, cx)
 969                .detach();
 970        }
 971
 972        let mut prettier_plugins_by_worktree = HashMap::default();
 973        for (worktree, language, settings) in language_formatters_to_check {
 974            if let Some(plugins) =
 975                prettier_support::prettier_plugins_for_language(&language, &settings)
 976            {
 977                prettier_plugins_by_worktree
 978                    .entry(worktree)
 979                    .or_insert_with(|| HashSet::default())
 980                    .extend(plugins);
 981            }
 982        }
 983        for (worktree, prettier_plugins) in prettier_plugins_by_worktree {
 984            self.install_default_prettier(worktree, prettier_plugins, cx);
 985        }
 986
 987        // Start all the newly-enabled language servers.
 988        for (worktree, language) in language_servers_to_start {
 989            let worktree_path = worktree.read(cx).abs_path();
 990            self.start_language_servers(&worktree, worktree_path, language, cx);
 991        }
 992
 993        // Restart all language servers with changed initialization options.
 994        for (worktree, language) in language_servers_to_restart {
 995            self.restart_language_servers(worktree, language, cx);
 996        }
 997
 998        if self.copilot_lsp_subscription.is_none() {
 999            if let Some(copilot) = Copilot::global(cx) {
1000                for buffer in self.opened_buffers.values() {
1001                    if let Some(buffer) = buffer.upgrade() {
1002                        self.register_buffer_with_copilot(&buffer, cx);
1003                    }
1004                }
1005                self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
1006            }
1007        }
1008
1009        cx.notify();
1010    }
1011
1012    pub fn buffer_for_id(&self, remote_id: u64) -> Option<Model<Buffer>> {
1013        self.opened_buffers
1014            .get(&remote_id)
1015            .and_then(|buffer| buffer.upgrade())
1016    }
1017
1018    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1019        &self.languages
1020    }
1021
1022    pub fn client(&self) -> Arc<Client> {
1023        self.client.clone()
1024    }
1025
1026    pub fn user_store(&self) -> Model<UserStore> {
1027        self.user_store.clone()
1028    }
1029
1030    pub fn opened_buffers(&self) -> Vec<Model<Buffer>> {
1031        self.opened_buffers
1032            .values()
1033            .filter_map(|b| b.upgrade())
1034            .collect()
1035    }
1036
1037    #[cfg(any(test, feature = "test-support"))]
1038    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
1039        let path = path.into();
1040        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
1041            self.opened_buffers.iter().any(|(_, buffer)| {
1042                if let Some(buffer) = buffer.upgrade() {
1043                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1044                        if file.worktree == worktree && file.path() == &path.path {
1045                            return true;
1046                        }
1047                    }
1048                }
1049                false
1050            })
1051        } else {
1052            false
1053        }
1054    }
1055
1056    pub fn fs(&self) -> &Arc<dyn Fs> {
1057        &self.fs
1058    }
1059
1060    pub fn remote_id(&self) -> Option<u64> {
1061        match self.client_state.as_ref()? {
1062            ProjectClientState::Local { remote_id, .. }
1063            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
1064        }
1065    }
1066
1067    pub fn replica_id(&self) -> ReplicaId {
1068        match &self.client_state {
1069            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
1070            _ => 0,
1071        }
1072    }
1073
1074    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1075        if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
1076            updates_tx
1077                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
1078                .ok();
1079        }
1080        cx.notify();
1081    }
1082
1083    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1084        &self.collaborators
1085    }
1086
1087    pub fn host(&self) -> Option<&Collaborator> {
1088        self.collaborators.values().find(|c| c.replica_id == 0)
1089    }
1090
1091    /// Collect all worktrees, including ones that don't appear in the project panel
1092    pub fn worktrees<'a>(&'a self) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1093        self.worktrees
1094            .iter()
1095            .filter_map(move |worktree| worktree.upgrade())
1096    }
1097
1098    /// Collect all user-visible worktrees, the ones that appear in the project panel
1099    pub fn visible_worktrees<'a>(
1100        &'a self,
1101        cx: &'a AppContext,
1102    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
1103        self.worktrees.iter().filter_map(|worktree| {
1104            worktree.upgrade().and_then(|worktree| {
1105                if worktree.read(cx).is_visible() {
1106                    Some(worktree)
1107                } else {
1108                    None
1109                }
1110            })
1111        })
1112    }
1113
1114    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1115        self.visible_worktrees(cx)
1116            .map(|tree| tree.read(cx).root_name())
1117    }
1118
1119    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
1120        self.worktrees()
1121            .find(|worktree| worktree.read(cx).id() == id)
1122    }
1123
1124    pub fn worktree_for_entry(
1125        &self,
1126        entry_id: ProjectEntryId,
1127        cx: &AppContext,
1128    ) -> Option<Model<Worktree>> {
1129        self.worktrees()
1130            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1131    }
1132
1133    pub fn worktree_id_for_entry(
1134        &self,
1135        entry_id: ProjectEntryId,
1136        cx: &AppContext,
1137    ) -> Option<WorktreeId> {
1138        self.worktree_for_entry(entry_id, cx)
1139            .map(|worktree| worktree.read(cx).id())
1140    }
1141
1142    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1143        paths.iter().all(|path| self.contains_path(path, cx))
1144    }
1145
1146    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1147        for worktree in self.worktrees() {
1148            let worktree = worktree.read(cx).as_local();
1149            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1150                return true;
1151            }
1152        }
1153        false
1154    }
1155
1156    pub fn create_entry(
1157        &mut self,
1158        project_path: impl Into<ProjectPath>,
1159        is_directory: bool,
1160        cx: &mut ModelContext<Self>,
1161    ) -> Task<Result<Option<Entry>>> {
1162        let project_path = project_path.into();
1163        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1164            return Task::ready(Ok(None));
1165        };
1166        if self.is_local() {
1167            worktree.update(cx, |worktree, cx| {
1168                worktree
1169                    .as_local_mut()
1170                    .unwrap()
1171                    .create_entry(project_path.path, is_directory, cx)
1172            })
1173        } else {
1174            let client = self.client.clone();
1175            let project_id = self.remote_id().unwrap();
1176            cx.spawn(move |_, mut cx| async move {
1177                let response = client
1178                    .request(proto::CreateProjectEntry {
1179                        worktree_id: project_path.worktree_id.to_proto(),
1180                        project_id,
1181                        path: project_path.path.to_string_lossy().into(),
1182                        is_directory,
1183                    })
1184                    .await?;
1185                match response.entry {
1186                    Some(entry) => worktree
1187                        .update(&mut cx, |worktree, cx| {
1188                            worktree.as_remote_mut().unwrap().insert_entry(
1189                                entry,
1190                                response.worktree_scan_id as usize,
1191                                cx,
1192                            )
1193                        })?
1194                        .await
1195                        .map(Some),
1196                    None => Ok(None),
1197                }
1198            })
1199        }
1200    }
1201
1202    pub fn copy_entry(
1203        &mut self,
1204        entry_id: ProjectEntryId,
1205        new_path: impl Into<Arc<Path>>,
1206        cx: &mut ModelContext<Self>,
1207    ) -> Task<Result<Option<Entry>>> {
1208        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1209            return Task::ready(Ok(None));
1210        };
1211        let new_path = new_path.into();
1212        if self.is_local() {
1213            worktree.update(cx, |worktree, cx| {
1214                worktree
1215                    .as_local_mut()
1216                    .unwrap()
1217                    .copy_entry(entry_id, new_path, cx)
1218            })
1219        } else {
1220            let client = self.client.clone();
1221            let project_id = self.remote_id().unwrap();
1222
1223            cx.spawn(move |_, mut cx| async move {
1224                let response = client
1225                    .request(proto::CopyProjectEntry {
1226                        project_id,
1227                        entry_id: entry_id.to_proto(),
1228                        new_path: new_path.to_string_lossy().into(),
1229                    })
1230                    .await?;
1231                match response.entry {
1232                    Some(entry) => worktree
1233                        .update(&mut cx, |worktree, cx| {
1234                            worktree.as_remote_mut().unwrap().insert_entry(
1235                                entry,
1236                                response.worktree_scan_id as usize,
1237                                cx,
1238                            )
1239                        })?
1240                        .await
1241                        .map(Some),
1242                    None => Ok(None),
1243                }
1244            })
1245        }
1246    }
1247
1248    pub fn rename_entry(
1249        &mut self,
1250        entry_id: ProjectEntryId,
1251        new_path: impl Into<Arc<Path>>,
1252        cx: &mut ModelContext<Self>,
1253    ) -> Task<Result<Option<Entry>>> {
1254        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1255            return Task::ready(Ok(None));
1256        };
1257        let new_path = new_path.into();
1258        if self.is_local() {
1259            worktree.update(cx, |worktree, cx| {
1260                worktree
1261                    .as_local_mut()
1262                    .unwrap()
1263                    .rename_entry(entry_id, new_path, cx)
1264            })
1265        } else {
1266            let client = self.client.clone();
1267            let project_id = self.remote_id().unwrap();
1268
1269            cx.spawn(move |_, mut cx| async move {
1270                let response = client
1271                    .request(proto::RenameProjectEntry {
1272                        project_id,
1273                        entry_id: entry_id.to_proto(),
1274                        new_path: new_path.to_string_lossy().into(),
1275                    })
1276                    .await?;
1277                match response.entry {
1278                    Some(entry) => worktree
1279                        .update(&mut cx, |worktree, cx| {
1280                            worktree.as_remote_mut().unwrap().insert_entry(
1281                                entry,
1282                                response.worktree_scan_id as usize,
1283                                cx,
1284                            )
1285                        })?
1286                        .await
1287                        .map(Some),
1288                    None => Ok(None),
1289                }
1290            })
1291        }
1292    }
1293
1294    pub fn delete_entry(
1295        &mut self,
1296        entry_id: ProjectEntryId,
1297        cx: &mut ModelContext<Self>,
1298    ) -> Option<Task<Result<()>>> {
1299        let worktree = self.worktree_for_entry(entry_id, cx)?;
1300
1301        cx.emit(Event::DeletedEntry(entry_id));
1302
1303        if self.is_local() {
1304            worktree.update(cx, |worktree, cx| {
1305                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1306            })
1307        } else {
1308            let client = self.client.clone();
1309            let project_id = self.remote_id().unwrap();
1310            Some(cx.spawn(move |_, mut cx| async move {
1311                let response = client
1312                    .request(proto::DeleteProjectEntry {
1313                        project_id,
1314                        entry_id: entry_id.to_proto(),
1315                    })
1316                    .await?;
1317                worktree
1318                    .update(&mut cx, move |worktree, cx| {
1319                        worktree.as_remote_mut().unwrap().delete_entry(
1320                            entry_id,
1321                            response.worktree_scan_id as usize,
1322                            cx,
1323                        )
1324                    })?
1325                    .await
1326            }))
1327        }
1328    }
1329
1330    pub fn expand_entry(
1331        &mut self,
1332        worktree_id: WorktreeId,
1333        entry_id: ProjectEntryId,
1334        cx: &mut ModelContext<Self>,
1335    ) -> Option<Task<Result<()>>> {
1336        let worktree = self.worktree_for_id(worktree_id, cx)?;
1337        if self.is_local() {
1338            worktree.update(cx, |worktree, cx| {
1339                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
1340            })
1341        } else {
1342            let worktree = worktree.downgrade();
1343            let request = self.client.request(proto::ExpandProjectEntry {
1344                project_id: self.remote_id().unwrap(),
1345                entry_id: entry_id.to_proto(),
1346            });
1347            Some(cx.spawn(move |_, mut cx| async move {
1348                let response = request.await?;
1349                if let Some(worktree) = worktree.upgrade() {
1350                    worktree
1351                        .update(&mut cx, |worktree, _| {
1352                            worktree
1353                                .as_remote_mut()
1354                                .unwrap()
1355                                .wait_for_snapshot(response.worktree_scan_id as usize)
1356                        })?
1357                        .await?;
1358                }
1359                Ok(())
1360            }))
1361        }
1362    }
1363
1364    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1365        if self.client_state.is_some() {
1366            return Err(anyhow!("project was already shared"));
1367        }
1368        self.client_subscriptions.push(
1369            self.client
1370                .subscribe_to_entity(project_id)?
1371                .set_model(&cx.handle(), &mut cx.to_async()),
1372        );
1373
1374        for open_buffer in self.opened_buffers.values_mut() {
1375            match open_buffer {
1376                OpenBuffer::Strong(_) => {}
1377                OpenBuffer::Weak(buffer) => {
1378                    if let Some(buffer) = buffer.upgrade() {
1379                        *open_buffer = OpenBuffer::Strong(buffer);
1380                    }
1381                }
1382                OpenBuffer::Operations(_) => unreachable!(),
1383            }
1384        }
1385
1386        for worktree_handle in self.worktrees.iter_mut() {
1387            match worktree_handle {
1388                WorktreeHandle::Strong(_) => {}
1389                WorktreeHandle::Weak(worktree) => {
1390                    if let Some(worktree) = worktree.upgrade() {
1391                        *worktree_handle = WorktreeHandle::Strong(worktree);
1392                    }
1393                }
1394            }
1395        }
1396
1397        for (server_id, status) in &self.language_server_statuses {
1398            self.client
1399                .send(proto::StartLanguageServer {
1400                    project_id,
1401                    server: Some(proto::LanguageServer {
1402                        id: server_id.0 as u64,
1403                        name: status.name.clone(),
1404                    }),
1405                })
1406                .log_err();
1407        }
1408
1409        let store = cx.global::<SettingsStore>();
1410        for worktree in self.worktrees() {
1411            let worktree_id = worktree.read(cx).id().to_proto();
1412            for (path, content) in store.local_settings(worktree.entity_id().as_u64() as usize) {
1413                self.client
1414                    .send(proto::UpdateWorktreeSettings {
1415                        project_id,
1416                        worktree_id,
1417                        path: path.to_string_lossy().into(),
1418                        content: Some(content),
1419                    })
1420                    .log_err();
1421            }
1422        }
1423
1424        let (updates_tx, mut updates_rx) = mpsc::unbounded();
1425        let client = self.client.clone();
1426        self.client_state = Some(ProjectClientState::Local {
1427            remote_id: project_id,
1428            updates_tx,
1429            _send_updates: cx.spawn(move |this, mut cx| async move {
1430                while let Some(update) = updates_rx.next().await {
1431                    match update {
1432                        LocalProjectUpdate::WorktreesChanged => {
1433                            let worktrees = this.update(&mut cx, |this, _cx| {
1434                                this.worktrees().collect::<Vec<_>>()
1435                            })?;
1436                            let update_project = this
1437                                .update(&mut cx, |this, cx| {
1438                                    this.client.request(proto::UpdateProject {
1439                                        project_id,
1440                                        worktrees: this.worktree_metadata_protos(cx),
1441                                    })
1442                                })?
1443                                .await;
1444                            if update_project.is_ok() {
1445                                for worktree in worktrees {
1446                                    worktree.update(&mut cx, |worktree, cx| {
1447                                        let worktree = worktree.as_local_mut().unwrap();
1448                                        worktree.share(project_id, cx).detach_and_log_err(cx)
1449                                    })?;
1450                                }
1451                            }
1452                        }
1453                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1454                            let buffer = this.update(&mut cx, |this, _| {
1455                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1456                                let shared_buffers =
1457                                    this.shared_buffers.entry(peer_id).or_default();
1458                                if shared_buffers.insert(buffer_id) {
1459                                    if let OpenBuffer::Strong(buffer) = buffer {
1460                                        Some(buffer.clone())
1461                                    } else {
1462                                        None
1463                                    }
1464                                } else {
1465                                    None
1466                                }
1467                            })?;
1468
1469                            let Some(buffer) = buffer else { continue };
1470                            let operations =
1471                                buffer.update(&mut cx, |b, cx| b.serialize_ops(None, cx))?;
1472                            let operations = operations.await;
1473                            let state = buffer.update(&mut cx, |buffer, _| buffer.to_proto())?;
1474
1475                            let initial_state = proto::CreateBufferForPeer {
1476                                project_id,
1477                                peer_id: Some(peer_id),
1478                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1479                            };
1480                            if client.send(initial_state).log_err().is_some() {
1481                                let client = client.clone();
1482                                cx.background_executor()
1483                                    .spawn(async move {
1484                                        let mut chunks = split_operations(operations).peekable();
1485                                        while let Some(chunk) = chunks.next() {
1486                                            let is_last = chunks.peek().is_none();
1487                                            client.send(proto::CreateBufferForPeer {
1488                                                project_id,
1489                                                peer_id: Some(peer_id),
1490                                                variant: Some(
1491                                                    proto::create_buffer_for_peer::Variant::Chunk(
1492                                                        proto::BufferChunk {
1493                                                            buffer_id,
1494                                                            operations: chunk,
1495                                                            is_last,
1496                                                        },
1497                                                    ),
1498                                                ),
1499                                            })?;
1500                                        }
1501                                        anyhow::Ok(())
1502                                    })
1503                                    .await
1504                                    .log_err();
1505                            }
1506                        }
1507                    }
1508                }
1509                Ok(())
1510            }),
1511        });
1512
1513        self.metadata_changed(cx);
1514        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1515        cx.notify();
1516        Ok(())
1517    }
1518
1519    pub fn reshared(
1520        &mut self,
1521        message: proto::ResharedProject,
1522        cx: &mut ModelContext<Self>,
1523    ) -> Result<()> {
1524        self.shared_buffers.clear();
1525        self.set_collaborators_from_proto(message.collaborators, cx)?;
1526        self.metadata_changed(cx);
1527        Ok(())
1528    }
1529
1530    pub fn rejoined(
1531        &mut self,
1532        message: proto::RejoinedProject,
1533        message_id: u32,
1534        cx: &mut ModelContext<Self>,
1535    ) -> Result<()> {
1536        cx.update_global::<SettingsStore, _>(|store, cx| {
1537            for worktree in &self.worktrees {
1538                store
1539                    .clear_local_settings(worktree.handle_id(), cx)
1540                    .log_err();
1541            }
1542        });
1543
1544        self.join_project_response_message_id = message_id;
1545        self.set_worktrees_from_proto(message.worktrees, cx)?;
1546        self.set_collaborators_from_proto(message.collaborators, cx)?;
1547        self.language_server_statuses = message
1548            .language_servers
1549            .into_iter()
1550            .map(|server| {
1551                (
1552                    LanguageServerId(server.id as usize),
1553                    LanguageServerStatus {
1554                        name: server.name,
1555                        pending_work: Default::default(),
1556                        has_pending_diagnostic_updates: false,
1557                        progress_tokens: Default::default(),
1558                    },
1559                )
1560            })
1561            .collect();
1562        self.buffer_ordered_messages_tx
1563            .unbounded_send(BufferOrderedMessage::Resync)
1564            .unwrap();
1565        cx.notify();
1566        Ok(())
1567    }
1568
1569    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1570        self.unshare_internal(cx)?;
1571        self.metadata_changed(cx);
1572        cx.notify();
1573        Ok(())
1574    }
1575
1576    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1577        if self.is_remote() {
1578            return Err(anyhow!("attempted to unshare a remote project"));
1579        }
1580
1581        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1582            self.collaborators.clear();
1583            self.shared_buffers.clear();
1584            self.client_subscriptions.clear();
1585
1586            for worktree_handle in self.worktrees.iter_mut() {
1587                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1588                    let is_visible = worktree.update(cx, |worktree, _| {
1589                        worktree.as_local_mut().unwrap().unshare();
1590                        worktree.is_visible()
1591                    });
1592                    if !is_visible {
1593                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1594                    }
1595                }
1596            }
1597
1598            for open_buffer in self.opened_buffers.values_mut() {
1599                // Wake up any tasks waiting for peers' edits to this buffer.
1600                if let Some(buffer) = open_buffer.upgrade() {
1601                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1602                }
1603
1604                if let OpenBuffer::Strong(buffer) = open_buffer {
1605                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1606                }
1607            }
1608
1609            self.client.send(proto::UnshareProject {
1610                project_id: remote_id,
1611            })?;
1612
1613            Ok(())
1614        } else {
1615            Err(anyhow!("attempted to unshare an unshared project"))
1616        }
1617    }
1618
1619    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1620        self.disconnected_from_host_internal(cx);
1621        cx.emit(Event::DisconnectedFromHost);
1622        cx.notify();
1623    }
1624
1625    pub fn set_role(&mut self, role: proto::ChannelRole) {
1626        if let Some(ProjectClientState::Remote { capability, .. }) = &mut self.client_state {
1627            *capability = if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin
1628            {
1629                Capability::ReadWrite
1630            } else {
1631                Capability::ReadOnly
1632            };
1633        }
1634    }
1635
1636    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1637        if let Some(ProjectClientState::Remote {
1638            sharing_has_stopped,
1639            ..
1640        }) = &mut self.client_state
1641        {
1642            *sharing_has_stopped = true;
1643
1644            self.collaborators.clear();
1645
1646            for worktree in &self.worktrees {
1647                if let Some(worktree) = worktree.upgrade() {
1648                    worktree.update(cx, |worktree, _| {
1649                        if let Some(worktree) = worktree.as_remote_mut() {
1650                            worktree.disconnected_from_host();
1651                        }
1652                    });
1653                }
1654            }
1655
1656            for open_buffer in self.opened_buffers.values_mut() {
1657                // Wake up any tasks waiting for peers' edits to this buffer.
1658                if let Some(buffer) = open_buffer.upgrade() {
1659                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1660                }
1661
1662                if let OpenBuffer::Strong(buffer) = open_buffer {
1663                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1664                }
1665            }
1666
1667            // Wake up all futures currently waiting on a buffer to get opened,
1668            // to give them a chance to fail now that we've disconnected.
1669            *self.opened_buffer.0.borrow_mut() = ();
1670        }
1671    }
1672
1673    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1674        cx.emit(Event::Closed);
1675    }
1676
1677    pub fn is_disconnected(&self) -> bool {
1678        match &self.client_state {
1679            Some(ProjectClientState::Remote {
1680                sharing_has_stopped,
1681                ..
1682            }) => *sharing_has_stopped,
1683            _ => false,
1684        }
1685    }
1686
1687    pub fn capability(&self) -> Capability {
1688        match &self.client_state {
1689            Some(ProjectClientState::Remote { capability, .. }) => *capability,
1690            Some(ProjectClientState::Local { .. }) | None => Capability::ReadWrite,
1691        }
1692    }
1693
1694    pub fn is_read_only(&self) -> bool {
1695        self.is_disconnected() || self.capability() == Capability::ReadOnly
1696    }
1697
1698    pub fn is_local(&self) -> bool {
1699        match &self.client_state {
1700            Some(ProjectClientState::Remote { .. }) => false,
1701            _ => true,
1702        }
1703    }
1704
1705    pub fn is_remote(&self) -> bool {
1706        !self.is_local()
1707    }
1708
1709    pub fn create_buffer(
1710        &mut self,
1711        text: &str,
1712        language: Option<Arc<Language>>,
1713        cx: &mut ModelContext<Self>,
1714    ) -> Result<Model<Buffer>> {
1715        if self.is_remote() {
1716            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1717        }
1718        let id = post_inc(&mut self.next_buffer_id);
1719        let buffer = cx.new_model(|cx| {
1720            Buffer::new(self.replica_id(), id, text)
1721                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1722        });
1723        self.register_buffer(&buffer, cx)?;
1724        Ok(buffer)
1725    }
1726
1727    pub fn open_path(
1728        &mut self,
1729        path: ProjectPath,
1730        cx: &mut ModelContext<Self>,
1731    ) -> Task<Result<(Option<ProjectEntryId>, AnyModel)>> {
1732        let task = self.open_buffer(path.clone(), cx);
1733        cx.spawn(move |_, cx| async move {
1734            let buffer = task.await?;
1735            let project_entry_id = buffer.read_with(&cx, |buffer, cx| {
1736                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1737            })?;
1738
1739            let buffer: &AnyModel = &buffer;
1740            Ok((project_entry_id, buffer.clone()))
1741        })
1742    }
1743
1744    pub fn open_local_buffer(
1745        &mut self,
1746        abs_path: impl AsRef<Path>,
1747        cx: &mut ModelContext<Self>,
1748    ) -> Task<Result<Model<Buffer>>> {
1749        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1750            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1751        } else {
1752            Task::ready(Err(anyhow!("no such path")))
1753        }
1754    }
1755
1756    pub fn open_buffer(
1757        &mut self,
1758        path: impl Into<ProjectPath>,
1759        cx: &mut ModelContext<Self>,
1760    ) -> Task<Result<Model<Buffer>>> {
1761        let project_path = path.into();
1762        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1763            worktree
1764        } else {
1765            return Task::ready(Err(anyhow!("no such worktree")));
1766        };
1767
1768        // If there is already a buffer for the given path, then return it.
1769        let existing_buffer = self.get_open_buffer(&project_path, cx);
1770        if let Some(existing_buffer) = existing_buffer {
1771            return Task::ready(Ok(existing_buffer));
1772        }
1773
1774        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1775            // If the given path is already being loaded, then wait for that existing
1776            // task to complete and return the same buffer.
1777            hash_map::Entry::Occupied(e) => e.get().clone(),
1778
1779            // Otherwise, record the fact that this path is now being loaded.
1780            hash_map::Entry::Vacant(entry) => {
1781                let (mut tx, rx) = postage::watch::channel();
1782                entry.insert(rx.clone());
1783
1784                let load_buffer = if worktree.read(cx).is_local() {
1785                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1786                } else {
1787                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1788                };
1789
1790                let project_path = project_path.clone();
1791                cx.spawn(move |this, mut cx| async move {
1792                    let load_result = load_buffer.await;
1793                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1794                        // Record the fact that the buffer is no longer loading.
1795                        this.loading_buffers_by_path.remove(&project_path);
1796                        let buffer = load_result.map_err(Arc::new)?;
1797                        Ok(buffer)
1798                    })?);
1799                    anyhow::Ok(())
1800                })
1801                .detach();
1802                rx
1803            }
1804        };
1805
1806        cx.background_executor().spawn(async move {
1807            wait_for_loading_buffer(loading_watch)
1808                .await
1809                .map_err(|error| anyhow!("{project_path:?} opening failure: {error:#}"))
1810        })
1811    }
1812
1813    fn open_local_buffer_internal(
1814        &mut self,
1815        path: &Arc<Path>,
1816        worktree: &Model<Worktree>,
1817        cx: &mut ModelContext<Self>,
1818    ) -> Task<Result<Model<Buffer>>> {
1819        let buffer_id = post_inc(&mut self.next_buffer_id);
1820        let load_buffer = worktree.update(cx, |worktree, cx| {
1821            let worktree = worktree.as_local_mut().unwrap();
1822            worktree.load_buffer(buffer_id, path, cx)
1823        });
1824        cx.spawn(move |this, mut cx| async move {
1825            let buffer = load_buffer.await?;
1826            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))??;
1827            Ok(buffer)
1828        })
1829    }
1830
1831    fn open_remote_buffer_internal(
1832        &mut self,
1833        path: &Arc<Path>,
1834        worktree: &Model<Worktree>,
1835        cx: &mut ModelContext<Self>,
1836    ) -> Task<Result<Model<Buffer>>> {
1837        let rpc = self.client.clone();
1838        let project_id = self.remote_id().unwrap();
1839        let remote_worktree_id = worktree.read(cx).id();
1840        let path = path.clone();
1841        let path_string = path.to_string_lossy().to_string();
1842        cx.spawn(move |this, mut cx| async move {
1843            let response = rpc
1844                .request(proto::OpenBufferByPath {
1845                    project_id,
1846                    worktree_id: remote_worktree_id.to_proto(),
1847                    path: path_string,
1848                })
1849                .await?;
1850            this.update(&mut cx, |this, cx| {
1851                this.wait_for_remote_buffer(response.buffer_id, cx)
1852            })?
1853            .await
1854        })
1855    }
1856
1857    /// LanguageServerName is owned, because it is inserted into a map
1858    pub fn open_local_buffer_via_lsp(
1859        &mut self,
1860        abs_path: lsp::Url,
1861        language_server_id: LanguageServerId,
1862        language_server_name: LanguageServerName,
1863        cx: &mut ModelContext<Self>,
1864    ) -> Task<Result<Model<Buffer>>> {
1865        cx.spawn(move |this, mut cx| async move {
1866            let abs_path = abs_path
1867                .to_file_path()
1868                .map_err(|_| anyhow!("can't convert URI to path"))?;
1869            let (worktree, relative_path) = if let Some(result) =
1870                this.update(&mut cx, |this, cx| this.find_local_worktree(&abs_path, cx))?
1871            {
1872                result
1873            } else {
1874                let worktree = this
1875                    .update(&mut cx, |this, cx| {
1876                        this.create_local_worktree(&abs_path, false, cx)
1877                    })?
1878                    .await?;
1879                this.update(&mut cx, |this, cx| {
1880                    this.language_server_ids.insert(
1881                        (worktree.read(cx).id(), language_server_name),
1882                        language_server_id,
1883                    );
1884                })
1885                .ok();
1886                (worktree, PathBuf::new())
1887            };
1888
1889            let project_path = ProjectPath {
1890                worktree_id: worktree.update(&mut cx, |worktree, _| worktree.id())?,
1891                path: relative_path.into(),
1892            };
1893            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))?
1894                .await
1895        })
1896    }
1897
1898    pub fn open_buffer_by_id(
1899        &mut self,
1900        id: u64,
1901        cx: &mut ModelContext<Self>,
1902    ) -> Task<Result<Model<Buffer>>> {
1903        if let Some(buffer) = self.buffer_for_id(id) {
1904            Task::ready(Ok(buffer))
1905        } else if self.is_local() {
1906            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1907        } else if let Some(project_id) = self.remote_id() {
1908            let request = self
1909                .client
1910                .request(proto::OpenBufferById { project_id, id });
1911            cx.spawn(move |this, mut cx| async move {
1912                let buffer_id = request.await?.buffer_id;
1913                this.update(&mut cx, |this, cx| {
1914                    this.wait_for_remote_buffer(buffer_id, cx)
1915                })?
1916                .await
1917            })
1918        } else {
1919            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1920        }
1921    }
1922
1923    pub fn save_buffers(
1924        &self,
1925        buffers: HashSet<Model<Buffer>>,
1926        cx: &mut ModelContext<Self>,
1927    ) -> Task<Result<()>> {
1928        cx.spawn(move |this, mut cx| async move {
1929            let save_tasks = buffers.into_iter().filter_map(|buffer| {
1930                this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
1931                    .ok()
1932            });
1933            try_join_all(save_tasks).await?;
1934            Ok(())
1935        })
1936    }
1937
1938    pub fn save_buffer(
1939        &self,
1940        buffer: Model<Buffer>,
1941        cx: &mut ModelContext<Self>,
1942    ) -> Task<Result<()>> {
1943        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1944            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1945        };
1946        let worktree = file.worktree.clone();
1947        let path = file.path.clone();
1948        worktree.update(cx, |worktree, cx| match worktree {
1949            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1950            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1951        })
1952    }
1953
1954    pub fn save_buffer_as(
1955        &mut self,
1956        buffer: Model<Buffer>,
1957        abs_path: PathBuf,
1958        cx: &mut ModelContext<Self>,
1959    ) -> Task<Result<()>> {
1960        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1961        let old_file = File::from_dyn(buffer.read(cx).file())
1962            .filter(|f| f.is_local())
1963            .cloned();
1964        cx.spawn(move |this, mut cx| async move {
1965            if let Some(old_file) = &old_file {
1966                this.update(&mut cx, |this, cx| {
1967                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1968                })?;
1969            }
1970            let (worktree, path) = worktree_task.await?;
1971            worktree
1972                .update(&mut cx, |worktree, cx| match worktree {
1973                    Worktree::Local(worktree) => {
1974                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1975                    }
1976                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1977                })?
1978                .await?;
1979
1980            this.update(&mut cx, |this, cx| {
1981                this.detect_language_for_buffer(&buffer, cx);
1982                this.register_buffer_with_language_servers(&buffer, cx);
1983            })?;
1984            Ok(())
1985        })
1986    }
1987
1988    pub fn get_open_buffer(
1989        &mut self,
1990        path: &ProjectPath,
1991        cx: &mut ModelContext<Self>,
1992    ) -> Option<Model<Buffer>> {
1993        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1994        self.opened_buffers.values().find_map(|buffer| {
1995            let buffer = buffer.upgrade()?;
1996            let file = File::from_dyn(buffer.read(cx).file())?;
1997            if file.worktree == worktree && file.path() == &path.path {
1998                Some(buffer)
1999            } else {
2000                None
2001            }
2002        })
2003    }
2004
2005    fn register_buffer(
2006        &mut self,
2007        buffer: &Model<Buffer>,
2008        cx: &mut ModelContext<Self>,
2009    ) -> Result<()> {
2010        self.request_buffer_diff_recalculation(buffer, cx);
2011        buffer.update(cx, |buffer, _| {
2012            buffer.set_language_registry(self.languages.clone())
2013        });
2014
2015        let remote_id = buffer.read(cx).remote_id();
2016        let is_remote = self.is_remote();
2017        let open_buffer = if is_remote || self.is_shared() {
2018            OpenBuffer::Strong(buffer.clone())
2019        } else {
2020            OpenBuffer::Weak(buffer.downgrade())
2021        };
2022
2023        match self.opened_buffers.entry(remote_id) {
2024            hash_map::Entry::Vacant(entry) => {
2025                entry.insert(open_buffer);
2026            }
2027            hash_map::Entry::Occupied(mut entry) => {
2028                if let OpenBuffer::Operations(operations) = entry.get_mut() {
2029                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
2030                } else if entry.get().upgrade().is_some() {
2031                    if is_remote {
2032                        return Ok(());
2033                    } else {
2034                        debug_panic!("buffer {} was already registered", remote_id);
2035                        Err(anyhow!("buffer {} was already registered", remote_id))?;
2036                    }
2037                }
2038                entry.insert(open_buffer);
2039            }
2040        }
2041        cx.subscribe(buffer, |this, buffer, event, cx| {
2042            this.on_buffer_event(buffer, event, cx);
2043        })
2044        .detach();
2045
2046        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2047            if file.is_local {
2048                self.local_buffer_ids_by_path.insert(
2049                    ProjectPath {
2050                        worktree_id: file.worktree_id(cx),
2051                        path: file.path.clone(),
2052                    },
2053                    remote_id,
2054                );
2055
2056                if let Some(entry_id) = file.entry_id {
2057                    self.local_buffer_ids_by_entry_id
2058                        .insert(entry_id, remote_id);
2059                }
2060            }
2061        }
2062
2063        self.detect_language_for_buffer(buffer, cx);
2064        self.register_buffer_with_language_servers(buffer, cx);
2065        self.register_buffer_with_copilot(buffer, cx);
2066        cx.observe_release(buffer, |this, buffer, cx| {
2067            if let Some(file) = File::from_dyn(buffer.file()) {
2068                if file.is_local() {
2069                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2070                    for server in this.language_servers_for_buffer(buffer, cx) {
2071                        server
2072                            .1
2073                            .notify::<lsp::notification::DidCloseTextDocument>(
2074                                lsp::DidCloseTextDocumentParams {
2075                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
2076                                },
2077                            )
2078                            .log_err();
2079                    }
2080                }
2081            }
2082        })
2083        .detach();
2084
2085        *self.opened_buffer.0.borrow_mut() = ();
2086        Ok(())
2087    }
2088
2089    fn register_buffer_with_language_servers(
2090        &mut self,
2091        buffer_handle: &Model<Buffer>,
2092        cx: &mut ModelContext<Self>,
2093    ) {
2094        let buffer = buffer_handle.read(cx);
2095        let buffer_id = buffer.remote_id();
2096
2097        if let Some(file) = File::from_dyn(buffer.file()) {
2098            if !file.is_local() {
2099                return;
2100            }
2101
2102            let abs_path = file.abs_path(cx);
2103            let uri = lsp::Url::from_file_path(&abs_path)
2104                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
2105            let initial_snapshot = buffer.text_snapshot();
2106            let language = buffer.language().cloned();
2107            let worktree_id = file.worktree_id(cx);
2108
2109            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
2110                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
2111                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2112                        .log_err();
2113                }
2114            }
2115
2116            if let Some(language) = language {
2117                for adapter in language.lsp_adapters() {
2118                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
2119                    let server = self
2120                        .language_server_ids
2121                        .get(&(worktree_id, adapter.name.clone()))
2122                        .and_then(|id| self.language_servers.get(id))
2123                        .and_then(|server_state| {
2124                            if let LanguageServerState::Running { server, .. } = server_state {
2125                                Some(server.clone())
2126                            } else {
2127                                None
2128                            }
2129                        });
2130                    let server = match server {
2131                        Some(server) => server,
2132                        None => continue,
2133                    };
2134
2135                    server
2136                        .notify::<lsp::notification::DidOpenTextDocument>(
2137                            lsp::DidOpenTextDocumentParams {
2138                                text_document: lsp::TextDocumentItem::new(
2139                                    uri.clone(),
2140                                    language_id.unwrap_or_default(),
2141                                    0,
2142                                    initial_snapshot.text(),
2143                                ),
2144                            },
2145                        )
2146                        .log_err();
2147
2148                    buffer_handle.update(cx, |buffer, cx| {
2149                        buffer.set_completion_triggers(
2150                            server
2151                                .capabilities()
2152                                .completion_provider
2153                                .as_ref()
2154                                .and_then(|provider| provider.trigger_characters.clone())
2155                                .unwrap_or_default(),
2156                            cx,
2157                        );
2158                    });
2159
2160                    let snapshot = LspBufferSnapshot {
2161                        version: 0,
2162                        snapshot: initial_snapshot.clone(),
2163                    };
2164                    self.buffer_snapshots
2165                        .entry(buffer_id)
2166                        .or_default()
2167                        .insert(server.server_id(), vec![snapshot]);
2168                }
2169            }
2170        }
2171    }
2172
2173    fn unregister_buffer_from_language_servers(
2174        &mut self,
2175        buffer: &Model<Buffer>,
2176        old_file: &File,
2177        cx: &mut ModelContext<Self>,
2178    ) {
2179        let old_path = match old_file.as_local() {
2180            Some(local) => local.abs_path(cx),
2181            None => return,
2182        };
2183
2184        buffer.update(cx, |buffer, cx| {
2185            let worktree_id = old_file.worktree_id(cx);
2186            let ids = &self.language_server_ids;
2187
2188            let language = buffer.language().cloned();
2189            let adapters = language.iter().flat_map(|language| language.lsp_adapters());
2190            for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
2191                buffer.update_diagnostics(server_id, Default::default(), cx);
2192            }
2193
2194            self.buffer_snapshots.remove(&buffer.remote_id());
2195            let file_url = lsp::Url::from_file_path(old_path).unwrap();
2196            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2197                language_server
2198                    .notify::<lsp::notification::DidCloseTextDocument>(
2199                        lsp::DidCloseTextDocumentParams {
2200                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
2201                        },
2202                    )
2203                    .log_err();
2204            }
2205        });
2206    }
2207
2208    fn register_buffer_with_copilot(
2209        &self,
2210        buffer_handle: &Model<Buffer>,
2211        cx: &mut ModelContext<Self>,
2212    ) {
2213        if let Some(copilot) = Copilot::global(cx) {
2214            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
2215        }
2216    }
2217
2218    async fn send_buffer_ordered_messages(
2219        this: WeakModel<Self>,
2220        rx: UnboundedReceiver<BufferOrderedMessage>,
2221        mut cx: AsyncAppContext,
2222    ) -> Result<()> {
2223        const MAX_BATCH_SIZE: usize = 128;
2224
2225        let mut operations_by_buffer_id = HashMap::default();
2226        async fn flush_operations(
2227            this: &WeakModel<Project>,
2228            operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
2229            needs_resync_with_host: &mut bool,
2230            is_local: bool,
2231            cx: &mut AsyncAppContext,
2232        ) -> Result<()> {
2233            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2234                let request = this.update(cx, |this, _| {
2235                    let project_id = this.remote_id()?;
2236                    Some(this.client.request(proto::UpdateBuffer {
2237                        buffer_id,
2238                        project_id,
2239                        operations,
2240                    }))
2241                })?;
2242                if let Some(request) = request {
2243                    if request.await.is_err() && !is_local {
2244                        *needs_resync_with_host = true;
2245                        break;
2246                    }
2247                }
2248            }
2249            Ok(())
2250        }
2251
2252        let mut needs_resync_with_host = false;
2253        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2254
2255        while let Some(changes) = changes.next().await {
2256            let is_local = this.update(&mut cx, |this, _| this.is_local())?;
2257
2258            for change in changes {
2259                match change {
2260                    BufferOrderedMessage::Operation {
2261                        buffer_id,
2262                        operation,
2263                    } => {
2264                        if needs_resync_with_host {
2265                            continue;
2266                        }
2267
2268                        operations_by_buffer_id
2269                            .entry(buffer_id)
2270                            .or_insert(Vec::new())
2271                            .push(operation);
2272                    }
2273
2274                    BufferOrderedMessage::Resync => {
2275                        operations_by_buffer_id.clear();
2276                        if this
2277                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))?
2278                            .await
2279                            .is_ok()
2280                        {
2281                            needs_resync_with_host = false;
2282                        }
2283                    }
2284
2285                    BufferOrderedMessage::LanguageServerUpdate {
2286                        language_server_id,
2287                        message,
2288                    } => {
2289                        flush_operations(
2290                            &this,
2291                            &mut operations_by_buffer_id,
2292                            &mut needs_resync_with_host,
2293                            is_local,
2294                            &mut cx,
2295                        )
2296                        .await?;
2297
2298                        this.update(&mut cx, |this, _| {
2299                            if let Some(project_id) = this.remote_id() {
2300                                this.client
2301                                    .send(proto::UpdateLanguageServer {
2302                                        project_id,
2303                                        language_server_id: language_server_id.0 as u64,
2304                                        variant: Some(message),
2305                                    })
2306                                    .log_err();
2307                            }
2308                        })?;
2309                    }
2310                }
2311            }
2312
2313            flush_operations(
2314                &this,
2315                &mut operations_by_buffer_id,
2316                &mut needs_resync_with_host,
2317                is_local,
2318                &mut cx,
2319            )
2320            .await?;
2321        }
2322
2323        Ok(())
2324    }
2325
2326    fn on_buffer_event(
2327        &mut self,
2328        buffer: Model<Buffer>,
2329        event: &BufferEvent,
2330        cx: &mut ModelContext<Self>,
2331    ) -> Option<()> {
2332        if matches!(
2333            event,
2334            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2335        ) {
2336            self.request_buffer_diff_recalculation(&buffer, cx);
2337        }
2338
2339        match event {
2340            BufferEvent::Operation(operation) => {
2341                self.buffer_ordered_messages_tx
2342                    .unbounded_send(BufferOrderedMessage::Operation {
2343                        buffer_id: buffer.read(cx).remote_id(),
2344                        operation: language::proto::serialize_operation(operation),
2345                    })
2346                    .ok();
2347            }
2348
2349            BufferEvent::Edited { .. } => {
2350                let buffer = buffer.read(cx);
2351                let file = File::from_dyn(buffer.file())?;
2352                let abs_path = file.as_local()?.abs_path(cx);
2353                let uri = lsp::Url::from_file_path(abs_path).unwrap();
2354                let next_snapshot = buffer.text_snapshot();
2355
2356                let language_servers: Vec<_> = self
2357                    .language_servers_for_buffer(buffer, cx)
2358                    .map(|i| i.1.clone())
2359                    .collect();
2360
2361                for language_server in language_servers {
2362                    let language_server = language_server.clone();
2363
2364                    let buffer_snapshots = self
2365                        .buffer_snapshots
2366                        .get_mut(&buffer.remote_id())
2367                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
2368                    let previous_snapshot = buffer_snapshots.last()?;
2369
2370                    let build_incremental_change = || {
2371                        buffer
2372                            .edits_since::<(PointUtf16, usize)>(
2373                                previous_snapshot.snapshot.version(),
2374                            )
2375                            .map(|edit| {
2376                                let edit_start = edit.new.start.0;
2377                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2378                                let new_text = next_snapshot
2379                                    .text_for_range(edit.new.start.1..edit.new.end.1)
2380                                    .collect();
2381                                lsp::TextDocumentContentChangeEvent {
2382                                    range: Some(lsp::Range::new(
2383                                        point_to_lsp(edit_start),
2384                                        point_to_lsp(edit_end),
2385                                    )),
2386                                    range_length: None,
2387                                    text: new_text,
2388                                }
2389                            })
2390                            .collect()
2391                    };
2392
2393                    let document_sync_kind = language_server
2394                        .capabilities()
2395                        .text_document_sync
2396                        .as_ref()
2397                        .and_then(|sync| match sync {
2398                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
2399                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
2400                        });
2401
2402                    let content_changes: Vec<_> = match document_sync_kind {
2403                        Some(lsp::TextDocumentSyncKind::FULL) => {
2404                            vec![lsp::TextDocumentContentChangeEvent {
2405                                range: None,
2406                                range_length: None,
2407                                text: next_snapshot.text(),
2408                            }]
2409                        }
2410                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
2411                        _ => {
2412                            #[cfg(any(test, feature = "test-support"))]
2413                            {
2414                                build_incremental_change()
2415                            }
2416
2417                            #[cfg(not(any(test, feature = "test-support")))]
2418                            {
2419                                continue;
2420                            }
2421                        }
2422                    };
2423
2424                    let next_version = previous_snapshot.version + 1;
2425
2426                    buffer_snapshots.push(LspBufferSnapshot {
2427                        version: next_version,
2428                        snapshot: next_snapshot.clone(),
2429                    });
2430
2431                    language_server
2432                        .notify::<lsp::notification::DidChangeTextDocument>(
2433                            lsp::DidChangeTextDocumentParams {
2434                                text_document: lsp::VersionedTextDocumentIdentifier::new(
2435                                    uri.clone(),
2436                                    next_version,
2437                                ),
2438                                content_changes,
2439                            },
2440                        )
2441                        .log_err();
2442                }
2443            }
2444
2445            BufferEvent::Saved => {
2446                let file = File::from_dyn(buffer.read(cx).file())?;
2447                let worktree_id = file.worktree_id(cx);
2448                let abs_path = file.as_local()?.abs_path(cx);
2449                let text_document = lsp::TextDocumentIdentifier {
2450                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
2451                };
2452
2453                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2454                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
2455
2456                    server
2457                        .notify::<lsp::notification::DidSaveTextDocument>(
2458                            lsp::DidSaveTextDocumentParams {
2459                                text_document: text_document.clone(),
2460                                text,
2461                            },
2462                        )
2463                        .log_err();
2464                }
2465
2466                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2467                for language_server_id in language_server_ids {
2468                    if let Some(LanguageServerState::Running {
2469                        adapter,
2470                        simulate_disk_based_diagnostics_completion,
2471                        ..
2472                    }) = self.language_servers.get_mut(&language_server_id)
2473                    {
2474                        // After saving a buffer using a language server that doesn't provide
2475                        // a disk-based progress token, kick off a timer that will reset every
2476                        // time the buffer is saved. If the timer eventually fires, simulate
2477                        // disk-based diagnostics being finished so that other pieces of UI
2478                        // (e.g., project diagnostics view, diagnostic status bar) can update.
2479                        // We don't emit an event right away because the language server might take
2480                        // some time to publish diagnostics.
2481                        if adapter.disk_based_diagnostics_progress_token.is_none() {
2482                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2483                                Duration::from_secs(1);
2484
2485                            let task = cx.spawn(move |this, mut cx| async move {
2486                                cx.background_executor().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2487                                if let Some(this) = this.upgrade() {
2488                                    this.update(&mut cx, |this, cx| {
2489                                        this.disk_based_diagnostics_finished(
2490                                            language_server_id,
2491                                            cx,
2492                                        );
2493                                        this.buffer_ordered_messages_tx
2494                                            .unbounded_send(
2495                                                BufferOrderedMessage::LanguageServerUpdate {
2496                                                    language_server_id,
2497                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2498                                                },
2499                                            )
2500                                            .ok();
2501                                    }).ok();
2502                                }
2503                            });
2504                            *simulate_disk_based_diagnostics_completion = Some(task);
2505                        }
2506                    }
2507                }
2508            }
2509            BufferEvent::FileHandleChanged => {
2510                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
2511                    return None;
2512                };
2513
2514                let remote_id = buffer.read(cx).remote_id();
2515                if let Some(entry_id) = file.entry_id {
2516                    match self.local_buffer_ids_by_entry_id.get(&entry_id) {
2517                        Some(_) => {
2518                            return None;
2519                        }
2520                        None => {
2521                            self.local_buffer_ids_by_entry_id
2522                                .insert(entry_id, remote_id);
2523                        }
2524                    }
2525                };
2526                self.local_buffer_ids_by_path.insert(
2527                    ProjectPath {
2528                        worktree_id: file.worktree_id(cx),
2529                        path: file.path.clone(),
2530                    },
2531                    remote_id,
2532                );
2533            }
2534            _ => {}
2535        }
2536
2537        None
2538    }
2539
2540    fn request_buffer_diff_recalculation(
2541        &mut self,
2542        buffer: &Model<Buffer>,
2543        cx: &mut ModelContext<Self>,
2544    ) {
2545        self.buffers_needing_diff.insert(buffer.downgrade());
2546        let first_insertion = self.buffers_needing_diff.len() == 1;
2547
2548        let settings = ProjectSettings::get_global(cx);
2549        let delay = if let Some(delay) = settings.git.gutter_debounce {
2550            delay
2551        } else {
2552            if first_insertion {
2553                let this = cx.weak_model();
2554                cx.defer(move |cx| {
2555                    if let Some(this) = this.upgrade() {
2556                        this.update(cx, |this, cx| {
2557                            this.recalculate_buffer_diffs(cx).detach();
2558                        });
2559                    }
2560                });
2561            }
2562            return;
2563        };
2564
2565        const MIN_DELAY: u64 = 50;
2566        let delay = delay.max(MIN_DELAY);
2567        let duration = Duration::from_millis(delay);
2568
2569        self.git_diff_debouncer
2570            .fire_new(duration, cx, move |this, cx| {
2571                this.recalculate_buffer_diffs(cx)
2572            });
2573    }
2574
2575    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2576        let buffers = self.buffers_needing_diff.drain().collect::<Vec<_>>();
2577        cx.spawn(move |this, mut cx| async move {
2578            let tasks: Vec<_> = buffers
2579                .iter()
2580                .filter_map(|buffer| {
2581                    let buffer = buffer.upgrade()?;
2582                    buffer
2583                        .update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx))
2584                        .ok()
2585                        .flatten()
2586                })
2587                .collect();
2588
2589            futures::future::join_all(tasks).await;
2590
2591            this.update(&mut cx, |this, cx| {
2592                if !this.buffers_needing_diff.is_empty() {
2593                    this.recalculate_buffer_diffs(cx).detach();
2594                } else {
2595                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2596                    for buffer in buffers {
2597                        if let Some(buffer) = buffer.upgrade() {
2598                            buffer.update(cx, |_, cx| cx.notify());
2599                        }
2600                    }
2601                }
2602            })
2603            .ok();
2604        })
2605    }
2606
2607    fn language_servers_for_worktree(
2608        &self,
2609        worktree_id: WorktreeId,
2610    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2611        self.language_server_ids
2612            .iter()
2613            .filter_map(move |((language_server_worktree_id, _), id)| {
2614                if *language_server_worktree_id == worktree_id {
2615                    if let Some(LanguageServerState::Running {
2616                        adapter,
2617                        language,
2618                        server,
2619                        ..
2620                    }) = self.language_servers.get(id)
2621                    {
2622                        return Some((adapter, language, server));
2623                    }
2624                }
2625                None
2626            })
2627    }
2628
2629    fn maintain_buffer_languages(
2630        languages: Arc<LanguageRegistry>,
2631        cx: &mut ModelContext<Project>,
2632    ) -> Task<()> {
2633        let mut subscription = languages.subscribe();
2634        let mut prev_reload_count = languages.reload_count();
2635        cx.spawn(move |project, mut cx| async move {
2636            while let Some(()) = subscription.next().await {
2637                if let Some(project) = project.upgrade() {
2638                    // If the language registry has been reloaded, then remove and
2639                    // re-assign the languages on all open buffers.
2640                    let reload_count = languages.reload_count();
2641                    if reload_count > prev_reload_count {
2642                        prev_reload_count = reload_count;
2643                        project
2644                            .update(&mut cx, |this, cx| {
2645                                let buffers = this
2646                                    .opened_buffers
2647                                    .values()
2648                                    .filter_map(|b| b.upgrade())
2649                                    .collect::<Vec<_>>();
2650                                for buffer in buffers {
2651                                    if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned()
2652                                    {
2653                                        this.unregister_buffer_from_language_servers(
2654                                            &buffer, &f, cx,
2655                                        );
2656                                        buffer
2657                                            .update(cx, |buffer, cx| buffer.set_language(None, cx));
2658                                    }
2659                                }
2660                            })
2661                            .ok();
2662                    }
2663
2664                    project
2665                        .update(&mut cx, |project, cx| {
2666                            let mut plain_text_buffers = Vec::new();
2667                            let mut buffers_with_unknown_injections = Vec::new();
2668                            for buffer in project.opened_buffers.values() {
2669                                if let Some(handle) = buffer.upgrade() {
2670                                    let buffer = &handle.read(cx);
2671                                    if buffer.language().is_none()
2672                                        || buffer.language() == Some(&*language::PLAIN_TEXT)
2673                                    {
2674                                        plain_text_buffers.push(handle);
2675                                    } else if buffer.contains_unknown_injections() {
2676                                        buffers_with_unknown_injections.push(handle);
2677                                    }
2678                                }
2679                            }
2680
2681                            for buffer in plain_text_buffers {
2682                                project.detect_language_for_buffer(&buffer, cx);
2683                                project.register_buffer_with_language_servers(&buffer, cx);
2684                            }
2685
2686                            for buffer in buffers_with_unknown_injections {
2687                                buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2688                            }
2689                        })
2690                        .ok();
2691                }
2692            }
2693        })
2694    }
2695
2696    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<Result<()>> {
2697        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2698        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2699
2700        let settings_observation = cx.observe_global::<SettingsStore>(move |_, _| {
2701            *settings_changed_tx.borrow_mut() = ();
2702        });
2703
2704        cx.spawn(move |this, mut cx| async move {
2705            while let Some(_) = settings_changed_rx.next().await {
2706                let servers: Vec<_> = this.update(&mut cx, |this, _| {
2707                    this.language_servers
2708                        .values()
2709                        .filter_map(|state| match state {
2710                            LanguageServerState::Starting(_) => None,
2711                            LanguageServerState::Running {
2712                                adapter, server, ..
2713                            } => Some((adapter.clone(), server.clone())),
2714                        })
2715                        .collect()
2716                })?;
2717
2718                for (adapter, server) in servers {
2719                    let workspace_config = cx
2720                        .update(|cx| adapter.workspace_configuration(server.root_path(), cx))?
2721                        .await;
2722                    server
2723                        .notify::<lsp::notification::DidChangeConfiguration>(
2724                            lsp::DidChangeConfigurationParams {
2725                                settings: workspace_config.clone(),
2726                            },
2727                        )
2728                        .ok();
2729                }
2730            }
2731
2732            drop(settings_observation);
2733            anyhow::Ok(())
2734        })
2735    }
2736
2737    fn detect_language_for_buffer(
2738        &mut self,
2739        buffer_handle: &Model<Buffer>,
2740        cx: &mut ModelContext<Self>,
2741    ) -> Option<()> {
2742        // If the buffer has a language, set it and start the language server if we haven't already.
2743        let buffer = buffer_handle.read(cx);
2744        let full_path = buffer.file()?.full_path(cx);
2745        let content = buffer.as_rope();
2746        let new_language = self
2747            .languages
2748            .language_for_file(&full_path, Some(content))
2749            .now_or_never()?
2750            .ok()?;
2751        self.set_language_for_buffer(buffer_handle, new_language, cx);
2752        None
2753    }
2754
2755    pub fn set_language_for_buffer(
2756        &mut self,
2757        buffer: &Model<Buffer>,
2758        new_language: Arc<Language>,
2759        cx: &mut ModelContext<Self>,
2760    ) {
2761        buffer.update(cx, |buffer, cx| {
2762            if buffer.language().map_or(true, |old_language| {
2763                !Arc::ptr_eq(old_language, &new_language)
2764            }) {
2765                buffer.set_language(Some(new_language.clone()), cx);
2766            }
2767        });
2768
2769        let buffer_file = buffer.read(cx).file().cloned();
2770        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2771        let buffer_file = File::from_dyn(buffer_file.as_ref());
2772        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2773        if let Some(prettier_plugins) =
2774            prettier_support::prettier_plugins_for_language(&new_language, &settings)
2775        {
2776            self.install_default_prettier(worktree, prettier_plugins, cx);
2777        };
2778        if let Some(file) = buffer_file {
2779            let worktree = file.worktree.clone();
2780            if let Some(tree) = worktree.read(cx).as_local() {
2781                self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2782            }
2783        }
2784    }
2785
2786    fn start_language_servers(
2787        &mut self,
2788        worktree: &Model<Worktree>,
2789        worktree_path: Arc<Path>,
2790        language: Arc<Language>,
2791        cx: &mut ModelContext<Self>,
2792    ) {
2793        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2794        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2795        if !settings.enable_language_server {
2796            return;
2797        }
2798
2799        let worktree_id = worktree.read(cx).id();
2800        for adapter in language.lsp_adapters() {
2801            self.start_language_server(
2802                worktree_id,
2803                worktree_path.clone(),
2804                adapter.clone(),
2805                language.clone(),
2806                cx,
2807            );
2808        }
2809    }
2810
2811    fn start_language_server(
2812        &mut self,
2813        worktree_id: WorktreeId,
2814        worktree_path: Arc<Path>,
2815        adapter: Arc<CachedLspAdapter>,
2816        language: Arc<Language>,
2817        cx: &mut ModelContext<Self>,
2818    ) {
2819        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2820            return;
2821        }
2822
2823        let key = (worktree_id, adapter.name.clone());
2824        if self.language_server_ids.contains_key(&key) {
2825            return;
2826        }
2827
2828        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
2829        let pending_server = match self.languages.create_pending_language_server(
2830            stderr_capture.clone(),
2831            language.clone(),
2832            adapter.clone(),
2833            Arc::clone(&worktree_path),
2834            ProjectLspAdapterDelegate::new(self, cx),
2835            cx,
2836        ) {
2837            Some(pending_server) => pending_server,
2838            None => return,
2839        };
2840
2841        let project_settings = ProjectSettings::get_global(cx);
2842        let lsp = project_settings.lsp.get(&adapter.name.0);
2843        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2844
2845        let server_id = pending_server.server_id;
2846        let container_dir = pending_server.container_dir.clone();
2847        let state = LanguageServerState::Starting({
2848            let adapter = adapter.clone();
2849            let server_name = adapter.name.0.clone();
2850            let language = language.clone();
2851            let key = key.clone();
2852
2853            cx.spawn(move |this, mut cx| async move {
2854                let result = Self::setup_and_insert_language_server(
2855                    this.clone(),
2856                    &worktree_path,
2857                    override_options,
2858                    pending_server,
2859                    adapter.clone(),
2860                    language.clone(),
2861                    server_id,
2862                    key,
2863                    &mut cx,
2864                )
2865                .await;
2866
2867                match result {
2868                    Ok(server) => {
2869                        stderr_capture.lock().take();
2870                        server
2871                    }
2872
2873                    Err(err) => {
2874                        log::error!("failed to start language server {server_name:?}: {err}");
2875                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
2876
2877                        let this = this.upgrade()?;
2878                        let container_dir = container_dir?;
2879
2880                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
2881                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2882                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
2883                            log::error!("Hit {max} reinstallation attempts for {server_name:?}");
2884                            return None;
2885                        }
2886
2887                        let installation_test_binary = adapter
2888                            .installation_test_binary(container_dir.to_path_buf())
2889                            .await;
2890
2891                        this.update(&mut cx, |_, cx| {
2892                            Self::check_errored_server(
2893                                language,
2894                                adapter,
2895                                server_id,
2896                                installation_test_binary,
2897                                cx,
2898                            )
2899                        })
2900                        .ok();
2901
2902                        None
2903                    }
2904                }
2905            })
2906        });
2907
2908        self.language_servers.insert(server_id, state);
2909        self.language_server_ids.insert(key, server_id);
2910    }
2911
2912    fn reinstall_language_server(
2913        &mut self,
2914        language: Arc<Language>,
2915        adapter: Arc<CachedLspAdapter>,
2916        server_id: LanguageServerId,
2917        cx: &mut ModelContext<Self>,
2918    ) -> Option<Task<()>> {
2919        log::info!("beginning to reinstall server");
2920
2921        let existing_server = match self.language_servers.remove(&server_id) {
2922            Some(LanguageServerState::Running { server, .. }) => Some(server),
2923            _ => None,
2924        };
2925
2926        for worktree in &self.worktrees {
2927            if let Some(worktree) = worktree.upgrade() {
2928                let key = (worktree.read(cx).id(), adapter.name.clone());
2929                self.language_server_ids.remove(&key);
2930            }
2931        }
2932
2933        Some(cx.spawn(move |this, mut cx| async move {
2934            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2935                log::info!("shutting down existing server");
2936                task.await;
2937            }
2938
2939            // TODO: This is race-safe with regards to preventing new instances from
2940            // starting while deleting, but existing instances in other projects are going
2941            // to be very confused and messed up
2942            let Some(task) = this
2943                .update(&mut cx, |this, cx| {
2944                    this.languages.delete_server_container(adapter.clone(), cx)
2945                })
2946                .log_err()
2947            else {
2948                return;
2949            };
2950            task.await;
2951
2952            this.update(&mut cx, |this, mut cx| {
2953                let worktrees = this.worktrees.clone();
2954                for worktree in worktrees {
2955                    let worktree = match worktree.upgrade() {
2956                        Some(worktree) => worktree.read(cx),
2957                        None => continue,
2958                    };
2959                    let worktree_id = worktree.id();
2960                    let root_path = worktree.abs_path();
2961
2962                    this.start_language_server(
2963                        worktree_id,
2964                        root_path,
2965                        adapter.clone(),
2966                        language.clone(),
2967                        &mut cx,
2968                    );
2969                }
2970            })
2971            .ok();
2972        }))
2973    }
2974
2975    async fn setup_and_insert_language_server(
2976        this: WeakModel<Self>,
2977        worktree_path: &Path,
2978        override_initialization_options: Option<serde_json::Value>,
2979        pending_server: PendingLanguageServer,
2980        adapter: Arc<CachedLspAdapter>,
2981        language: Arc<Language>,
2982        server_id: LanguageServerId,
2983        key: (WorktreeId, LanguageServerName),
2984        cx: &mut AsyncAppContext,
2985    ) -> Result<Option<Arc<LanguageServer>>> {
2986        let language_server = Self::setup_pending_language_server(
2987            this.clone(),
2988            override_initialization_options,
2989            pending_server,
2990            worktree_path,
2991            adapter.clone(),
2992            server_id,
2993            cx,
2994        )
2995        .await?;
2996
2997        let this = match this.upgrade() {
2998            Some(this) => this,
2999            None => return Err(anyhow!("failed to upgrade project handle")),
3000        };
3001
3002        this.update(cx, |this, cx| {
3003            this.insert_newly_running_language_server(
3004                language,
3005                adapter,
3006                language_server.clone(),
3007                server_id,
3008                key,
3009                cx,
3010            )
3011        })??;
3012
3013        Ok(Some(language_server))
3014    }
3015
3016    async fn setup_pending_language_server(
3017        this: WeakModel<Self>,
3018        override_options: Option<serde_json::Value>,
3019        pending_server: PendingLanguageServer,
3020        worktree_path: &Path,
3021        adapter: Arc<CachedLspAdapter>,
3022        server_id: LanguageServerId,
3023        cx: &mut AsyncAppContext,
3024    ) -> Result<Arc<LanguageServer>> {
3025        let workspace_config = cx
3026            .update(|cx| adapter.workspace_configuration(worktree_path, cx))?
3027            .await;
3028        let language_server = pending_server.task.await?;
3029
3030        language_server
3031            .on_notification::<lsp::notification::PublishDiagnostics, _>({
3032                let adapter = adapter.clone();
3033                let this = this.clone();
3034                move |mut params, mut cx| {
3035                    let adapter = adapter.clone();
3036                    if let Some(this) = this.upgrade() {
3037                        adapter.process_diagnostics(&mut params);
3038                        this.update(&mut cx, |this, cx| {
3039                            this.update_diagnostics(
3040                                server_id,
3041                                params,
3042                                &adapter.disk_based_diagnostic_sources,
3043                                cx,
3044                            )
3045                            .log_err();
3046                        })
3047                        .ok();
3048                    }
3049                }
3050            })
3051            .detach();
3052
3053        language_server
3054            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
3055                let adapter = adapter.clone();
3056                let worktree_path = worktree_path.to_path_buf();
3057                move |params, cx| {
3058                    let adapter = adapter.clone();
3059                    let worktree_path = worktree_path.clone();
3060                    async move {
3061                        let workspace_config = cx
3062                            .update(|cx| adapter.workspace_configuration(&worktree_path, cx))?
3063                            .await;
3064                        Ok(params
3065                            .items
3066                            .into_iter()
3067                            .map(|item| {
3068                                if let Some(section) = &item.section {
3069                                    workspace_config
3070                                        .get(section)
3071                                        .cloned()
3072                                        .unwrap_or(serde_json::Value::Null)
3073                                } else {
3074                                    workspace_config.clone()
3075                                }
3076                            })
3077                            .collect())
3078                    }
3079                }
3080            })
3081            .detach();
3082
3083        // Even though we don't have handling for these requests, respond to them to
3084        // avoid stalling any language server like `gopls` which waits for a response
3085        // to these requests when initializing.
3086        language_server
3087            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
3088                let this = this.clone();
3089                move |params, mut cx| {
3090                    let this = this.clone();
3091                    async move {
3092                        this.update(&mut cx, |this, _| {
3093                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
3094                            {
3095                                if let lsp::NumberOrString::String(token) = params.token {
3096                                    status.progress_tokens.insert(token);
3097                                }
3098                            }
3099                        })?;
3100
3101                        Ok(())
3102                    }
3103                }
3104            })
3105            .detach();
3106
3107        language_server
3108            .on_request::<lsp::request::RegisterCapability, _, _>({
3109                let this = this.clone();
3110                move |params, mut cx| {
3111                    let this = this.clone();
3112                    async move {
3113                        for reg in params.registrations {
3114                            if reg.method == "workspace/didChangeWatchedFiles" {
3115                                if let Some(options) = reg.register_options {
3116                                    let options = serde_json::from_value(options)?;
3117                                    this.update(&mut cx, |this, cx| {
3118                                        this.on_lsp_did_change_watched_files(
3119                                            server_id, options, cx,
3120                                        );
3121                                    })?;
3122                                }
3123                            }
3124                        }
3125                        Ok(())
3126                    }
3127                }
3128            })
3129            .detach();
3130
3131        language_server
3132            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3133                let adapter = adapter.clone();
3134                let this = this.clone();
3135                move |params, cx| {
3136                    Self::on_lsp_workspace_edit(
3137                        this.clone(),
3138                        params,
3139                        server_id,
3140                        adapter.clone(),
3141                        cx,
3142                    )
3143                }
3144            })
3145            .detach();
3146
3147        language_server
3148            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3149                let this = this.clone();
3150                move |(), mut cx| {
3151                    let this = this.clone();
3152                    async move {
3153                        this.update(&mut cx, |project, cx| {
3154                            cx.emit(Event::RefreshInlayHints);
3155                            project.remote_id().map(|project_id| {
3156                                project.client.send(proto::RefreshInlayHints { project_id })
3157                            })
3158                        })?
3159                        .transpose()?;
3160                        Ok(())
3161                    }
3162                }
3163            })
3164            .detach();
3165
3166        let disk_based_diagnostics_progress_token =
3167            adapter.disk_based_diagnostics_progress_token.clone();
3168
3169        language_server
3170            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3171                if let Some(this) = this.upgrade() {
3172                    this.update(&mut cx, |this, cx| {
3173                        this.on_lsp_progress(
3174                            params,
3175                            server_id,
3176                            disk_based_diagnostics_progress_token.clone(),
3177                            cx,
3178                        );
3179                    })
3180                    .ok();
3181                }
3182            })
3183            .detach();
3184        let mut initialization_options = adapter.adapter.initialization_options().await;
3185        match (&mut initialization_options, override_options) {
3186            (Some(initialization_options), Some(override_options)) => {
3187                merge_json_value_into(override_options, initialization_options);
3188            }
3189            (None, override_options) => initialization_options = override_options,
3190            _ => {}
3191        }
3192        let language_server = language_server.initialize(initialization_options).await?;
3193
3194        language_server
3195            .notify::<lsp::notification::DidChangeConfiguration>(
3196                lsp::DidChangeConfigurationParams {
3197                    settings: workspace_config,
3198                },
3199            )
3200            .ok();
3201
3202        Ok(language_server)
3203    }
3204
3205    fn insert_newly_running_language_server(
3206        &mut self,
3207        language: Arc<Language>,
3208        adapter: Arc<CachedLspAdapter>,
3209        language_server: Arc<LanguageServer>,
3210        server_id: LanguageServerId,
3211        key: (WorktreeId, LanguageServerName),
3212        cx: &mut ModelContext<Self>,
3213    ) -> Result<()> {
3214        // If the language server for this key doesn't match the server id, don't store the
3215        // server. Which will cause it to be dropped, killing the process
3216        if self
3217            .language_server_ids
3218            .get(&key)
3219            .map(|id| id != &server_id)
3220            .unwrap_or(false)
3221        {
3222            return Ok(());
3223        }
3224
3225        // Update language_servers collection with Running variant of LanguageServerState
3226        // indicating that the server is up and running and ready
3227        self.language_servers.insert(
3228            server_id,
3229            LanguageServerState::Running {
3230                adapter: adapter.clone(),
3231                language: language.clone(),
3232                watched_paths: Default::default(),
3233                server: language_server.clone(),
3234                simulate_disk_based_diagnostics_completion: None,
3235            },
3236        );
3237
3238        self.language_server_statuses.insert(
3239            server_id,
3240            LanguageServerStatus {
3241                name: language_server.name().to_string(),
3242                pending_work: Default::default(),
3243                has_pending_diagnostic_updates: false,
3244                progress_tokens: Default::default(),
3245            },
3246        );
3247
3248        cx.emit(Event::LanguageServerAdded(server_id));
3249
3250        if let Some(project_id) = self.remote_id() {
3251            self.client.send(proto::StartLanguageServer {
3252                project_id,
3253                server: Some(proto::LanguageServer {
3254                    id: server_id.0 as u64,
3255                    name: language_server.name().to_string(),
3256                }),
3257            })?;
3258        }
3259
3260        // Tell the language server about every open buffer in the worktree that matches the language.
3261        for buffer in self.opened_buffers.values() {
3262            if let Some(buffer_handle) = buffer.upgrade() {
3263                let buffer = buffer_handle.read(cx);
3264                let file = match File::from_dyn(buffer.file()) {
3265                    Some(file) => file,
3266                    None => continue,
3267                };
3268                let language = match buffer.language() {
3269                    Some(language) => language,
3270                    None => continue,
3271                };
3272
3273                if file.worktree.read(cx).id() != key.0
3274                    || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3275                {
3276                    continue;
3277                }
3278
3279                let file = match file.as_local() {
3280                    Some(file) => file,
3281                    None => continue,
3282                };
3283
3284                let versions = self
3285                    .buffer_snapshots
3286                    .entry(buffer.remote_id())
3287                    .or_default()
3288                    .entry(server_id)
3289                    .or_insert_with(|| {
3290                        vec![LspBufferSnapshot {
3291                            version: 0,
3292                            snapshot: buffer.text_snapshot(),
3293                        }]
3294                    });
3295
3296                let snapshot = versions.last().unwrap();
3297                let version = snapshot.version;
3298                let initial_snapshot = &snapshot.snapshot;
3299                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3300                language_server.notify::<lsp::notification::DidOpenTextDocument>(
3301                    lsp::DidOpenTextDocumentParams {
3302                        text_document: lsp::TextDocumentItem::new(
3303                            uri,
3304                            adapter
3305                                .language_ids
3306                                .get(language.name().as_ref())
3307                                .cloned()
3308                                .unwrap_or_default(),
3309                            version,
3310                            initial_snapshot.text(),
3311                        ),
3312                    },
3313                )?;
3314
3315                buffer_handle.update(cx, |buffer, cx| {
3316                    buffer.set_completion_triggers(
3317                        language_server
3318                            .capabilities()
3319                            .completion_provider
3320                            .as_ref()
3321                            .and_then(|provider| provider.trigger_characters.clone())
3322                            .unwrap_or_default(),
3323                        cx,
3324                    )
3325                });
3326            }
3327        }
3328
3329        cx.notify();
3330        Ok(())
3331    }
3332
3333    // Returns a list of all of the worktrees which no longer have a language server and the root path
3334    // for the stopped server
3335    fn stop_language_server(
3336        &mut self,
3337        worktree_id: WorktreeId,
3338        adapter_name: LanguageServerName,
3339        cx: &mut ModelContext<Self>,
3340    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3341        let key = (worktree_id, adapter_name);
3342        if let Some(server_id) = self.language_server_ids.remove(&key) {
3343            log::info!("stopping language server {}", key.1 .0);
3344
3345            // Remove other entries for this language server as well
3346            let mut orphaned_worktrees = vec![worktree_id];
3347            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3348            for other_key in other_keys {
3349                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3350                    self.language_server_ids.remove(&other_key);
3351                    orphaned_worktrees.push(other_key.0);
3352                }
3353            }
3354
3355            for buffer in self.opened_buffers.values() {
3356                if let Some(buffer) = buffer.upgrade() {
3357                    buffer.update(cx, |buffer, cx| {
3358                        buffer.update_diagnostics(server_id, Default::default(), cx);
3359                    });
3360                }
3361            }
3362            for worktree in &self.worktrees {
3363                if let Some(worktree) = worktree.upgrade() {
3364                    worktree.update(cx, |worktree, cx| {
3365                        if let Some(worktree) = worktree.as_local_mut() {
3366                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3367                        }
3368                    });
3369                }
3370            }
3371
3372            self.language_server_statuses.remove(&server_id);
3373            cx.notify();
3374
3375            let server_state = self.language_servers.remove(&server_id);
3376            cx.emit(Event::LanguageServerRemoved(server_id));
3377            cx.spawn(move |this, mut cx| async move {
3378                let mut root_path = None;
3379
3380                let server = match server_state {
3381                    Some(LanguageServerState::Starting(task)) => task.await,
3382                    Some(LanguageServerState::Running { server, .. }) => Some(server),
3383                    None => None,
3384                };
3385
3386                if let Some(server) = server {
3387                    root_path = Some(server.root_path().clone());
3388                    if let Some(shutdown) = server.shutdown() {
3389                        shutdown.await;
3390                    }
3391                }
3392
3393                if let Some(this) = this.upgrade() {
3394                    this.update(&mut cx, |this, cx| {
3395                        this.language_server_statuses.remove(&server_id);
3396                        cx.notify();
3397                    })
3398                    .ok();
3399                }
3400
3401                (root_path, orphaned_worktrees)
3402            })
3403        } else {
3404            Task::ready((None, Vec::new()))
3405        }
3406    }
3407
3408    pub fn restart_language_servers_for_buffers(
3409        &mut self,
3410        buffers: impl IntoIterator<Item = Model<Buffer>>,
3411        cx: &mut ModelContext<Self>,
3412    ) -> Option<()> {
3413        let language_server_lookup_info: HashSet<(Model<Worktree>, Arc<Language>)> = buffers
3414            .into_iter()
3415            .filter_map(|buffer| {
3416                let buffer = buffer.read(cx);
3417                let file = File::from_dyn(buffer.file())?;
3418                let full_path = file.full_path(cx);
3419                let language = self
3420                    .languages
3421                    .language_for_file(&full_path, Some(buffer.as_rope()))
3422                    .now_or_never()?
3423                    .ok()?;
3424                Some((file.worktree.clone(), language))
3425            })
3426            .collect();
3427        for (worktree, language) in language_server_lookup_info {
3428            self.restart_language_servers(worktree, language, cx);
3429        }
3430
3431        None
3432    }
3433
3434    // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3435    fn restart_language_servers(
3436        &mut self,
3437        worktree: Model<Worktree>,
3438        language: Arc<Language>,
3439        cx: &mut ModelContext<Self>,
3440    ) {
3441        let worktree_id = worktree.read(cx).id();
3442        let fallback_path = worktree.read(cx).abs_path();
3443
3444        let mut stops = Vec::new();
3445        for adapter in language.lsp_adapters() {
3446            stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3447        }
3448
3449        if stops.is_empty() {
3450            return;
3451        }
3452        let mut stops = stops.into_iter();
3453
3454        cx.spawn(move |this, mut cx| async move {
3455            let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3456            for stop in stops {
3457                let (_, worktrees) = stop.await;
3458                orphaned_worktrees.extend_from_slice(&worktrees);
3459            }
3460
3461            let this = match this.upgrade() {
3462                Some(this) => this,
3463                None => return,
3464            };
3465
3466            this.update(&mut cx, |this, cx| {
3467                // Attempt to restart using original server path. Fallback to passed in
3468                // path if we could not retrieve the root path
3469                let root_path = original_root_path
3470                    .map(|path_buf| Arc::from(path_buf.as_path()))
3471                    .unwrap_or(fallback_path);
3472
3473                this.start_language_servers(&worktree, root_path, language.clone(), cx);
3474
3475                // Lookup new server ids and set them for each of the orphaned worktrees
3476                for adapter in language.lsp_adapters() {
3477                    if let Some(new_server_id) = this
3478                        .language_server_ids
3479                        .get(&(worktree_id, adapter.name.clone()))
3480                        .cloned()
3481                    {
3482                        for &orphaned_worktree in &orphaned_worktrees {
3483                            this.language_server_ids
3484                                .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3485                        }
3486                    }
3487                }
3488            })
3489            .ok();
3490        })
3491        .detach();
3492    }
3493
3494    fn check_errored_server(
3495        language: Arc<Language>,
3496        adapter: Arc<CachedLspAdapter>,
3497        server_id: LanguageServerId,
3498        installation_test_binary: Option<LanguageServerBinary>,
3499        cx: &mut ModelContext<Self>,
3500    ) {
3501        if !adapter.can_be_reinstalled() {
3502            log::info!(
3503                "Validation check requested for {:?} but it cannot be reinstalled",
3504                adapter.name.0
3505            );
3506            return;
3507        }
3508
3509        cx.spawn(move |this, mut cx| async move {
3510            log::info!("About to spawn test binary");
3511
3512            // A lack of test binary counts as a failure
3513            let process = installation_test_binary.and_then(|binary| {
3514                smol::process::Command::new(&binary.path)
3515                    .current_dir(&binary.path)
3516                    .args(binary.arguments)
3517                    .stdin(Stdio::piped())
3518                    .stdout(Stdio::piped())
3519                    .stderr(Stdio::inherit())
3520                    .kill_on_drop(true)
3521                    .spawn()
3522                    .ok()
3523            });
3524
3525            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3526            let mut timeout = cx.background_executor().timer(PROCESS_TIMEOUT).fuse();
3527
3528            let mut errored = false;
3529            if let Some(mut process) = process {
3530                futures::select! {
3531                    status = process.status().fuse() => match status {
3532                        Ok(status) => errored = !status.success(),
3533                        Err(_) => errored = true,
3534                    },
3535
3536                    _ = timeout => {
3537                        log::info!("test binary time-ed out, this counts as a success");
3538                        _ = process.kill();
3539                    }
3540                }
3541            } else {
3542                log::warn!("test binary failed to launch");
3543                errored = true;
3544            }
3545
3546            if errored {
3547                log::warn!("test binary check failed");
3548                let task = this
3549                    .update(&mut cx, move |this, mut cx| {
3550                        this.reinstall_language_server(language, adapter, server_id, &mut cx)
3551                    })
3552                    .ok()
3553                    .flatten();
3554
3555                if let Some(task) = task {
3556                    task.await;
3557                }
3558            }
3559        })
3560        .detach();
3561    }
3562
3563    fn on_lsp_progress(
3564        &mut self,
3565        progress: lsp::ProgressParams,
3566        language_server_id: LanguageServerId,
3567        disk_based_diagnostics_progress_token: Option<String>,
3568        cx: &mut ModelContext<Self>,
3569    ) {
3570        let token = match progress.token {
3571            lsp::NumberOrString::String(token) => token,
3572            lsp::NumberOrString::Number(token) => {
3573                log::info!("skipping numeric progress token {}", token);
3574                return;
3575            }
3576        };
3577        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3578        let language_server_status =
3579            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3580                status
3581            } else {
3582                return;
3583            };
3584
3585        if !language_server_status.progress_tokens.contains(&token) {
3586            return;
3587        }
3588
3589        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3590            .as_ref()
3591            .map_or(false, |disk_based_token| {
3592                token.starts_with(disk_based_token)
3593            });
3594
3595        match progress {
3596            lsp::WorkDoneProgress::Begin(report) => {
3597                if is_disk_based_diagnostics_progress {
3598                    language_server_status.has_pending_diagnostic_updates = true;
3599                    self.disk_based_diagnostics_started(language_server_id, cx);
3600                    self.buffer_ordered_messages_tx
3601                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3602                            language_server_id,
3603                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3604                        })
3605                        .ok();
3606                } else {
3607                    self.on_lsp_work_start(
3608                        language_server_id,
3609                        token.clone(),
3610                        LanguageServerProgress {
3611                            message: report.message.clone(),
3612                            percentage: report.percentage.map(|p| p as usize),
3613                            last_update_at: Instant::now(),
3614                        },
3615                        cx,
3616                    );
3617                    self.buffer_ordered_messages_tx
3618                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3619                            language_server_id,
3620                            message: proto::update_language_server::Variant::WorkStart(
3621                                proto::LspWorkStart {
3622                                    token,
3623                                    message: report.message,
3624                                    percentage: report.percentage.map(|p| p as u32),
3625                                },
3626                            ),
3627                        })
3628                        .ok();
3629                }
3630            }
3631            lsp::WorkDoneProgress::Report(report) => {
3632                if !is_disk_based_diagnostics_progress {
3633                    self.on_lsp_work_progress(
3634                        language_server_id,
3635                        token.clone(),
3636                        LanguageServerProgress {
3637                            message: report.message.clone(),
3638                            percentage: report.percentage.map(|p| p as usize),
3639                            last_update_at: Instant::now(),
3640                        },
3641                        cx,
3642                    );
3643                    self.buffer_ordered_messages_tx
3644                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3645                            language_server_id,
3646                            message: proto::update_language_server::Variant::WorkProgress(
3647                                proto::LspWorkProgress {
3648                                    token,
3649                                    message: report.message,
3650                                    percentage: report.percentage.map(|p| p as u32),
3651                                },
3652                            ),
3653                        })
3654                        .ok();
3655                }
3656            }
3657            lsp::WorkDoneProgress::End(_) => {
3658                language_server_status.progress_tokens.remove(&token);
3659
3660                if is_disk_based_diagnostics_progress {
3661                    language_server_status.has_pending_diagnostic_updates = false;
3662                    self.disk_based_diagnostics_finished(language_server_id, cx);
3663                    self.buffer_ordered_messages_tx
3664                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3665                            language_server_id,
3666                            message:
3667                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3668                                    Default::default(),
3669                                ),
3670                        })
3671                        .ok();
3672                } else {
3673                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3674                    self.buffer_ordered_messages_tx
3675                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3676                            language_server_id,
3677                            message: proto::update_language_server::Variant::WorkEnd(
3678                                proto::LspWorkEnd { token },
3679                            ),
3680                        })
3681                        .ok();
3682                }
3683            }
3684        }
3685    }
3686
3687    fn on_lsp_work_start(
3688        &mut self,
3689        language_server_id: LanguageServerId,
3690        token: String,
3691        progress: LanguageServerProgress,
3692        cx: &mut ModelContext<Self>,
3693    ) {
3694        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3695            status.pending_work.insert(token, progress);
3696            cx.notify();
3697        }
3698    }
3699
3700    fn on_lsp_work_progress(
3701        &mut self,
3702        language_server_id: LanguageServerId,
3703        token: String,
3704        progress: LanguageServerProgress,
3705        cx: &mut ModelContext<Self>,
3706    ) {
3707        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3708            let entry = status
3709                .pending_work
3710                .entry(token)
3711                .or_insert(LanguageServerProgress {
3712                    message: Default::default(),
3713                    percentage: Default::default(),
3714                    last_update_at: progress.last_update_at,
3715                });
3716            if progress.message.is_some() {
3717                entry.message = progress.message;
3718            }
3719            if progress.percentage.is_some() {
3720                entry.percentage = progress.percentage;
3721            }
3722            entry.last_update_at = progress.last_update_at;
3723            cx.notify();
3724        }
3725    }
3726
3727    fn on_lsp_work_end(
3728        &mut self,
3729        language_server_id: LanguageServerId,
3730        token: String,
3731        cx: &mut ModelContext<Self>,
3732    ) {
3733        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3734            cx.emit(Event::RefreshInlayHints);
3735            status.pending_work.remove(&token);
3736            cx.notify();
3737        }
3738    }
3739
3740    fn on_lsp_did_change_watched_files(
3741        &mut self,
3742        language_server_id: LanguageServerId,
3743        params: DidChangeWatchedFilesRegistrationOptions,
3744        cx: &mut ModelContext<Self>,
3745    ) {
3746        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3747            self.language_servers.get_mut(&language_server_id)
3748        {
3749            let mut builders = HashMap::default();
3750            for watcher in params.watchers {
3751                for worktree in &self.worktrees {
3752                    if let Some(worktree) = worktree.upgrade() {
3753                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3754                            if let Some(abs_path) = tree.abs_path().to_str() {
3755                                let relative_glob_pattern = match &watcher.glob_pattern {
3756                                    lsp::GlobPattern::String(s) => s
3757                                        .strip_prefix(abs_path)
3758                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3759                                    lsp::GlobPattern::Relative(rp) => {
3760                                        let base_uri = match &rp.base_uri {
3761                                            lsp::OneOf::Left(workspace_folder) => {
3762                                                &workspace_folder.uri
3763                                            }
3764                                            lsp::OneOf::Right(base_uri) => base_uri,
3765                                        };
3766                                        base_uri.to_file_path().ok().and_then(|file_path| {
3767                                            (file_path.to_str() == Some(abs_path))
3768                                                .then_some(rp.pattern.as_str())
3769                                        })
3770                                    }
3771                                };
3772                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3773                                    let literal_prefix =
3774                                        glob_literal_prefix(&relative_glob_pattern);
3775                                    tree.as_local_mut()
3776                                        .unwrap()
3777                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3778                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3779                                        builders
3780                                            .entry(tree.id())
3781                                            .or_insert_with(|| GlobSetBuilder::new())
3782                                            .add(glob);
3783                                    }
3784                                    return true;
3785                                }
3786                            }
3787                            false
3788                        });
3789                        if glob_is_inside_worktree {
3790                            break;
3791                        }
3792                    }
3793                }
3794            }
3795
3796            watched_paths.clear();
3797            for (worktree_id, builder) in builders {
3798                if let Ok(globset) = builder.build() {
3799                    watched_paths.insert(worktree_id, globset);
3800                }
3801            }
3802
3803            cx.notify();
3804        }
3805    }
3806
3807    async fn on_lsp_workspace_edit(
3808        this: WeakModel<Self>,
3809        params: lsp::ApplyWorkspaceEditParams,
3810        server_id: LanguageServerId,
3811        adapter: Arc<CachedLspAdapter>,
3812        mut cx: AsyncAppContext,
3813    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3814        let this = this
3815            .upgrade()
3816            .ok_or_else(|| anyhow!("project project closed"))?;
3817        let language_server = this
3818            .update(&mut cx, |this, _| this.language_server_for_id(server_id))?
3819            .ok_or_else(|| anyhow!("language server not found"))?;
3820        let transaction = Self::deserialize_workspace_edit(
3821            this.clone(),
3822            params.edit,
3823            true,
3824            adapter.clone(),
3825            language_server.clone(),
3826            &mut cx,
3827        )
3828        .await
3829        .log_err();
3830        this.update(&mut cx, |this, _| {
3831            if let Some(transaction) = transaction {
3832                this.last_workspace_edits_by_language_server
3833                    .insert(server_id, transaction);
3834            }
3835        })?;
3836        Ok(lsp::ApplyWorkspaceEditResponse {
3837            applied: true,
3838            failed_change: None,
3839            failure_reason: None,
3840        })
3841    }
3842
3843    pub fn language_server_statuses(
3844        &self,
3845    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3846        self.language_server_statuses.values()
3847    }
3848
3849    pub fn update_diagnostics(
3850        &mut self,
3851        language_server_id: LanguageServerId,
3852        mut params: lsp::PublishDiagnosticsParams,
3853        disk_based_sources: &[String],
3854        cx: &mut ModelContext<Self>,
3855    ) -> Result<()> {
3856        let abs_path = params
3857            .uri
3858            .to_file_path()
3859            .map_err(|_| anyhow!("URI is not a file"))?;
3860        let mut diagnostics = Vec::default();
3861        let mut primary_diagnostic_group_ids = HashMap::default();
3862        let mut sources_by_group_id = HashMap::default();
3863        let mut supporting_diagnostics = HashMap::default();
3864
3865        // Ensure that primary diagnostics are always the most severe
3866        params.diagnostics.sort_by_key(|item| item.severity);
3867
3868        for diagnostic in &params.diagnostics {
3869            let source = diagnostic.source.as_ref();
3870            let code = diagnostic.code.as_ref().map(|code| match code {
3871                lsp::NumberOrString::Number(code) => code.to_string(),
3872                lsp::NumberOrString::String(code) => code.clone(),
3873            });
3874            let range = range_from_lsp(diagnostic.range);
3875            let is_supporting = diagnostic
3876                .related_information
3877                .as_ref()
3878                .map_or(false, |infos| {
3879                    infos.iter().any(|info| {
3880                        primary_diagnostic_group_ids.contains_key(&(
3881                            source,
3882                            code.clone(),
3883                            range_from_lsp(info.location.range),
3884                        ))
3885                    })
3886                });
3887
3888            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3889                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3890            });
3891
3892            if is_supporting {
3893                supporting_diagnostics.insert(
3894                    (source, code.clone(), range),
3895                    (diagnostic.severity, is_unnecessary),
3896                );
3897            } else {
3898                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3899                let is_disk_based =
3900                    source.map_or(false, |source| disk_based_sources.contains(source));
3901
3902                sources_by_group_id.insert(group_id, source);
3903                primary_diagnostic_group_ids
3904                    .insert((source, code.clone(), range.clone()), group_id);
3905
3906                diagnostics.push(DiagnosticEntry {
3907                    range,
3908                    diagnostic: Diagnostic {
3909                        source: diagnostic.source.clone(),
3910                        code: code.clone(),
3911                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3912                        message: diagnostic.message.clone(),
3913                        group_id,
3914                        is_primary: true,
3915                        is_valid: true,
3916                        is_disk_based,
3917                        is_unnecessary,
3918                    },
3919                });
3920                if let Some(infos) = &diagnostic.related_information {
3921                    for info in infos {
3922                        if info.location.uri == params.uri && !info.message.is_empty() {
3923                            let range = range_from_lsp(info.location.range);
3924                            diagnostics.push(DiagnosticEntry {
3925                                range,
3926                                diagnostic: Diagnostic {
3927                                    source: diagnostic.source.clone(),
3928                                    code: code.clone(),
3929                                    severity: DiagnosticSeverity::INFORMATION,
3930                                    message: info.message.clone(),
3931                                    group_id,
3932                                    is_primary: false,
3933                                    is_valid: true,
3934                                    is_disk_based,
3935                                    is_unnecessary: false,
3936                                },
3937                            });
3938                        }
3939                    }
3940                }
3941            }
3942        }
3943
3944        for entry in &mut diagnostics {
3945            let diagnostic = &mut entry.diagnostic;
3946            if !diagnostic.is_primary {
3947                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3948                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3949                    source,
3950                    diagnostic.code.clone(),
3951                    entry.range.clone(),
3952                )) {
3953                    if let Some(severity) = severity {
3954                        diagnostic.severity = severity;
3955                    }
3956                    diagnostic.is_unnecessary = is_unnecessary;
3957                }
3958            }
3959        }
3960
3961        self.update_diagnostic_entries(
3962            language_server_id,
3963            abs_path,
3964            params.version,
3965            diagnostics,
3966            cx,
3967        )?;
3968        Ok(())
3969    }
3970
3971    pub fn update_diagnostic_entries(
3972        &mut self,
3973        server_id: LanguageServerId,
3974        abs_path: PathBuf,
3975        version: Option<i32>,
3976        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3977        cx: &mut ModelContext<Project>,
3978    ) -> Result<(), anyhow::Error> {
3979        let (worktree, relative_path) = self
3980            .find_local_worktree(&abs_path, cx)
3981            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3982
3983        let project_path = ProjectPath {
3984            worktree_id: worktree.read(cx).id(),
3985            path: relative_path.into(),
3986        };
3987
3988        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3989            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3990        }
3991
3992        let updated = worktree.update(cx, |worktree, cx| {
3993            worktree
3994                .as_local_mut()
3995                .ok_or_else(|| anyhow!("not a local worktree"))?
3996                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3997        })?;
3998        if updated {
3999            cx.emit(Event::DiagnosticsUpdated {
4000                language_server_id: server_id,
4001                path: project_path,
4002            });
4003        }
4004        Ok(())
4005    }
4006
4007    fn update_buffer_diagnostics(
4008        &mut self,
4009        buffer: &Model<Buffer>,
4010        server_id: LanguageServerId,
4011        version: Option<i32>,
4012        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
4013        cx: &mut ModelContext<Self>,
4014    ) -> Result<()> {
4015        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
4016            Ordering::Equal
4017                .then_with(|| b.is_primary.cmp(&a.is_primary))
4018                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
4019                .then_with(|| a.severity.cmp(&b.severity))
4020                .then_with(|| a.message.cmp(&b.message))
4021        }
4022
4023        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
4024
4025        diagnostics.sort_unstable_by(|a, b| {
4026            Ordering::Equal
4027                .then_with(|| a.range.start.cmp(&b.range.start))
4028                .then_with(|| b.range.end.cmp(&a.range.end))
4029                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
4030        });
4031
4032        let mut sanitized_diagnostics = Vec::new();
4033        let edits_since_save = Patch::new(
4034            snapshot
4035                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
4036                .collect(),
4037        );
4038        for entry in diagnostics {
4039            let start;
4040            let end;
4041            if entry.diagnostic.is_disk_based {
4042                // Some diagnostics are based on files on disk instead of buffers'
4043                // current contents. Adjust these diagnostics' ranges to reflect
4044                // any unsaved edits.
4045                start = edits_since_save.old_to_new(entry.range.start);
4046                end = edits_since_save.old_to_new(entry.range.end);
4047            } else {
4048                start = entry.range.start;
4049                end = entry.range.end;
4050            }
4051
4052            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
4053                ..snapshot.clip_point_utf16(end, Bias::Right);
4054
4055            // Expand empty ranges by one codepoint
4056            if range.start == range.end {
4057                // This will be go to the next boundary when being clipped
4058                range.end.column += 1;
4059                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
4060                if range.start == range.end && range.end.column > 0 {
4061                    range.start.column -= 1;
4062                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
4063                }
4064            }
4065
4066            sanitized_diagnostics.push(DiagnosticEntry {
4067                range,
4068                diagnostic: entry.diagnostic,
4069            });
4070        }
4071        drop(edits_since_save);
4072
4073        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
4074        buffer.update(cx, |buffer, cx| {
4075            buffer.update_diagnostics(server_id, set, cx)
4076        });
4077        Ok(())
4078    }
4079
4080    pub fn reload_buffers(
4081        &self,
4082        buffers: HashSet<Model<Buffer>>,
4083        push_to_history: bool,
4084        cx: &mut ModelContext<Self>,
4085    ) -> Task<Result<ProjectTransaction>> {
4086        let mut local_buffers = Vec::new();
4087        let mut remote_buffers = None;
4088        for buffer_handle in buffers {
4089            let buffer = buffer_handle.read(cx);
4090            if buffer.is_dirty() {
4091                if let Some(file) = File::from_dyn(buffer.file()) {
4092                    if file.is_local() {
4093                        local_buffers.push(buffer_handle);
4094                    } else {
4095                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
4096                    }
4097                }
4098            }
4099        }
4100
4101        let remote_buffers = self.remote_id().zip(remote_buffers);
4102        let client = self.client.clone();
4103
4104        cx.spawn(move |this, mut cx| async move {
4105            let mut project_transaction = ProjectTransaction::default();
4106
4107            if let Some((project_id, remote_buffers)) = remote_buffers {
4108                let response = client
4109                    .request(proto::ReloadBuffers {
4110                        project_id,
4111                        buffer_ids: remote_buffers
4112                            .iter()
4113                            .filter_map(|buffer| {
4114                                buffer.update(&mut cx, |buffer, _| buffer.remote_id()).ok()
4115                            })
4116                            .collect(),
4117                    })
4118                    .await?
4119                    .transaction
4120                    .ok_or_else(|| anyhow!("missing transaction"))?;
4121                project_transaction = this
4122                    .update(&mut cx, |this, cx| {
4123                        this.deserialize_project_transaction(response, push_to_history, cx)
4124                    })?
4125                    .await?;
4126            }
4127
4128            for buffer in local_buffers {
4129                let transaction = buffer
4130                    .update(&mut cx, |buffer, cx| buffer.reload(cx))?
4131                    .await?;
4132                buffer.update(&mut cx, |buffer, cx| {
4133                    if let Some(transaction) = transaction {
4134                        if !push_to_history {
4135                            buffer.forget_transaction(transaction.id);
4136                        }
4137                        project_transaction.0.insert(cx.handle(), transaction);
4138                    }
4139                })?;
4140            }
4141
4142            Ok(project_transaction)
4143        })
4144    }
4145
4146    pub fn format(
4147        &mut self,
4148        buffers: HashSet<Model<Buffer>>,
4149        push_to_history: bool,
4150        trigger: FormatTrigger,
4151        cx: &mut ModelContext<Project>,
4152    ) -> Task<anyhow::Result<ProjectTransaction>> {
4153        if self.is_local() {
4154            let mut buffers_with_paths_and_servers = buffers
4155                .into_iter()
4156                .filter_map(|buffer_handle| {
4157                    let buffer = buffer_handle.read(cx);
4158                    let file = File::from_dyn(buffer.file())?;
4159                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4160                    let server = self
4161                        .primary_language_server_for_buffer(buffer, cx)
4162                        .map(|s| s.1.clone());
4163                    Some((buffer_handle, buffer_abs_path, server))
4164                })
4165                .collect::<Vec<_>>();
4166
4167            cx.spawn(move |project, mut cx| async move {
4168                // Do not allow multiple concurrent formatting requests for the
4169                // same buffer.
4170                project.update(&mut cx, |this, cx| {
4171                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
4172                        this.buffers_being_formatted
4173                            .insert(buffer.read(cx).remote_id())
4174                    });
4175                })?;
4176
4177                let _cleanup = defer({
4178                    let this = project.clone();
4179                    let mut cx = cx.clone();
4180                    let buffers = &buffers_with_paths_and_servers;
4181                    move || {
4182                        this.update(&mut cx, |this, cx| {
4183                            for (buffer, _, _) in buffers {
4184                                this.buffers_being_formatted
4185                                    .remove(&buffer.read(cx).remote_id());
4186                            }
4187                        })
4188                        .ok();
4189                    }
4190                });
4191
4192                let mut project_transaction = ProjectTransaction::default();
4193                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
4194                    let settings = buffer.update(&mut cx, |buffer, cx| {
4195                        language_settings(buffer.language(), buffer.file(), cx).clone()
4196                    })?;
4197
4198                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4199                    let ensure_final_newline = settings.ensure_final_newline_on_save;
4200                    let tab_size = settings.tab_size;
4201
4202                    // First, format buffer's whitespace according to the settings.
4203                    let trailing_whitespace_diff = if remove_trailing_whitespace {
4204                        Some(
4205                            buffer
4206                                .update(&mut cx, |b, cx| b.remove_trailing_whitespace(cx))?
4207                                .await,
4208                        )
4209                    } else {
4210                        None
4211                    };
4212                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4213                        buffer.finalize_last_transaction();
4214                        buffer.start_transaction();
4215                        if let Some(diff) = trailing_whitespace_diff {
4216                            buffer.apply_diff(diff, cx);
4217                        }
4218                        if ensure_final_newline {
4219                            buffer.ensure_final_newline(cx);
4220                        }
4221                        buffer.end_transaction(cx)
4222                    })?;
4223
4224                    // Apply language-specific formatting using either a language server
4225                    // or external command.
4226                    let mut format_operation = None;
4227                    match (&settings.formatter, &settings.format_on_save) {
4228                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4229
4230                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4231                        | (_, FormatOnSave::LanguageServer) => {
4232                            if let Some((language_server, buffer_abs_path)) =
4233                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4234                            {
4235                                format_operation = Some(FormatOperation::Lsp(
4236                                    Self::format_via_lsp(
4237                                        &project,
4238                                        &buffer,
4239                                        buffer_abs_path,
4240                                        &language_server,
4241                                        tab_size,
4242                                        &mut cx,
4243                                    )
4244                                    .await
4245                                    .context("failed to format via language server")?,
4246                                ));
4247                            }
4248                        }
4249
4250                        (
4251                            Formatter::External { command, arguments },
4252                            FormatOnSave::On | FormatOnSave::Off,
4253                        )
4254                        | (_, FormatOnSave::External { command, arguments }) => {
4255                            if let Some(buffer_abs_path) = buffer_abs_path {
4256                                format_operation = Self::format_via_external_command(
4257                                    buffer,
4258                                    buffer_abs_path,
4259                                    &command,
4260                                    &arguments,
4261                                    &mut cx,
4262                                )
4263                                .await
4264                                .context(format!(
4265                                    "failed to format via external command {:?}",
4266                                    command
4267                                ))?
4268                                .map(FormatOperation::External);
4269                            }
4270                        }
4271                        (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4272                            if let Some(new_operation) =
4273                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4274                                    .await
4275                            {
4276                                format_operation = Some(new_operation);
4277                            } else if let Some((language_server, buffer_abs_path)) =
4278                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4279                            {
4280                                format_operation = Some(FormatOperation::Lsp(
4281                                    Self::format_via_lsp(
4282                                        &project,
4283                                        &buffer,
4284                                        buffer_abs_path,
4285                                        &language_server,
4286                                        tab_size,
4287                                        &mut cx,
4288                                    )
4289                                    .await
4290                                    .context("failed to format via language server")?,
4291                                ));
4292                            }
4293                        }
4294                        (Formatter::Prettier, FormatOnSave::On | FormatOnSave::Off) => {
4295                            if let Some(new_operation) =
4296                                prettier_support::format_with_prettier(&project, buffer, &mut cx)
4297                                    .await
4298                            {
4299                                format_operation = Some(new_operation);
4300                            }
4301                        }
4302                    };
4303
4304                    buffer.update(&mut cx, |b, cx| {
4305                        // If the buffer had its whitespace formatted and was edited while the language-specific
4306                        // formatting was being computed, avoid applying the language-specific formatting, because
4307                        // it can't be grouped with the whitespace formatting in the undo history.
4308                        if let Some(transaction_id) = whitespace_transaction_id {
4309                            if b.peek_undo_stack()
4310                                .map_or(true, |e| e.transaction_id() != transaction_id)
4311                            {
4312                                format_operation.take();
4313                            }
4314                        }
4315
4316                        // Apply any language-specific formatting, and group the two formatting operations
4317                        // in the buffer's undo history.
4318                        if let Some(operation) = format_operation {
4319                            match operation {
4320                                FormatOperation::Lsp(edits) => {
4321                                    b.edit(edits, None, cx);
4322                                }
4323                                FormatOperation::External(diff) => {
4324                                    b.apply_diff(diff, cx);
4325                                }
4326                                FormatOperation::Prettier(diff) => {
4327                                    b.apply_diff(diff, cx);
4328                                }
4329                            }
4330
4331                            if let Some(transaction_id) = whitespace_transaction_id {
4332                                b.group_until_transaction(transaction_id);
4333                            }
4334                        }
4335
4336                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4337                            if !push_to_history {
4338                                b.forget_transaction(transaction.id);
4339                            }
4340                            project_transaction.0.insert(buffer.clone(), transaction);
4341                        }
4342                    })?;
4343                }
4344
4345                Ok(project_transaction)
4346            })
4347        } else {
4348            let remote_id = self.remote_id();
4349            let client = self.client.clone();
4350            cx.spawn(move |this, mut cx| async move {
4351                let mut project_transaction = ProjectTransaction::default();
4352                if let Some(project_id) = remote_id {
4353                    let response = client
4354                        .request(proto::FormatBuffers {
4355                            project_id,
4356                            trigger: trigger as i32,
4357                            buffer_ids: buffers
4358                                .iter()
4359                                .map(|buffer| {
4360                                    buffer.update(&mut cx, |buffer, _| buffer.remote_id())
4361                                })
4362                                .collect::<Result<_>>()?,
4363                        })
4364                        .await?
4365                        .transaction
4366                        .ok_or_else(|| anyhow!("missing transaction"))?;
4367                    project_transaction = this
4368                        .update(&mut cx, |this, cx| {
4369                            this.deserialize_project_transaction(response, push_to_history, cx)
4370                        })?
4371                        .await?;
4372                }
4373                Ok(project_transaction)
4374            })
4375        }
4376    }
4377
4378    async fn format_via_lsp(
4379        this: &WeakModel<Self>,
4380        buffer: &Model<Buffer>,
4381        abs_path: &Path,
4382        language_server: &Arc<LanguageServer>,
4383        tab_size: NonZeroU32,
4384        cx: &mut AsyncAppContext,
4385    ) -> Result<Vec<(Range<Anchor>, String)>> {
4386        let uri = lsp::Url::from_file_path(abs_path)
4387            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4388        let text_document = lsp::TextDocumentIdentifier::new(uri);
4389        let capabilities = &language_server.capabilities();
4390
4391        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4392        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4393
4394        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4395            language_server
4396                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4397                    text_document,
4398                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4399                    work_done_progress_params: Default::default(),
4400                })
4401                .await?
4402        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4403            let buffer_start = lsp::Position::new(0, 0);
4404            let buffer_end = buffer.update(cx, |b, _| point_to_lsp(b.max_point_utf16()))?;
4405
4406            language_server
4407                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4408                    text_document,
4409                    range: lsp::Range::new(buffer_start, buffer_end),
4410                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4411                    work_done_progress_params: Default::default(),
4412                })
4413                .await?
4414        } else {
4415            None
4416        };
4417
4418        if let Some(lsp_edits) = lsp_edits {
4419            this.update(cx, |this, cx| {
4420                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4421            })?
4422            .await
4423        } else {
4424            Ok(Vec::new())
4425        }
4426    }
4427
4428    async fn format_via_external_command(
4429        buffer: &Model<Buffer>,
4430        buffer_abs_path: &Path,
4431        command: &str,
4432        arguments: &[String],
4433        cx: &mut AsyncAppContext,
4434    ) -> Result<Option<Diff>> {
4435        let working_dir_path = buffer.update(cx, |buffer, cx| {
4436            let file = File::from_dyn(buffer.file())?;
4437            let worktree = file.worktree.read(cx).as_local()?;
4438            let mut worktree_path = worktree.abs_path().to_path_buf();
4439            if worktree.root_entry()?.is_file() {
4440                worktree_path.pop();
4441            }
4442            Some(worktree_path)
4443        })?;
4444
4445        if let Some(working_dir_path) = working_dir_path {
4446            let mut child =
4447                smol::process::Command::new(command)
4448                    .args(arguments.iter().map(|arg| {
4449                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4450                    }))
4451                    .current_dir(&working_dir_path)
4452                    .stdin(smol::process::Stdio::piped())
4453                    .stdout(smol::process::Stdio::piped())
4454                    .stderr(smol::process::Stdio::piped())
4455                    .spawn()?;
4456            let stdin = child
4457                .stdin
4458                .as_mut()
4459                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4460            let text = buffer.update(cx, |buffer, _| buffer.as_rope().clone())?;
4461            for chunk in text.chunks() {
4462                stdin.write_all(chunk.as_bytes()).await?;
4463            }
4464            stdin.flush().await?;
4465
4466            let output = child.output().await?;
4467            if !output.status.success() {
4468                return Err(anyhow!(
4469                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4470                    output.status.code(),
4471                    String::from_utf8_lossy(&output.stdout),
4472                    String::from_utf8_lossy(&output.stderr),
4473                ));
4474            }
4475
4476            let stdout = String::from_utf8(output.stdout)?;
4477            Ok(Some(
4478                buffer
4479                    .update(cx, |buffer, cx| buffer.diff(stdout, cx))?
4480                    .await,
4481            ))
4482        } else {
4483            Ok(None)
4484        }
4485    }
4486
4487    pub fn definition<T: ToPointUtf16>(
4488        &self,
4489        buffer: &Model<Buffer>,
4490        position: T,
4491        cx: &mut ModelContext<Self>,
4492    ) -> Task<Result<Vec<LocationLink>>> {
4493        let position = position.to_point_utf16(buffer.read(cx));
4494        self.request_lsp(
4495            buffer.clone(),
4496            LanguageServerToQuery::Primary,
4497            GetDefinition { position },
4498            cx,
4499        )
4500    }
4501
4502    pub fn type_definition<T: ToPointUtf16>(
4503        &self,
4504        buffer: &Model<Buffer>,
4505        position: T,
4506        cx: &mut ModelContext<Self>,
4507    ) -> Task<Result<Vec<LocationLink>>> {
4508        let position = position.to_point_utf16(buffer.read(cx));
4509        self.request_lsp(
4510            buffer.clone(),
4511            LanguageServerToQuery::Primary,
4512            GetTypeDefinition { position },
4513            cx,
4514        )
4515    }
4516
4517    pub fn references<T: ToPointUtf16>(
4518        &self,
4519        buffer: &Model<Buffer>,
4520        position: T,
4521        cx: &mut ModelContext<Self>,
4522    ) -> Task<Result<Vec<Location>>> {
4523        let position = position.to_point_utf16(buffer.read(cx));
4524        self.request_lsp(
4525            buffer.clone(),
4526            LanguageServerToQuery::Primary,
4527            GetReferences { position },
4528            cx,
4529        )
4530    }
4531
4532    pub fn document_highlights<T: ToPointUtf16>(
4533        &self,
4534        buffer: &Model<Buffer>,
4535        position: T,
4536        cx: &mut ModelContext<Self>,
4537    ) -> Task<Result<Vec<DocumentHighlight>>> {
4538        let position = position.to_point_utf16(buffer.read(cx));
4539        self.request_lsp(
4540            buffer.clone(),
4541            LanguageServerToQuery::Primary,
4542            GetDocumentHighlights { position },
4543            cx,
4544        )
4545    }
4546
4547    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4548        if self.is_local() {
4549            let mut requests = Vec::new();
4550            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4551                let worktree_id = *worktree_id;
4552                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4553                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4554                    Some(worktree) => worktree,
4555                    None => continue,
4556                };
4557                let worktree_abs_path = worktree.abs_path().clone();
4558
4559                let (adapter, language, server) = match self.language_servers.get(server_id) {
4560                    Some(LanguageServerState::Running {
4561                        adapter,
4562                        language,
4563                        server,
4564                        ..
4565                    }) => (adapter.clone(), language.clone(), server),
4566
4567                    _ => continue,
4568                };
4569
4570                requests.push(
4571                    server
4572                        .request::<lsp::request::WorkspaceSymbolRequest>(
4573                            lsp::WorkspaceSymbolParams {
4574                                query: query.to_string(),
4575                                ..Default::default()
4576                            },
4577                        )
4578                        .log_err()
4579                        .map(move |response| {
4580                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4581                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4582                                    flat_responses.into_iter().map(|lsp_symbol| {
4583                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4584                                    }).collect::<Vec<_>>()
4585                                }
4586                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4587                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4588                                        let location = match lsp_symbol.location {
4589                                            OneOf::Left(location) => location,
4590                                            OneOf::Right(_) => {
4591                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4592                                                return None
4593                                            }
4594                                        };
4595                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4596                                    }).collect::<Vec<_>>()
4597                                }
4598                            }).unwrap_or_default();
4599
4600                            (
4601                                adapter,
4602                                language,
4603                                worktree_id,
4604                                worktree_abs_path,
4605                                lsp_symbols,
4606                            )
4607                        }),
4608                );
4609            }
4610
4611            cx.spawn(move |this, mut cx| async move {
4612                let responses = futures::future::join_all(requests).await;
4613                let this = match this.upgrade() {
4614                    Some(this) => this,
4615                    None => return Ok(Vec::new()),
4616                };
4617
4618                let symbols = this.update(&mut cx, |this, cx| {
4619                    let mut symbols = Vec::new();
4620                    for (
4621                        adapter,
4622                        adapter_language,
4623                        source_worktree_id,
4624                        worktree_abs_path,
4625                        lsp_symbols,
4626                    ) in responses
4627                    {
4628                        symbols.extend(lsp_symbols.into_iter().filter_map(
4629                            |(symbol_name, symbol_kind, symbol_location)| {
4630                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4631                                let mut worktree_id = source_worktree_id;
4632                                let path;
4633                                if let Some((worktree, rel_path)) =
4634                                    this.find_local_worktree(&abs_path, cx)
4635                                {
4636                                    worktree_id = worktree.read(cx).id();
4637                                    path = rel_path;
4638                                } else {
4639                                    path = relativize_path(&worktree_abs_path, &abs_path);
4640                                }
4641
4642                                let project_path = ProjectPath {
4643                                    worktree_id,
4644                                    path: path.into(),
4645                                };
4646                                let signature = this.symbol_signature(&project_path);
4647                                let adapter_language = adapter_language.clone();
4648                                let language = this
4649                                    .languages
4650                                    .language_for_file(&project_path.path, None)
4651                                    .unwrap_or_else(move |_| adapter_language);
4652                                let language_server_name = adapter.name.clone();
4653                                Some(async move {
4654                                    let language = language.await;
4655                                    let label =
4656                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4657
4658                                    Symbol {
4659                                        language_server_name,
4660                                        source_worktree_id,
4661                                        path: project_path,
4662                                        label: label.unwrap_or_else(|| {
4663                                            CodeLabel::plain(symbol_name.clone(), None)
4664                                        }),
4665                                        kind: symbol_kind,
4666                                        name: symbol_name,
4667                                        range: range_from_lsp(symbol_location.range),
4668                                        signature,
4669                                    }
4670                                })
4671                            },
4672                        ));
4673                    }
4674
4675                    symbols
4676                })?;
4677
4678                Ok(futures::future::join_all(symbols).await)
4679            })
4680        } else if let Some(project_id) = self.remote_id() {
4681            let request = self.client.request(proto::GetProjectSymbols {
4682                project_id,
4683                query: query.to_string(),
4684            });
4685            cx.spawn(move |this, mut cx| async move {
4686                let response = request.await?;
4687                let mut symbols = Vec::new();
4688                if let Some(this) = this.upgrade() {
4689                    let new_symbols = this.update(&mut cx, |this, _| {
4690                        response
4691                            .symbols
4692                            .into_iter()
4693                            .map(|symbol| this.deserialize_symbol(symbol))
4694                            .collect::<Vec<_>>()
4695                    })?;
4696                    symbols = futures::future::join_all(new_symbols)
4697                        .await
4698                        .into_iter()
4699                        .filter_map(|symbol| symbol.log_err())
4700                        .collect::<Vec<_>>();
4701                }
4702                Ok(symbols)
4703            })
4704        } else {
4705            Task::ready(Ok(Default::default()))
4706        }
4707    }
4708
4709    pub fn open_buffer_for_symbol(
4710        &mut self,
4711        symbol: &Symbol,
4712        cx: &mut ModelContext<Self>,
4713    ) -> Task<Result<Model<Buffer>>> {
4714        if self.is_local() {
4715            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4716                symbol.source_worktree_id,
4717                symbol.language_server_name.clone(),
4718            )) {
4719                *id
4720            } else {
4721                return Task::ready(Err(anyhow!(
4722                    "language server for worktree and language not found"
4723                )));
4724            };
4725
4726            let worktree_abs_path = if let Some(worktree_abs_path) = self
4727                .worktree_for_id(symbol.path.worktree_id, cx)
4728                .and_then(|worktree| worktree.read(cx).as_local())
4729                .map(|local_worktree| local_worktree.abs_path())
4730            {
4731                worktree_abs_path
4732            } else {
4733                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4734            };
4735
4736            let symbol_abs_path = resolve_path(worktree_abs_path, &symbol.path.path);
4737            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4738                uri
4739            } else {
4740                return Task::ready(Err(anyhow!("invalid symbol path")));
4741            };
4742
4743            self.open_local_buffer_via_lsp(
4744                symbol_uri,
4745                language_server_id,
4746                symbol.language_server_name.clone(),
4747                cx,
4748            )
4749        } else if let Some(project_id) = self.remote_id() {
4750            let request = self.client.request(proto::OpenBufferForSymbol {
4751                project_id,
4752                symbol: Some(serialize_symbol(symbol)),
4753            });
4754            cx.spawn(move |this, mut cx| async move {
4755                let response = request.await?;
4756                this.update(&mut cx, |this, cx| {
4757                    this.wait_for_remote_buffer(response.buffer_id, cx)
4758                })?
4759                .await
4760            })
4761        } else {
4762            Task::ready(Err(anyhow!("project does not have a remote id")))
4763        }
4764    }
4765
4766    pub fn hover<T: ToPointUtf16>(
4767        &self,
4768        buffer: &Model<Buffer>,
4769        position: T,
4770        cx: &mut ModelContext<Self>,
4771    ) -> Task<Result<Option<Hover>>> {
4772        let position = position.to_point_utf16(buffer.read(cx));
4773        self.request_lsp(
4774            buffer.clone(),
4775            LanguageServerToQuery::Primary,
4776            GetHover { position },
4777            cx,
4778        )
4779    }
4780
4781    pub fn completions<T: ToOffset + ToPointUtf16>(
4782        &self,
4783        buffer: &Model<Buffer>,
4784        position: T,
4785        cx: &mut ModelContext<Self>,
4786    ) -> Task<Result<Vec<Completion>>> {
4787        let position = position.to_point_utf16(buffer.read(cx));
4788        if self.is_local() {
4789            let snapshot = buffer.read(cx).snapshot();
4790            let offset = position.to_offset(&snapshot);
4791            let scope = snapshot.language_scope_at(offset);
4792
4793            let server_ids: Vec<_> = self
4794                .language_servers_for_buffer(buffer.read(cx), cx)
4795                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4796                .filter(|(adapter, _)| {
4797                    scope
4798                        .as_ref()
4799                        .map(|scope| scope.language_allowed(&adapter.name))
4800                        .unwrap_or(true)
4801                })
4802                .map(|(_, server)| server.server_id())
4803                .collect();
4804
4805            let buffer = buffer.clone();
4806            cx.spawn(move |this, mut cx| async move {
4807                let mut tasks = Vec::with_capacity(server_ids.len());
4808                this.update(&mut cx, |this, cx| {
4809                    for server_id in server_ids {
4810                        tasks.push(this.request_lsp(
4811                            buffer.clone(),
4812                            LanguageServerToQuery::Other(server_id),
4813                            GetCompletions { position },
4814                            cx,
4815                        ));
4816                    }
4817                })?;
4818
4819                let mut completions = Vec::new();
4820                for task in tasks {
4821                    if let Ok(new_completions) = task.await {
4822                        completions.extend_from_slice(&new_completions);
4823                    }
4824                }
4825
4826                Ok(completions)
4827            })
4828        } else if let Some(project_id) = self.remote_id() {
4829            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4830        } else {
4831            Task::ready(Ok(Default::default()))
4832        }
4833    }
4834
4835    pub fn apply_additional_edits_for_completion(
4836        &self,
4837        buffer_handle: Model<Buffer>,
4838        completion: Completion,
4839        push_to_history: bool,
4840        cx: &mut ModelContext<Self>,
4841    ) -> Task<Result<Option<Transaction>>> {
4842        let buffer = buffer_handle.read(cx);
4843        let buffer_id = buffer.remote_id();
4844
4845        if self.is_local() {
4846            let server_id = completion.server_id;
4847            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4848                Some((_, server)) => server.clone(),
4849                _ => return Task::ready(Ok(Default::default())),
4850            };
4851
4852            cx.spawn(move |this, mut cx| async move {
4853                let can_resolve = lang_server
4854                    .capabilities()
4855                    .completion_provider
4856                    .as_ref()
4857                    .and_then(|options| options.resolve_provider)
4858                    .unwrap_or(false);
4859                let additional_text_edits = if can_resolve {
4860                    lang_server
4861                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4862                        .await?
4863                        .additional_text_edits
4864                } else {
4865                    completion.lsp_completion.additional_text_edits
4866                };
4867                if let Some(edits) = additional_text_edits {
4868                    let edits = this
4869                        .update(&mut cx, |this, cx| {
4870                            this.edits_from_lsp(
4871                                &buffer_handle,
4872                                edits,
4873                                lang_server.server_id(),
4874                                None,
4875                                cx,
4876                            )
4877                        })?
4878                        .await?;
4879
4880                    buffer_handle.update(&mut cx, |buffer, cx| {
4881                        buffer.finalize_last_transaction();
4882                        buffer.start_transaction();
4883
4884                        for (range, text) in edits {
4885                            let primary = &completion.old_range;
4886                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4887                                && primary.end.cmp(&range.start, buffer).is_ge();
4888                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4889                                && range.end.cmp(&primary.end, buffer).is_ge();
4890
4891                            //Skip additional edits which overlap with the primary completion edit
4892                            //https://github.com/zed-industries/zed/pull/1871
4893                            if !start_within && !end_within {
4894                                buffer.edit([(range, text)], None, cx);
4895                            }
4896                        }
4897
4898                        let transaction = if buffer.end_transaction(cx).is_some() {
4899                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4900                            if !push_to_history {
4901                                buffer.forget_transaction(transaction.id);
4902                            }
4903                            Some(transaction)
4904                        } else {
4905                            None
4906                        };
4907                        Ok(transaction)
4908                    })?
4909                } else {
4910                    Ok(None)
4911                }
4912            })
4913        } else if let Some(project_id) = self.remote_id() {
4914            let client = self.client.clone();
4915            cx.spawn(move |_, mut cx| async move {
4916                let response = client
4917                    .request(proto::ApplyCompletionAdditionalEdits {
4918                        project_id,
4919                        buffer_id,
4920                        completion: Some(language::proto::serialize_completion(&completion)),
4921                    })
4922                    .await?;
4923
4924                if let Some(transaction) = response.transaction {
4925                    let transaction = language::proto::deserialize_transaction(transaction)?;
4926                    buffer_handle
4927                        .update(&mut cx, |buffer, _| {
4928                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4929                        })?
4930                        .await?;
4931                    if push_to_history {
4932                        buffer_handle.update(&mut cx, |buffer, _| {
4933                            buffer.push_transaction(transaction.clone(), Instant::now());
4934                        })?;
4935                    }
4936                    Ok(Some(transaction))
4937                } else {
4938                    Ok(None)
4939                }
4940            })
4941        } else {
4942            Task::ready(Err(anyhow!("project does not have a remote id")))
4943        }
4944    }
4945
4946    pub fn code_actions<T: Clone + ToOffset>(
4947        &self,
4948        buffer_handle: &Model<Buffer>,
4949        range: Range<T>,
4950        cx: &mut ModelContext<Self>,
4951    ) -> Task<Result<Vec<CodeAction>>> {
4952        let buffer = buffer_handle.read(cx);
4953        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4954        self.request_lsp(
4955            buffer_handle.clone(),
4956            LanguageServerToQuery::Primary,
4957            GetCodeActions { range },
4958            cx,
4959        )
4960    }
4961
4962    pub fn apply_code_action(
4963        &self,
4964        buffer_handle: Model<Buffer>,
4965        mut action: CodeAction,
4966        push_to_history: bool,
4967        cx: &mut ModelContext<Self>,
4968    ) -> Task<Result<ProjectTransaction>> {
4969        if self.is_local() {
4970            let buffer = buffer_handle.read(cx);
4971            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4972                self.language_server_for_buffer(buffer, action.server_id, cx)
4973            {
4974                (adapter.clone(), server.clone())
4975            } else {
4976                return Task::ready(Ok(Default::default()));
4977            };
4978            let range = action.range.to_point_utf16(buffer);
4979
4980            cx.spawn(move |this, mut cx| async move {
4981                if let Some(lsp_range) = action
4982                    .lsp_action
4983                    .data
4984                    .as_mut()
4985                    .and_then(|d| d.get_mut("codeActionParams"))
4986                    .and_then(|d| d.get_mut("range"))
4987                {
4988                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4989                    action.lsp_action = lang_server
4990                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4991                        .await?;
4992                } else {
4993                    let actions = this
4994                        .update(&mut cx, |this, cx| {
4995                            this.code_actions(&buffer_handle, action.range, cx)
4996                        })?
4997                        .await?;
4998                    action.lsp_action = actions
4999                        .into_iter()
5000                        .find(|a| a.lsp_action.title == action.lsp_action.title)
5001                        .ok_or_else(|| anyhow!("code action is outdated"))?
5002                        .lsp_action;
5003                }
5004
5005                if let Some(edit) = action.lsp_action.edit {
5006                    if edit.changes.is_some() || edit.document_changes.is_some() {
5007                        return Self::deserialize_workspace_edit(
5008                            this.upgrade().ok_or_else(|| anyhow!("no app present"))?,
5009                            edit,
5010                            push_to_history,
5011                            lsp_adapter.clone(),
5012                            lang_server.clone(),
5013                            &mut cx,
5014                        )
5015                        .await;
5016                    }
5017                }
5018
5019                if let Some(command) = action.lsp_action.command {
5020                    this.update(&mut cx, |this, _| {
5021                        this.last_workspace_edits_by_language_server
5022                            .remove(&lang_server.server_id());
5023                    })?;
5024
5025                    let result = lang_server
5026                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
5027                            command: command.command,
5028                            arguments: command.arguments.unwrap_or_default(),
5029                            ..Default::default()
5030                        })
5031                        .await;
5032
5033                    if let Err(err) = result {
5034                        // TODO: LSP ERROR
5035                        return Err(err);
5036                    }
5037
5038                    return Ok(this.update(&mut cx, |this, _| {
5039                        this.last_workspace_edits_by_language_server
5040                            .remove(&lang_server.server_id())
5041                            .unwrap_or_default()
5042                    })?);
5043                }
5044
5045                Ok(ProjectTransaction::default())
5046            })
5047        } else if let Some(project_id) = self.remote_id() {
5048            let client = self.client.clone();
5049            let request = proto::ApplyCodeAction {
5050                project_id,
5051                buffer_id: buffer_handle.read(cx).remote_id(),
5052                action: Some(language::proto::serialize_code_action(&action)),
5053            };
5054            cx.spawn(move |this, mut cx| async move {
5055                let response = client
5056                    .request(request)
5057                    .await?
5058                    .transaction
5059                    .ok_or_else(|| anyhow!("missing transaction"))?;
5060                this.update(&mut cx, |this, cx| {
5061                    this.deserialize_project_transaction(response, push_to_history, cx)
5062                })?
5063                .await
5064            })
5065        } else {
5066            Task::ready(Err(anyhow!("project does not have a remote id")))
5067        }
5068    }
5069
5070    fn apply_on_type_formatting(
5071        &self,
5072        buffer: Model<Buffer>,
5073        position: Anchor,
5074        trigger: String,
5075        cx: &mut ModelContext<Self>,
5076    ) -> Task<Result<Option<Transaction>>> {
5077        if self.is_local() {
5078            cx.spawn(move |this, mut cx| async move {
5079                // Do not allow multiple concurrent formatting requests for the
5080                // same buffer.
5081                this.update(&mut cx, |this, cx| {
5082                    this.buffers_being_formatted
5083                        .insert(buffer.read(cx).remote_id())
5084                })?;
5085
5086                let _cleanup = defer({
5087                    let this = this.clone();
5088                    let mut cx = cx.clone();
5089                    let closure_buffer = buffer.clone();
5090                    move || {
5091                        this.update(&mut cx, |this, cx| {
5092                            this.buffers_being_formatted
5093                                .remove(&closure_buffer.read(cx).remote_id());
5094                        })
5095                        .ok();
5096                    }
5097                });
5098
5099                buffer
5100                    .update(&mut cx, |buffer, _| {
5101                        buffer.wait_for_edits(Some(position.timestamp))
5102                    })?
5103                    .await?;
5104                this.update(&mut cx, |this, cx| {
5105                    let position = position.to_point_utf16(buffer.read(cx));
5106                    this.on_type_format(buffer, position, trigger, false, cx)
5107                })?
5108                .await
5109            })
5110        } else if let Some(project_id) = self.remote_id() {
5111            let client = self.client.clone();
5112            let request = proto::OnTypeFormatting {
5113                project_id,
5114                buffer_id: buffer.read(cx).remote_id(),
5115                position: Some(serialize_anchor(&position)),
5116                trigger,
5117                version: serialize_version(&buffer.read(cx).version()),
5118            };
5119            cx.spawn(move |_, _| async move {
5120                client
5121                    .request(request)
5122                    .await?
5123                    .transaction
5124                    .map(language::proto::deserialize_transaction)
5125                    .transpose()
5126            })
5127        } else {
5128            Task::ready(Err(anyhow!("project does not have a remote id")))
5129        }
5130    }
5131
5132    async fn deserialize_edits(
5133        this: Model<Self>,
5134        buffer_to_edit: Model<Buffer>,
5135        edits: Vec<lsp::TextEdit>,
5136        push_to_history: bool,
5137        _: Arc<CachedLspAdapter>,
5138        language_server: Arc<LanguageServer>,
5139        cx: &mut AsyncAppContext,
5140    ) -> Result<Option<Transaction>> {
5141        let edits = this
5142            .update(cx, |this, cx| {
5143                this.edits_from_lsp(
5144                    &buffer_to_edit,
5145                    edits,
5146                    language_server.server_id(),
5147                    None,
5148                    cx,
5149                )
5150            })?
5151            .await?;
5152
5153        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5154            buffer.finalize_last_transaction();
5155            buffer.start_transaction();
5156            for (range, text) in edits {
5157                buffer.edit([(range, text)], None, cx);
5158            }
5159
5160            if buffer.end_transaction(cx).is_some() {
5161                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5162                if !push_to_history {
5163                    buffer.forget_transaction(transaction.id);
5164                }
5165                Some(transaction)
5166            } else {
5167                None
5168            }
5169        })?;
5170
5171        Ok(transaction)
5172    }
5173
5174    async fn deserialize_workspace_edit(
5175        this: Model<Self>,
5176        edit: lsp::WorkspaceEdit,
5177        push_to_history: bool,
5178        lsp_adapter: Arc<CachedLspAdapter>,
5179        language_server: Arc<LanguageServer>,
5180        cx: &mut AsyncAppContext,
5181    ) -> Result<ProjectTransaction> {
5182        let fs = this.update(cx, |this, _| this.fs.clone())?;
5183        let mut operations = Vec::new();
5184        if let Some(document_changes) = edit.document_changes {
5185            match document_changes {
5186                lsp::DocumentChanges::Edits(edits) => {
5187                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5188                }
5189                lsp::DocumentChanges::Operations(ops) => operations = ops,
5190            }
5191        } else if let Some(changes) = edit.changes {
5192            operations.extend(changes.into_iter().map(|(uri, edits)| {
5193                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5194                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5195                        uri,
5196                        version: None,
5197                    },
5198                    edits: edits.into_iter().map(OneOf::Left).collect(),
5199                })
5200            }));
5201        }
5202
5203        let mut project_transaction = ProjectTransaction::default();
5204        for operation in operations {
5205            match operation {
5206                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5207                    let abs_path = op
5208                        .uri
5209                        .to_file_path()
5210                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5211
5212                    if let Some(parent_path) = abs_path.parent() {
5213                        fs.create_dir(parent_path).await?;
5214                    }
5215                    if abs_path.ends_with("/") {
5216                        fs.create_dir(&abs_path).await?;
5217                    } else {
5218                        fs.create_file(
5219                            &abs_path,
5220                            op.options
5221                                .map(|options| fs::CreateOptions {
5222                                    overwrite: options.overwrite.unwrap_or(false),
5223                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5224                                })
5225                                .unwrap_or_default(),
5226                        )
5227                        .await?;
5228                    }
5229                }
5230
5231                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5232                    let source_abs_path = op
5233                        .old_uri
5234                        .to_file_path()
5235                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5236                    let target_abs_path = op
5237                        .new_uri
5238                        .to_file_path()
5239                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5240                    fs.rename(
5241                        &source_abs_path,
5242                        &target_abs_path,
5243                        op.options
5244                            .map(|options| fs::RenameOptions {
5245                                overwrite: options.overwrite.unwrap_or(false),
5246                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5247                            })
5248                            .unwrap_or_default(),
5249                    )
5250                    .await?;
5251                }
5252
5253                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5254                    let abs_path = op
5255                        .uri
5256                        .to_file_path()
5257                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5258                    let options = op
5259                        .options
5260                        .map(|options| fs::RemoveOptions {
5261                            recursive: options.recursive.unwrap_or(false),
5262                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5263                        })
5264                        .unwrap_or_default();
5265                    if abs_path.ends_with("/") {
5266                        fs.remove_dir(&abs_path, options).await?;
5267                    } else {
5268                        fs.remove_file(&abs_path, options).await?;
5269                    }
5270                }
5271
5272                lsp::DocumentChangeOperation::Edit(op) => {
5273                    let buffer_to_edit = this
5274                        .update(cx, |this, cx| {
5275                            this.open_local_buffer_via_lsp(
5276                                op.text_document.uri,
5277                                language_server.server_id(),
5278                                lsp_adapter.name.clone(),
5279                                cx,
5280                            )
5281                        })?
5282                        .await?;
5283
5284                    let edits = this
5285                        .update(cx, |this, cx| {
5286                            let edits = op.edits.into_iter().map(|edit| match edit {
5287                                OneOf::Left(edit) => edit,
5288                                OneOf::Right(edit) => edit.text_edit,
5289                            });
5290                            this.edits_from_lsp(
5291                                &buffer_to_edit,
5292                                edits,
5293                                language_server.server_id(),
5294                                op.text_document.version,
5295                                cx,
5296                            )
5297                        })?
5298                        .await?;
5299
5300                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5301                        buffer.finalize_last_transaction();
5302                        buffer.start_transaction();
5303                        for (range, text) in edits {
5304                            buffer.edit([(range, text)], None, cx);
5305                        }
5306                        let transaction = if buffer.end_transaction(cx).is_some() {
5307                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5308                            if !push_to_history {
5309                                buffer.forget_transaction(transaction.id);
5310                            }
5311                            Some(transaction)
5312                        } else {
5313                            None
5314                        };
5315
5316                        transaction
5317                    })?;
5318                    if let Some(transaction) = transaction {
5319                        project_transaction.0.insert(buffer_to_edit, transaction);
5320                    }
5321                }
5322            }
5323        }
5324
5325        Ok(project_transaction)
5326    }
5327
5328    pub fn prepare_rename<T: ToPointUtf16>(
5329        &self,
5330        buffer: Model<Buffer>,
5331        position: T,
5332        cx: &mut ModelContext<Self>,
5333    ) -> Task<Result<Option<Range<Anchor>>>> {
5334        let position = position.to_point_utf16(buffer.read(cx));
5335        self.request_lsp(
5336            buffer,
5337            LanguageServerToQuery::Primary,
5338            PrepareRename { position },
5339            cx,
5340        )
5341    }
5342
5343    pub fn perform_rename<T: ToPointUtf16>(
5344        &self,
5345        buffer: Model<Buffer>,
5346        position: T,
5347        new_name: String,
5348        push_to_history: bool,
5349        cx: &mut ModelContext<Self>,
5350    ) -> Task<Result<ProjectTransaction>> {
5351        let position = position.to_point_utf16(buffer.read(cx));
5352        self.request_lsp(
5353            buffer,
5354            LanguageServerToQuery::Primary,
5355            PerformRename {
5356                position,
5357                new_name,
5358                push_to_history,
5359            },
5360            cx,
5361        )
5362    }
5363
5364    pub fn on_type_format<T: ToPointUtf16>(
5365        &self,
5366        buffer: Model<Buffer>,
5367        position: T,
5368        trigger: String,
5369        push_to_history: bool,
5370        cx: &mut ModelContext<Self>,
5371    ) -> Task<Result<Option<Transaction>>> {
5372        let (position, tab_size) = buffer.update(cx, |buffer, cx| {
5373            let position = position.to_point_utf16(buffer);
5374            (
5375                position,
5376                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5377                    .tab_size,
5378            )
5379        });
5380        self.request_lsp(
5381            buffer.clone(),
5382            LanguageServerToQuery::Primary,
5383            OnTypeFormatting {
5384                position,
5385                trigger,
5386                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5387                push_to_history,
5388            },
5389            cx,
5390        )
5391    }
5392
5393    pub fn inlay_hints<T: ToOffset>(
5394        &self,
5395        buffer_handle: Model<Buffer>,
5396        range: Range<T>,
5397        cx: &mut ModelContext<Self>,
5398    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5399        let buffer = buffer_handle.read(cx);
5400        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5401        let range_start = range.start;
5402        let range_end = range.end;
5403        let buffer_id = buffer.remote_id();
5404        let buffer_version = buffer.version().clone();
5405        let lsp_request = InlayHints { range };
5406
5407        if self.is_local() {
5408            let lsp_request_task = self.request_lsp(
5409                buffer_handle.clone(),
5410                LanguageServerToQuery::Primary,
5411                lsp_request,
5412                cx,
5413            );
5414            cx.spawn(move |_, mut cx| async move {
5415                buffer_handle
5416                    .update(&mut cx, |buffer, _| {
5417                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5418                    })?
5419                    .await
5420                    .context("waiting for inlay hint request range edits")?;
5421                lsp_request_task.await.context("inlay hints LSP request")
5422            })
5423        } else if let Some(project_id) = self.remote_id() {
5424            let client = self.client.clone();
5425            let request = proto::InlayHints {
5426                project_id,
5427                buffer_id,
5428                start: Some(serialize_anchor(&range_start)),
5429                end: Some(serialize_anchor(&range_end)),
5430                version: serialize_version(&buffer_version),
5431            };
5432            cx.spawn(move |project, cx| async move {
5433                let response = client
5434                    .request(request)
5435                    .await
5436                    .context("inlay hints proto request")?;
5437                let hints_request_result = LspCommand::response_from_proto(
5438                    lsp_request,
5439                    response,
5440                    project.upgrade().ok_or_else(|| anyhow!("No project"))?,
5441                    buffer_handle.clone(),
5442                    cx,
5443                )
5444                .await;
5445
5446                hints_request_result.context("inlay hints proto response conversion")
5447            })
5448        } else {
5449            Task::ready(Err(anyhow!("project does not have a remote id")))
5450        }
5451    }
5452
5453    pub fn resolve_inlay_hint(
5454        &self,
5455        hint: InlayHint,
5456        buffer_handle: Model<Buffer>,
5457        server_id: LanguageServerId,
5458        cx: &mut ModelContext<Self>,
5459    ) -> Task<anyhow::Result<InlayHint>> {
5460        if self.is_local() {
5461            let buffer = buffer_handle.read(cx);
5462            let (_, lang_server) = if let Some((adapter, server)) =
5463                self.language_server_for_buffer(buffer, server_id, cx)
5464            {
5465                (adapter.clone(), server.clone())
5466            } else {
5467                return Task::ready(Ok(hint));
5468            };
5469            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5470                return Task::ready(Ok(hint));
5471            }
5472
5473            let buffer_snapshot = buffer.snapshot();
5474            cx.spawn(move |_, mut cx| async move {
5475                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5476                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5477                );
5478                let resolved_hint = resolve_task
5479                    .await
5480                    .context("inlay hint resolve LSP request")?;
5481                let resolved_hint = InlayHints::lsp_to_project_hint(
5482                    resolved_hint,
5483                    &buffer_handle,
5484                    server_id,
5485                    ResolveState::Resolved,
5486                    false,
5487                    &mut cx,
5488                )
5489                .await?;
5490                Ok(resolved_hint)
5491            })
5492        } else if let Some(project_id) = self.remote_id() {
5493            let client = self.client.clone();
5494            let request = proto::ResolveInlayHint {
5495                project_id,
5496                buffer_id: buffer_handle.read(cx).remote_id(),
5497                language_server_id: server_id.0 as u64,
5498                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5499            };
5500            cx.spawn(move |_, _| async move {
5501                let response = client
5502                    .request(request)
5503                    .await
5504                    .context("inlay hints proto request")?;
5505                match response.hint {
5506                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5507                        .context("inlay hints proto resolve response conversion"),
5508                    None => Ok(hint),
5509                }
5510            })
5511        } else {
5512            Task::ready(Err(anyhow!("project does not have a remote id")))
5513        }
5514    }
5515
5516    #[allow(clippy::type_complexity)]
5517    pub fn search(
5518        &self,
5519        query: SearchQuery,
5520        cx: &mut ModelContext<Self>,
5521    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5522        if self.is_local() {
5523            self.search_local(query, cx)
5524        } else if let Some(project_id) = self.remote_id() {
5525            let (tx, rx) = smol::channel::unbounded();
5526            let request = self.client.request(query.to_proto(project_id));
5527            cx.spawn(move |this, mut cx| async move {
5528                let response = request.await?;
5529                let mut result = HashMap::default();
5530                for location in response.locations {
5531                    let target_buffer = this
5532                        .update(&mut cx, |this, cx| {
5533                            this.wait_for_remote_buffer(location.buffer_id, cx)
5534                        })?
5535                        .await?;
5536                    let start = location
5537                        .start
5538                        .and_then(deserialize_anchor)
5539                        .ok_or_else(|| anyhow!("missing target start"))?;
5540                    let end = location
5541                        .end
5542                        .and_then(deserialize_anchor)
5543                        .ok_or_else(|| anyhow!("missing target end"))?;
5544                    result
5545                        .entry(target_buffer)
5546                        .or_insert(Vec::new())
5547                        .push(start..end)
5548                }
5549                for (buffer, ranges) in result {
5550                    let _ = tx.send((buffer, ranges)).await;
5551                }
5552                Result::<(), anyhow::Error>::Ok(())
5553            })
5554            .detach_and_log_err(cx);
5555            rx
5556        } else {
5557            unimplemented!();
5558        }
5559    }
5560
5561    pub fn search_local(
5562        &self,
5563        query: SearchQuery,
5564        cx: &mut ModelContext<Self>,
5565    ) -> Receiver<(Model<Buffer>, Vec<Range<Anchor>>)> {
5566        // Local search is split into several phases.
5567        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5568        // and the second phase that finds positions of all the matches found in the candidate files.
5569        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5570        //
5571        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5572        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5573        //
5574        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5575        //    Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
5576        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5577        // 2. At this point, we have a list of all potentially matching buffers/files.
5578        //    We sort that list by buffer path - this list is retained for later use.
5579        //    We ensure that all buffers are now opened and available in project.
5580        // 3. We run a scan over all the candidate buffers on multiple background threads.
5581        //    We cannot assume that there will even be a match - while at least one match
5582        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5583        //    There is also an auxilliary background thread responsible for result gathering.
5584        //    This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
5585        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5586        //    As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
5587        //    entry - which might already be available thanks to out-of-order processing.
5588        //
5589        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5590        // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
5591        // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
5592        // in face of constantly updating list of sorted matches.
5593        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5594        let snapshots = self
5595            .visible_worktrees(cx)
5596            .filter_map(|tree| {
5597                let tree = tree.read(cx).as_local()?;
5598                Some(tree.snapshot())
5599            })
5600            .collect::<Vec<_>>();
5601
5602        let background = cx.background_executor().clone();
5603        let path_count: usize = snapshots
5604            .iter()
5605            .map(|s| {
5606                if query.include_ignored() {
5607                    s.file_count()
5608                } else {
5609                    s.visible_file_count()
5610                }
5611            })
5612            .sum();
5613        if path_count == 0 {
5614            let (_, rx) = smol::channel::bounded(1024);
5615            return rx;
5616        }
5617        let workers = background.num_cpus().min(path_count);
5618        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5619        let mut unnamed_files = vec![];
5620        let opened_buffers = self
5621            .opened_buffers
5622            .iter()
5623            .filter_map(|(_, b)| {
5624                let buffer = b.upgrade()?;
5625                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
5626                    let is_ignored = buffer
5627                        .project_path(cx)
5628                        .and_then(|path| self.entry_for_path(&path, cx))
5629                        .map_or(false, |entry| entry.is_ignored);
5630                    (is_ignored, buffer.snapshot())
5631                });
5632                if is_ignored && !query.include_ignored() {
5633                    return None;
5634                } else if let Some(path) = snapshot.file().map(|file| file.path()) {
5635                    Some((path.clone(), (buffer, snapshot)))
5636                } else {
5637                    unnamed_files.push(buffer);
5638                    None
5639                }
5640            })
5641            .collect();
5642        cx.background_executor()
5643            .spawn(Self::background_search(
5644                unnamed_files,
5645                opened_buffers,
5646                cx.background_executor().clone(),
5647                self.fs.clone(),
5648                workers,
5649                query.clone(),
5650                path_count,
5651                snapshots,
5652                matching_paths_tx,
5653            ))
5654            .detach();
5655
5656        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5657        let background = cx.background_executor().clone();
5658        let (result_tx, result_rx) = smol::channel::bounded(1024);
5659        cx.background_executor()
5660            .spawn(async move {
5661                let Ok(buffers) = buffers.await else {
5662                    return;
5663                };
5664
5665                let buffers_len = buffers.len();
5666                if buffers_len == 0 {
5667                    return;
5668                }
5669                let query = &query;
5670                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5671                background
5672                    .scoped(|scope| {
5673                        #[derive(Clone)]
5674                        struct FinishedStatus {
5675                            entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
5676                            buffer_index: SearchMatchCandidateIndex,
5677                        }
5678
5679                        for _ in 0..workers {
5680                            let finished_tx = finished_tx.clone();
5681                            let mut buffers_rx = buffers_rx.clone();
5682                            scope.spawn(async move {
5683                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5684                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5685                                    {
5686                                        if query.file_matches(
5687                                            snapshot.file().map(|file| file.path().as_ref()),
5688                                        ) {
5689                                            query
5690                                                .search(&snapshot, None)
5691                                                .await
5692                                                .iter()
5693                                                .map(|range| {
5694                                                    snapshot.anchor_before(range.start)
5695                                                        ..snapshot.anchor_after(range.end)
5696                                                })
5697                                                .collect()
5698                                        } else {
5699                                            Vec::new()
5700                                        }
5701                                    } else {
5702                                        Vec::new()
5703                                    };
5704
5705                                    let status = if !buffer_matches.is_empty() {
5706                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5707                                            Some((buffer.clone(), buffer_matches))
5708                                        } else {
5709                                            None
5710                                        };
5711                                        FinishedStatus {
5712                                            entry,
5713                                            buffer_index,
5714                                        }
5715                                    } else {
5716                                        FinishedStatus {
5717                                            entry: None,
5718                                            buffer_index,
5719                                        }
5720                                    };
5721                                    if finished_tx.send(status).await.is_err() {
5722                                        break;
5723                                    }
5724                                }
5725                            });
5726                        }
5727                        // Report sorted matches
5728                        scope.spawn(async move {
5729                            let mut current_index = 0;
5730                            let mut scratch = vec![None; buffers_len];
5731                            while let Some(status) = finished_rx.next().await {
5732                                debug_assert!(
5733                                    scratch[status.buffer_index].is_none(),
5734                                    "Got match status of position {} twice",
5735                                    status.buffer_index
5736                                );
5737                                let index = status.buffer_index;
5738                                scratch[index] = Some(status);
5739                                while current_index < buffers_len {
5740                                    let Some(current_entry) = scratch[current_index].take() else {
5741                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5742                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5743                                        // this time.
5744                                        break;
5745                                    };
5746                                    if let Some(entry) = current_entry.entry {
5747                                        result_tx.send(entry).await.log_err();
5748                                    }
5749                                    current_index += 1;
5750                                }
5751                                if current_index == buffers_len {
5752                                    break;
5753                                }
5754                            }
5755                        });
5756                    })
5757                    .await;
5758            })
5759            .detach();
5760        result_rx
5761    }
5762
5763    /// Pick paths that might potentially contain a match of a given search query.
5764    async fn background_search(
5765        unnamed_buffers: Vec<Model<Buffer>>,
5766        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
5767        executor: BackgroundExecutor,
5768        fs: Arc<dyn Fs>,
5769        workers: usize,
5770        query: SearchQuery,
5771        path_count: usize,
5772        snapshots: Vec<LocalSnapshot>,
5773        matching_paths_tx: Sender<SearchMatchCandidate>,
5774    ) {
5775        let fs = &fs;
5776        let query = &query;
5777        let matching_paths_tx = &matching_paths_tx;
5778        let snapshots = &snapshots;
5779        let paths_per_worker = (path_count + workers - 1) / workers;
5780        for buffer in unnamed_buffers {
5781            matching_paths_tx
5782                .send(SearchMatchCandidate::OpenBuffer {
5783                    buffer: buffer.clone(),
5784                    path: None,
5785                })
5786                .await
5787                .log_err();
5788        }
5789        for (path, (buffer, _)) in opened_buffers.iter() {
5790            matching_paths_tx
5791                .send(SearchMatchCandidate::OpenBuffer {
5792                    buffer: buffer.clone(),
5793                    path: Some(path.clone()),
5794                })
5795                .await
5796                .log_err();
5797        }
5798        executor
5799            .scoped(|scope| {
5800                let max_concurrent_workers = Arc::new(Semaphore::new(workers));
5801
5802                for worker_ix in 0..workers {
5803                    let worker_start_ix = worker_ix * paths_per_worker;
5804                    let worker_end_ix = worker_start_ix + paths_per_worker;
5805                    let unnamed_buffers = opened_buffers.clone();
5806                    let limiter = Arc::clone(&max_concurrent_workers);
5807                    scope.spawn(async move {
5808                        let _guard = limiter.acquire().await;
5809                        let mut snapshot_start_ix = 0;
5810                        let mut abs_path = PathBuf::new();
5811                        for snapshot in snapshots {
5812                            let snapshot_end_ix = snapshot_start_ix
5813                                + if query.include_ignored() {
5814                                    snapshot.file_count()
5815                                } else {
5816                                    snapshot.visible_file_count()
5817                                };
5818                            if worker_end_ix <= snapshot_start_ix {
5819                                break;
5820                            } else if worker_start_ix > snapshot_end_ix {
5821                                snapshot_start_ix = snapshot_end_ix;
5822                                continue;
5823                            } else {
5824                                let start_in_snapshot =
5825                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5826                                let end_in_snapshot =
5827                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5828
5829                                for entry in snapshot
5830                                    .files(query.include_ignored(), start_in_snapshot)
5831                                    .take(end_in_snapshot - start_in_snapshot)
5832                                {
5833                                    if matching_paths_tx.is_closed() {
5834                                        break;
5835                                    }
5836                                    if unnamed_buffers.contains_key(&entry.path) {
5837                                        continue;
5838                                    }
5839                                    let matches = if query.file_matches(Some(&entry.path)) {
5840                                        abs_path.clear();
5841                                        abs_path.push(&snapshot.abs_path());
5842                                        abs_path.push(&entry.path);
5843                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5844                                        {
5845                                            query.detect(file).unwrap_or(false)
5846                                        } else {
5847                                            false
5848                                        }
5849                                    } else {
5850                                        false
5851                                    };
5852
5853                                    if matches {
5854                                        let project_path = SearchMatchCandidate::Path {
5855                                            worktree_id: snapshot.id(),
5856                                            path: entry.path.clone(),
5857                                            is_ignored: entry.is_ignored,
5858                                        };
5859                                        if matching_paths_tx.send(project_path).await.is_err() {
5860                                            break;
5861                                        }
5862                                    }
5863                                }
5864
5865                                snapshot_start_ix = snapshot_end_ix;
5866                            }
5867                        }
5868                    });
5869                }
5870
5871                if query.include_ignored() {
5872                    for snapshot in snapshots {
5873                        for ignored_entry in snapshot
5874                            .entries(query.include_ignored())
5875                            .filter(|e| e.is_ignored)
5876                        {
5877                            let limiter = Arc::clone(&max_concurrent_workers);
5878                            scope.spawn(async move {
5879                                let _guard = limiter.acquire().await;
5880                                let mut ignored_paths_to_process =
5881                                    VecDeque::from([snapshot.abs_path().join(&ignored_entry.path)]);
5882                                while let Some(ignored_abs_path) =
5883                                    ignored_paths_to_process.pop_front()
5884                                {
5885                                    if let Some(fs_metadata) = fs
5886                                        .metadata(&ignored_abs_path)
5887                                        .await
5888                                        .with_context(|| {
5889                                            format!("fetching fs metadata for {ignored_abs_path:?}")
5890                                        })
5891                                        .log_err()
5892                                        .flatten()
5893                                    {
5894                                        if fs_metadata.is_dir {
5895                                            if let Some(mut subfiles) = fs
5896                                                .read_dir(&ignored_abs_path)
5897                                                .await
5898                                                .with_context(|| {
5899                                                    format!(
5900                                                        "listing ignored path {ignored_abs_path:?}"
5901                                                    )
5902                                                })
5903                                                .log_err()
5904                                            {
5905                                                while let Some(subfile) = subfiles.next().await {
5906                                                    if let Some(subfile) = subfile.log_err() {
5907                                                        ignored_paths_to_process.push_back(subfile);
5908                                                    }
5909                                                }
5910                                            }
5911                                        } else if !fs_metadata.is_symlink {
5912                                            if !query.file_matches(Some(&ignored_abs_path))
5913                                                || snapshot.is_path_excluded(
5914                                                    ignored_entry.path.to_path_buf(),
5915                                                )
5916                                            {
5917                                                continue;
5918                                            }
5919                                            let matches = if let Some(file) = fs
5920                                                .open_sync(&ignored_abs_path)
5921                                                .await
5922                                                .with_context(|| {
5923                                                    format!(
5924                                                        "Opening ignored path {ignored_abs_path:?}"
5925                                                    )
5926                                                })
5927                                                .log_err()
5928                                            {
5929                                                query.detect(file).unwrap_or(false)
5930                                            } else {
5931                                                false
5932                                            };
5933                                            if matches {
5934                                                let project_path = SearchMatchCandidate::Path {
5935                                                    worktree_id: snapshot.id(),
5936                                                    path: Arc::from(
5937                                                        ignored_abs_path
5938                                                            .strip_prefix(snapshot.abs_path())
5939                                                            .expect(
5940                                                                "scanning worktree-related files",
5941                                                            ),
5942                                                    ),
5943                                                    is_ignored: true,
5944                                                };
5945                                                if matching_paths_tx
5946                                                    .send(project_path)
5947                                                    .await
5948                                                    .is_err()
5949                                                {
5950                                                    return;
5951                                                }
5952                                            }
5953                                        }
5954                                    }
5955                                }
5956                            });
5957                        }
5958                    }
5959                }
5960            })
5961            .await;
5962    }
5963
5964    pub fn request_lsp<R: LspCommand>(
5965        &self,
5966        buffer_handle: Model<Buffer>,
5967        server: LanguageServerToQuery,
5968        request: R,
5969        cx: &mut ModelContext<Self>,
5970    ) -> Task<Result<R::Response>>
5971    where
5972        <R::LspRequest as lsp::request::Request>::Result: Send,
5973        <R::LspRequest as lsp::request::Request>::Params: Send,
5974    {
5975        let buffer = buffer_handle.read(cx);
5976        if self.is_local() {
5977            let language_server = match server {
5978                LanguageServerToQuery::Primary => {
5979                    match self.primary_language_server_for_buffer(buffer, cx) {
5980                        Some((_, server)) => Some(Arc::clone(server)),
5981                        None => return Task::ready(Ok(Default::default())),
5982                    }
5983                }
5984                LanguageServerToQuery::Other(id) => self
5985                    .language_server_for_buffer(buffer, id, cx)
5986                    .map(|(_, server)| Arc::clone(server)),
5987            };
5988            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5989            if let (Some(file), Some(language_server)) = (file, language_server) {
5990                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5991                return cx.spawn(move |this, cx| async move {
5992                    if !request.check_capabilities(language_server.capabilities()) {
5993                        return Ok(Default::default());
5994                    }
5995
5996                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5997                    let response = match result {
5998                        Ok(response) => response,
5999
6000                        Err(err) => {
6001                            log::warn!(
6002                                "Generic lsp request to {} failed: {}",
6003                                language_server.name(),
6004                                err
6005                            );
6006                            return Err(err);
6007                        }
6008                    };
6009
6010                    request
6011                        .response_from_lsp(
6012                            response,
6013                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
6014                            buffer_handle,
6015                            language_server.server_id(),
6016                            cx,
6017                        )
6018                        .await
6019                });
6020            }
6021        } else if let Some(project_id) = self.remote_id() {
6022            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
6023        }
6024
6025        Task::ready(Ok(Default::default()))
6026    }
6027
6028    fn send_lsp_proto_request<R: LspCommand>(
6029        &self,
6030        buffer: Model<Buffer>,
6031        project_id: u64,
6032        request: R,
6033        cx: &mut ModelContext<'_, Project>,
6034    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
6035        let rpc = self.client.clone();
6036        let message = request.to_proto(project_id, buffer.read(cx));
6037        cx.spawn(move |this, mut cx| async move {
6038            // Ensure the project is still alive by the time the task
6039            // is scheduled.
6040            this.upgrade().context("project dropped")?;
6041            let response = rpc.request(message).await?;
6042            let this = this.upgrade().context("project dropped")?;
6043            if this.update(&mut cx, |this, _| this.is_disconnected())? {
6044                Err(anyhow!("disconnected before completing request"))
6045            } else {
6046                request
6047                    .response_from_proto(response, this, buffer, cx)
6048                    .await
6049            }
6050        })
6051    }
6052
6053    fn sort_candidates_and_open_buffers(
6054        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
6055        cx: &mut ModelContext<Self>,
6056    ) -> (
6057        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
6058        Receiver<(
6059            Option<(Model<Buffer>, BufferSnapshot)>,
6060            SearchMatchCandidateIndex,
6061        )>,
6062    ) {
6063        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
6064        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
6065        cx.spawn(move |this, cx| async move {
6066            let mut buffers = Vec::new();
6067            let mut ignored_buffers = Vec::new();
6068            while let Some(entry) = matching_paths_rx.next().await {
6069                if matches!(
6070                    entry,
6071                    SearchMatchCandidate::Path {
6072                        is_ignored: true,
6073                        ..
6074                    }
6075                ) {
6076                    ignored_buffers.push(entry);
6077                } else {
6078                    buffers.push(entry);
6079                }
6080            }
6081            buffers.sort_by_key(|candidate| candidate.path());
6082            ignored_buffers.sort_by_key(|candidate| candidate.path());
6083            buffers.extend(ignored_buffers);
6084            let matching_paths = buffers.clone();
6085            let _ = sorted_buffers_tx.send(buffers);
6086            for (index, candidate) in matching_paths.into_iter().enumerate() {
6087                if buffers_tx.is_closed() {
6088                    break;
6089                }
6090                let this = this.clone();
6091                let buffers_tx = buffers_tx.clone();
6092                cx.spawn(move |mut cx| async move {
6093                    let buffer = match candidate {
6094                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6095                        SearchMatchCandidate::Path {
6096                            worktree_id, path, ..
6097                        } => this
6098                            .update(&mut cx, |this, cx| {
6099                                this.open_buffer((worktree_id, path), cx)
6100                            })?
6101                            .await
6102                            .log_err(),
6103                    };
6104                    if let Some(buffer) = buffer {
6105                        let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6106                        buffers_tx
6107                            .send((Some((buffer, snapshot)), index))
6108                            .await
6109                            .log_err();
6110                    } else {
6111                        buffers_tx.send((None, index)).await.log_err();
6112                    }
6113
6114                    Ok::<_, anyhow::Error>(())
6115                })
6116                .detach();
6117            }
6118        })
6119        .detach();
6120        (sorted_buffers_rx, buffers_rx)
6121    }
6122
6123    pub fn find_or_create_local_worktree(
6124        &mut self,
6125        abs_path: impl AsRef<Path>,
6126        visible: bool,
6127        cx: &mut ModelContext<Self>,
6128    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6129        let abs_path = abs_path.as_ref();
6130        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6131            Task::ready(Ok((tree, relative_path)))
6132        } else {
6133            let worktree = self.create_local_worktree(abs_path, visible, cx);
6134            cx.background_executor()
6135                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6136        }
6137    }
6138
6139    pub fn find_local_worktree(
6140        &self,
6141        abs_path: &Path,
6142        cx: &AppContext,
6143    ) -> Option<(Model<Worktree>, PathBuf)> {
6144        for tree in &self.worktrees {
6145            if let Some(tree) = tree.upgrade() {
6146                if let Some(relative_path) = tree
6147                    .read(cx)
6148                    .as_local()
6149                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6150                {
6151                    return Some((tree.clone(), relative_path.into()));
6152                }
6153            }
6154        }
6155        None
6156    }
6157
6158    pub fn is_shared(&self) -> bool {
6159        match &self.client_state {
6160            Some(ProjectClientState::Local { .. }) => true,
6161            _ => false,
6162        }
6163    }
6164
6165    fn create_local_worktree(
6166        &mut self,
6167        abs_path: impl AsRef<Path>,
6168        visible: bool,
6169        cx: &mut ModelContext<Self>,
6170    ) -> Task<Result<Model<Worktree>>> {
6171        let fs = self.fs.clone();
6172        let client = self.client.clone();
6173        let next_entry_id = self.next_entry_id.clone();
6174        let path: Arc<Path> = abs_path.as_ref().into();
6175        let task = self
6176            .loading_local_worktrees
6177            .entry(path.clone())
6178            .or_insert_with(|| {
6179                cx.spawn(move |project, mut cx| {
6180                    async move {
6181                        let worktree = Worktree::local(
6182                            client.clone(),
6183                            path.clone(),
6184                            visible,
6185                            fs,
6186                            next_entry_id,
6187                            &mut cx,
6188                        )
6189                        .await;
6190
6191                        project.update(&mut cx, |project, _| {
6192                            project.loading_local_worktrees.remove(&path);
6193                        })?;
6194
6195                        let worktree = worktree?;
6196                        project
6197                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6198                        Ok(worktree)
6199                    }
6200                    .map_err(Arc::new)
6201                })
6202                .shared()
6203            })
6204            .clone();
6205        cx.background_executor().spawn(async move {
6206            match task.await {
6207                Ok(worktree) => Ok(worktree),
6208                Err(err) => Err(anyhow!("{}", err)),
6209            }
6210        })
6211    }
6212
6213    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6214        self.worktrees.retain(|worktree| {
6215            if let Some(worktree) = worktree.upgrade() {
6216                let id = worktree.read(cx).id();
6217                if id == id_to_remove {
6218                    cx.emit(Event::WorktreeRemoved(id));
6219                    false
6220                } else {
6221                    true
6222                }
6223            } else {
6224                false
6225            }
6226        });
6227        self.metadata_changed(cx);
6228    }
6229
6230    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6231        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6232        if worktree.read(cx).is_local() {
6233            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6234                worktree::Event::UpdatedEntries(changes) => {
6235                    this.update_local_worktree_buffers(&worktree, changes, cx);
6236                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6237                    this.update_local_worktree_settings(&worktree, changes, cx);
6238                    this.update_prettier_settings(&worktree, changes, cx);
6239                    cx.emit(Event::WorktreeUpdatedEntries(
6240                        worktree.read(cx).id(),
6241                        changes.clone(),
6242                    ));
6243                }
6244                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6245                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6246                }
6247            })
6248            .detach();
6249        }
6250
6251        let push_strong_handle = {
6252            let worktree = worktree.read(cx);
6253            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6254        };
6255        if push_strong_handle {
6256            self.worktrees
6257                .push(WorktreeHandle::Strong(worktree.clone()));
6258        } else {
6259            self.worktrees
6260                .push(WorktreeHandle::Weak(worktree.downgrade()));
6261        }
6262
6263        let handle_id = worktree.entity_id();
6264        cx.observe_release(worktree, move |this, worktree, cx| {
6265            let _ = this.remove_worktree(worktree.id(), cx);
6266            cx.update_global::<SettingsStore, _>(|store, cx| {
6267                store
6268                    .clear_local_settings(handle_id.as_u64() as usize, cx)
6269                    .log_err()
6270            });
6271        })
6272        .detach();
6273
6274        cx.emit(Event::WorktreeAdded);
6275        self.metadata_changed(cx);
6276    }
6277
6278    fn update_local_worktree_buffers(
6279        &mut self,
6280        worktree_handle: &Model<Worktree>,
6281        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6282        cx: &mut ModelContext<Self>,
6283    ) {
6284        let snapshot = worktree_handle.read(cx).snapshot();
6285
6286        let mut renamed_buffers = Vec::new();
6287        for (path, entry_id, _) in changes {
6288            let worktree_id = worktree_handle.read(cx).id();
6289            let project_path = ProjectPath {
6290                worktree_id,
6291                path: path.clone(),
6292            };
6293
6294            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6295                Some(&buffer_id) => buffer_id,
6296                None => match self.local_buffer_ids_by_path.get(&project_path) {
6297                    Some(&buffer_id) => buffer_id,
6298                    None => {
6299                        continue;
6300                    }
6301                },
6302            };
6303
6304            let open_buffer = self.opened_buffers.get(&buffer_id);
6305            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6306                buffer
6307            } else {
6308                self.opened_buffers.remove(&buffer_id);
6309                self.local_buffer_ids_by_path.remove(&project_path);
6310                self.local_buffer_ids_by_entry_id.remove(entry_id);
6311                continue;
6312            };
6313
6314            buffer.update(cx, |buffer, cx| {
6315                if let Some(old_file) = File::from_dyn(buffer.file()) {
6316                    if old_file.worktree != *worktree_handle {
6317                        return;
6318                    }
6319
6320                    let new_file = if let Some(entry) = old_file
6321                        .entry_id
6322                        .and_then(|entry_id| snapshot.entry_for_id(entry_id))
6323                    {
6324                        File {
6325                            is_local: true,
6326                            entry_id: Some(entry.id),
6327                            mtime: entry.mtime,
6328                            path: entry.path.clone(),
6329                            worktree: worktree_handle.clone(),
6330                            is_deleted: false,
6331                        }
6332                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6333                        File {
6334                            is_local: true,
6335                            entry_id: Some(entry.id),
6336                            mtime: entry.mtime,
6337                            path: entry.path.clone(),
6338                            worktree: worktree_handle.clone(),
6339                            is_deleted: false,
6340                        }
6341                    } else {
6342                        File {
6343                            is_local: true,
6344                            entry_id: old_file.entry_id,
6345                            path: old_file.path().clone(),
6346                            mtime: old_file.mtime(),
6347                            worktree: worktree_handle.clone(),
6348                            is_deleted: true,
6349                        }
6350                    };
6351
6352                    let old_path = old_file.abs_path(cx);
6353                    if new_file.abs_path(cx) != old_path {
6354                        renamed_buffers.push((cx.handle(), old_file.clone()));
6355                        self.local_buffer_ids_by_path.remove(&project_path);
6356                        self.local_buffer_ids_by_path.insert(
6357                            ProjectPath {
6358                                worktree_id,
6359                                path: path.clone(),
6360                            },
6361                            buffer_id,
6362                        );
6363                    }
6364
6365                    if new_file.entry_id != Some(*entry_id) {
6366                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6367                        if let Some(entry_id) = new_file.entry_id {
6368                            self.local_buffer_ids_by_entry_id
6369                                .insert(entry_id, buffer_id);
6370                        }
6371                    }
6372
6373                    if new_file != *old_file {
6374                        if let Some(project_id) = self.remote_id() {
6375                            self.client
6376                                .send(proto::UpdateBufferFile {
6377                                    project_id,
6378                                    buffer_id: buffer_id as u64,
6379                                    file: Some(new_file.to_proto()),
6380                                })
6381                                .log_err();
6382                        }
6383
6384                        buffer.file_updated(Arc::new(new_file), cx);
6385                    }
6386                }
6387            });
6388        }
6389
6390        for (buffer, old_file) in renamed_buffers {
6391            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6392            self.detect_language_for_buffer(&buffer, cx);
6393            self.register_buffer_with_language_servers(&buffer, cx);
6394        }
6395    }
6396
6397    fn update_local_worktree_language_servers(
6398        &mut self,
6399        worktree_handle: &Model<Worktree>,
6400        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6401        cx: &mut ModelContext<Self>,
6402    ) {
6403        if changes.is_empty() {
6404            return;
6405        }
6406
6407        let worktree_id = worktree_handle.read(cx).id();
6408        let mut language_server_ids = self
6409            .language_server_ids
6410            .iter()
6411            .filter_map(|((server_worktree_id, _), server_id)| {
6412                (*server_worktree_id == worktree_id).then_some(*server_id)
6413            })
6414            .collect::<Vec<_>>();
6415        language_server_ids.sort();
6416        language_server_ids.dedup();
6417
6418        let abs_path = worktree_handle.read(cx).abs_path();
6419        for server_id in &language_server_ids {
6420            if let Some(LanguageServerState::Running {
6421                server,
6422                watched_paths,
6423                ..
6424            }) = self.language_servers.get(server_id)
6425            {
6426                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6427                    let params = lsp::DidChangeWatchedFilesParams {
6428                        changes: changes
6429                            .iter()
6430                            .filter_map(|(path, _, change)| {
6431                                if !watched_paths.is_match(&path) {
6432                                    return None;
6433                                }
6434                                let typ = match change {
6435                                    PathChange::Loaded => return None,
6436                                    PathChange::Added => lsp::FileChangeType::CREATED,
6437                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6438                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6439                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6440                                };
6441                                Some(lsp::FileEvent {
6442                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6443                                    typ,
6444                                })
6445                            })
6446                            .collect(),
6447                    };
6448
6449                    if !params.changes.is_empty() {
6450                        server
6451                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6452                            .log_err();
6453                    }
6454                }
6455            }
6456        }
6457    }
6458
6459    fn update_local_worktree_buffers_git_repos(
6460        &mut self,
6461        worktree_handle: Model<Worktree>,
6462        changed_repos: &UpdatedGitRepositoriesSet,
6463        cx: &mut ModelContext<Self>,
6464    ) {
6465        debug_assert!(worktree_handle.read(cx).is_local());
6466
6467        // Identify the loading buffers whose containing repository that has changed.
6468        let future_buffers = self
6469            .loading_buffers_by_path
6470            .iter()
6471            .filter_map(|(project_path, receiver)| {
6472                if project_path.worktree_id != worktree_handle.read(cx).id() {
6473                    return None;
6474                }
6475                let path = &project_path.path;
6476                changed_repos
6477                    .iter()
6478                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6479                let receiver = receiver.clone();
6480                let path = path.clone();
6481                Some(async move {
6482                    wait_for_loading_buffer(receiver)
6483                        .await
6484                        .ok()
6485                        .map(|buffer| (buffer, path))
6486                })
6487            })
6488            .collect::<FuturesUnordered<_>>();
6489
6490        // Identify the current buffers whose containing repository has changed.
6491        let current_buffers = self
6492            .opened_buffers
6493            .values()
6494            .filter_map(|buffer| {
6495                let buffer = buffer.upgrade()?;
6496                let file = File::from_dyn(buffer.read(cx).file())?;
6497                if file.worktree != worktree_handle {
6498                    return None;
6499                }
6500                let path = file.path();
6501                changed_repos
6502                    .iter()
6503                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6504                Some((buffer, path.clone()))
6505            })
6506            .collect::<Vec<_>>();
6507
6508        if future_buffers.len() + current_buffers.len() == 0 {
6509            return;
6510        }
6511
6512        let remote_id = self.remote_id();
6513        let client = self.client.clone();
6514        cx.spawn(move |_, mut cx| async move {
6515            // Wait for all of the buffers to load.
6516            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6517
6518            // Reload the diff base for every buffer whose containing git repository has changed.
6519            let snapshot =
6520                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6521            let diff_bases_by_buffer = cx
6522                .background_executor()
6523                .spawn(async move {
6524                    future_buffers
6525                        .into_iter()
6526                        .filter_map(|e| e)
6527                        .chain(current_buffers)
6528                        .filter_map(|(buffer, path)| {
6529                            let (work_directory, repo) =
6530                                snapshot.repository_and_work_directory_for_path(&path)?;
6531                            let repo = snapshot.get_local_repo(&repo)?;
6532                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6533                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6534                            Some((buffer, base_text))
6535                        })
6536                        .collect::<Vec<_>>()
6537                })
6538                .await;
6539
6540            // Assign the new diff bases on all of the buffers.
6541            for (buffer, diff_base) in diff_bases_by_buffer {
6542                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6543                    buffer.set_diff_base(diff_base.clone(), cx);
6544                    buffer.remote_id()
6545                })?;
6546                if let Some(project_id) = remote_id {
6547                    client
6548                        .send(proto::UpdateDiffBase {
6549                            project_id,
6550                            buffer_id,
6551                            diff_base,
6552                        })
6553                        .log_err();
6554                }
6555            }
6556
6557            anyhow::Ok(())
6558        })
6559        .detach();
6560    }
6561
6562    fn update_local_worktree_settings(
6563        &mut self,
6564        worktree: &Model<Worktree>,
6565        changes: &UpdatedEntriesSet,
6566        cx: &mut ModelContext<Self>,
6567    ) {
6568        let project_id = self.remote_id();
6569        let worktree_id = worktree.entity_id();
6570        let worktree = worktree.read(cx).as_local().unwrap();
6571        let remote_worktree_id = worktree.id();
6572
6573        let mut settings_contents = Vec::new();
6574        for (path, _, change) in changes.iter() {
6575            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6576                let settings_dir = Arc::from(
6577                    path.ancestors()
6578                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6579                        .unwrap(),
6580                );
6581                let fs = self.fs.clone();
6582                let removed = *change == PathChange::Removed;
6583                let abs_path = worktree.absolutize(path);
6584                settings_contents.push(async move {
6585                    (
6586                        settings_dir,
6587                        if removed {
6588                            None
6589                        } else {
6590                            Some(async move { fs.load(&abs_path?).await }.await)
6591                        },
6592                    )
6593                });
6594            }
6595        }
6596
6597        if settings_contents.is_empty() {
6598            return;
6599        }
6600
6601        let client = self.client.clone();
6602        cx.spawn(move |_, cx| async move {
6603            let settings_contents: Vec<(Arc<Path>, _)> =
6604                futures::future::join_all(settings_contents).await;
6605            cx.update(|cx| {
6606                cx.update_global::<SettingsStore, _>(|store, cx| {
6607                    for (directory, file_content) in settings_contents {
6608                        let file_content = file_content.and_then(|content| content.log_err());
6609                        store
6610                            .set_local_settings(
6611                                worktree_id.as_u64() as usize,
6612                                directory.clone(),
6613                                file_content.as_ref().map(String::as_str),
6614                                cx,
6615                            )
6616                            .log_err();
6617                        if let Some(remote_id) = project_id {
6618                            client
6619                                .send(proto::UpdateWorktreeSettings {
6620                                    project_id: remote_id,
6621                                    worktree_id: remote_worktree_id.to_proto(),
6622                                    path: directory.to_string_lossy().into_owned(),
6623                                    content: file_content,
6624                                })
6625                                .log_err();
6626                        }
6627                    }
6628                });
6629            })
6630            .ok();
6631        })
6632        .detach();
6633    }
6634
6635    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6636        let new_active_entry = entry.and_then(|project_path| {
6637            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6638            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6639            Some(entry.id)
6640        });
6641        if new_active_entry != self.active_entry {
6642            self.active_entry = new_active_entry;
6643            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6644        }
6645    }
6646
6647    pub fn language_servers_running_disk_based_diagnostics(
6648        &self,
6649    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6650        self.language_server_statuses
6651            .iter()
6652            .filter_map(|(id, status)| {
6653                if status.has_pending_diagnostic_updates {
6654                    Some(*id)
6655                } else {
6656                    None
6657                }
6658            })
6659    }
6660
6661    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &AppContext) -> DiagnosticSummary {
6662        let mut summary = DiagnosticSummary::default();
6663        for (_, _, path_summary) in
6664            self.diagnostic_summaries(include_ignored, cx)
6665                .filter(|(path, _, _)| {
6666                    let worktree = self.entry_for_path(&path, cx).map(|entry| entry.is_ignored);
6667                    include_ignored || worktree == Some(false)
6668                })
6669        {
6670            summary.error_count += path_summary.error_count;
6671            summary.warning_count += path_summary.warning_count;
6672        }
6673        summary
6674    }
6675
6676    pub fn diagnostic_summaries<'a>(
6677        &'a self,
6678        include_ignored: bool,
6679        cx: &'a AppContext,
6680    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6681        self.visible_worktrees(cx)
6682            .flat_map(move |worktree| {
6683                let worktree = worktree.read(cx);
6684                let worktree_id = worktree.id();
6685                worktree
6686                    .diagnostic_summaries()
6687                    .map(move |(path, server_id, summary)| {
6688                        (ProjectPath { worktree_id, path }, server_id, summary)
6689                    })
6690            })
6691            .filter(move |(path, _, _)| {
6692                let worktree = self.entry_for_path(&path, cx).map(|entry| entry.is_ignored);
6693                include_ignored || worktree == Some(false)
6694            })
6695    }
6696
6697    pub fn disk_based_diagnostics_started(
6698        &mut self,
6699        language_server_id: LanguageServerId,
6700        cx: &mut ModelContext<Self>,
6701    ) {
6702        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6703    }
6704
6705    pub fn disk_based_diagnostics_finished(
6706        &mut self,
6707        language_server_id: LanguageServerId,
6708        cx: &mut ModelContext<Self>,
6709    ) {
6710        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6711    }
6712
6713    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6714        self.active_entry
6715    }
6716
6717    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6718        self.worktree_for_id(path.worktree_id, cx)?
6719            .read(cx)
6720            .entry_for_path(&path.path)
6721            .cloned()
6722    }
6723
6724    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6725        let worktree = self.worktree_for_entry(entry_id, cx)?;
6726        let worktree = worktree.read(cx);
6727        let worktree_id = worktree.id();
6728        let path = worktree.entry_for_id(entry_id)?.path.clone();
6729        Some(ProjectPath { worktree_id, path })
6730    }
6731
6732    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6733        let workspace_root = self
6734            .worktree_for_id(project_path.worktree_id, cx)?
6735            .read(cx)
6736            .abs_path();
6737        let project_path = project_path.path.as_ref();
6738
6739        Some(if project_path == Path::new("") {
6740            workspace_root.to_path_buf()
6741        } else {
6742            workspace_root.join(project_path)
6743        })
6744    }
6745
6746    // RPC message handlers
6747
6748    async fn handle_unshare_project(
6749        this: Model<Self>,
6750        _: TypedEnvelope<proto::UnshareProject>,
6751        _: Arc<Client>,
6752        mut cx: AsyncAppContext,
6753    ) -> Result<()> {
6754        this.update(&mut cx, |this, cx| {
6755            if this.is_local() {
6756                this.unshare(cx)?;
6757            } else {
6758                this.disconnected_from_host(cx);
6759            }
6760            Ok(())
6761        })?
6762    }
6763
6764    async fn handle_add_collaborator(
6765        this: Model<Self>,
6766        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6767        _: Arc<Client>,
6768        mut cx: AsyncAppContext,
6769    ) -> Result<()> {
6770        let collaborator = envelope
6771            .payload
6772            .collaborator
6773            .take()
6774            .ok_or_else(|| anyhow!("empty collaborator"))?;
6775
6776        let collaborator = Collaborator::from_proto(collaborator)?;
6777        this.update(&mut cx, |this, cx| {
6778            this.shared_buffers.remove(&collaborator.peer_id);
6779            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6780            this.collaborators
6781                .insert(collaborator.peer_id, collaborator);
6782            cx.notify();
6783        })?;
6784
6785        Ok(())
6786    }
6787
6788    async fn handle_update_project_collaborator(
6789        this: Model<Self>,
6790        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6791        _: Arc<Client>,
6792        mut cx: AsyncAppContext,
6793    ) -> Result<()> {
6794        let old_peer_id = envelope
6795            .payload
6796            .old_peer_id
6797            .ok_or_else(|| anyhow!("missing old peer id"))?;
6798        let new_peer_id = envelope
6799            .payload
6800            .new_peer_id
6801            .ok_or_else(|| anyhow!("missing new peer id"))?;
6802        this.update(&mut cx, |this, cx| {
6803            let collaborator = this
6804                .collaborators
6805                .remove(&old_peer_id)
6806                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6807            let is_host = collaborator.replica_id == 0;
6808            this.collaborators.insert(new_peer_id, collaborator);
6809
6810            let buffers = this.shared_buffers.remove(&old_peer_id);
6811            log::info!(
6812                "peer {} became {}. moving buffers {:?}",
6813                old_peer_id,
6814                new_peer_id,
6815                &buffers
6816            );
6817            if let Some(buffers) = buffers {
6818                this.shared_buffers.insert(new_peer_id, buffers);
6819            }
6820
6821            if is_host {
6822                this.opened_buffers
6823                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6824                this.buffer_ordered_messages_tx
6825                    .unbounded_send(BufferOrderedMessage::Resync)
6826                    .unwrap();
6827            }
6828
6829            cx.emit(Event::CollaboratorUpdated {
6830                old_peer_id,
6831                new_peer_id,
6832            });
6833            cx.notify();
6834            Ok(())
6835        })?
6836    }
6837
6838    async fn handle_remove_collaborator(
6839        this: Model<Self>,
6840        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6841        _: Arc<Client>,
6842        mut cx: AsyncAppContext,
6843    ) -> Result<()> {
6844        this.update(&mut cx, |this, cx| {
6845            let peer_id = envelope
6846                .payload
6847                .peer_id
6848                .ok_or_else(|| anyhow!("invalid peer id"))?;
6849            let replica_id = this
6850                .collaborators
6851                .remove(&peer_id)
6852                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6853                .replica_id;
6854            for buffer in this.opened_buffers.values() {
6855                if let Some(buffer) = buffer.upgrade() {
6856                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6857                }
6858            }
6859            this.shared_buffers.remove(&peer_id);
6860
6861            cx.emit(Event::CollaboratorLeft(peer_id));
6862            cx.notify();
6863            Ok(())
6864        })?
6865    }
6866
6867    async fn handle_update_project(
6868        this: Model<Self>,
6869        envelope: TypedEnvelope<proto::UpdateProject>,
6870        _: Arc<Client>,
6871        mut cx: AsyncAppContext,
6872    ) -> Result<()> {
6873        this.update(&mut cx, |this, cx| {
6874            // Don't handle messages that were sent before the response to us joining the project
6875            if envelope.message_id > this.join_project_response_message_id {
6876                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6877            }
6878            Ok(())
6879        })?
6880    }
6881
6882    async fn handle_update_worktree(
6883        this: Model<Self>,
6884        envelope: TypedEnvelope<proto::UpdateWorktree>,
6885        _: Arc<Client>,
6886        mut cx: AsyncAppContext,
6887    ) -> Result<()> {
6888        this.update(&mut cx, |this, cx| {
6889            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6890            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6891                worktree.update(cx, |worktree, _| {
6892                    let worktree = worktree.as_remote_mut().unwrap();
6893                    worktree.update_from_remote(envelope.payload);
6894                });
6895            }
6896            Ok(())
6897        })?
6898    }
6899
6900    async fn handle_update_worktree_settings(
6901        this: Model<Self>,
6902        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6903        _: Arc<Client>,
6904        mut cx: AsyncAppContext,
6905    ) -> Result<()> {
6906        this.update(&mut cx, |this, cx| {
6907            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6908            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6909                cx.update_global::<SettingsStore, _>(|store, cx| {
6910                    store
6911                        .set_local_settings(
6912                            worktree.entity_id().as_u64() as usize,
6913                            PathBuf::from(&envelope.payload.path).into(),
6914                            envelope.payload.content.as_ref().map(String::as_str),
6915                            cx,
6916                        )
6917                        .log_err();
6918                });
6919            }
6920            Ok(())
6921        })?
6922    }
6923
6924    async fn handle_create_project_entry(
6925        this: Model<Self>,
6926        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6927        _: Arc<Client>,
6928        mut cx: AsyncAppContext,
6929    ) -> Result<proto::ProjectEntryResponse> {
6930        let worktree = this.update(&mut cx, |this, cx| {
6931            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6932            this.worktree_for_id(worktree_id, cx)
6933                .ok_or_else(|| anyhow!("worktree not found"))
6934        })??;
6935        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6936        let entry = worktree
6937            .update(&mut cx, |worktree, cx| {
6938                let worktree = worktree.as_local_mut().unwrap();
6939                let path = PathBuf::from(envelope.payload.path);
6940                worktree.create_entry(path, envelope.payload.is_directory, cx)
6941            })?
6942            .await?;
6943        Ok(proto::ProjectEntryResponse {
6944            entry: entry.as_ref().map(|e| e.into()),
6945            worktree_scan_id: worktree_scan_id as u64,
6946        })
6947    }
6948
6949    async fn handle_rename_project_entry(
6950        this: Model<Self>,
6951        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6952        _: Arc<Client>,
6953        mut cx: AsyncAppContext,
6954    ) -> Result<proto::ProjectEntryResponse> {
6955        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6956        let worktree = this.update(&mut cx, |this, cx| {
6957            this.worktree_for_entry(entry_id, cx)
6958                .ok_or_else(|| anyhow!("worktree not found"))
6959        })??;
6960        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6961        let entry = worktree
6962            .update(&mut cx, |worktree, cx| {
6963                let new_path = PathBuf::from(envelope.payload.new_path);
6964                worktree
6965                    .as_local_mut()
6966                    .unwrap()
6967                    .rename_entry(entry_id, new_path, cx)
6968            })?
6969            .await?;
6970        Ok(proto::ProjectEntryResponse {
6971            entry: entry.as_ref().map(|e| e.into()),
6972            worktree_scan_id: worktree_scan_id as u64,
6973        })
6974    }
6975
6976    async fn handle_copy_project_entry(
6977        this: Model<Self>,
6978        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6979        _: Arc<Client>,
6980        mut cx: AsyncAppContext,
6981    ) -> Result<proto::ProjectEntryResponse> {
6982        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6983        let worktree = this.update(&mut cx, |this, cx| {
6984            this.worktree_for_entry(entry_id, cx)
6985                .ok_or_else(|| anyhow!("worktree not found"))
6986        })??;
6987        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6988        let entry = worktree
6989            .update(&mut cx, |worktree, cx| {
6990                let new_path = PathBuf::from(envelope.payload.new_path);
6991                worktree
6992                    .as_local_mut()
6993                    .unwrap()
6994                    .copy_entry(entry_id, new_path, cx)
6995            })?
6996            .await?;
6997        Ok(proto::ProjectEntryResponse {
6998            entry: entry.as_ref().map(|e| e.into()),
6999            worktree_scan_id: worktree_scan_id as u64,
7000        })
7001    }
7002
7003    async fn handle_delete_project_entry(
7004        this: Model<Self>,
7005        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
7006        _: Arc<Client>,
7007        mut cx: AsyncAppContext,
7008    ) -> Result<proto::ProjectEntryResponse> {
7009        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7010
7011        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
7012
7013        let worktree = this.update(&mut cx, |this, cx| {
7014            this.worktree_for_entry(entry_id, cx)
7015                .ok_or_else(|| anyhow!("worktree not found"))
7016        })??;
7017        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
7018        worktree
7019            .update(&mut cx, |worktree, cx| {
7020                worktree
7021                    .as_local_mut()
7022                    .unwrap()
7023                    .delete_entry(entry_id, cx)
7024                    .ok_or_else(|| anyhow!("invalid entry"))
7025            })??
7026            .await?;
7027        Ok(proto::ProjectEntryResponse {
7028            entry: None,
7029            worktree_scan_id: worktree_scan_id as u64,
7030        })
7031    }
7032
7033    async fn handle_expand_project_entry(
7034        this: Model<Self>,
7035        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7036        _: Arc<Client>,
7037        mut cx: AsyncAppContext,
7038    ) -> Result<proto::ExpandProjectEntryResponse> {
7039        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7040        let worktree = this
7041            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7042            .ok_or_else(|| anyhow!("invalid request"))?;
7043        worktree
7044            .update(&mut cx, |worktree, cx| {
7045                worktree
7046                    .as_local_mut()
7047                    .unwrap()
7048                    .expand_entry(entry_id, cx)
7049                    .ok_or_else(|| anyhow!("invalid entry"))
7050            })??
7051            .await?;
7052        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7053        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7054    }
7055
7056    async fn handle_update_diagnostic_summary(
7057        this: Model<Self>,
7058        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7059        _: Arc<Client>,
7060        mut cx: AsyncAppContext,
7061    ) -> Result<()> {
7062        this.update(&mut cx, |this, cx| {
7063            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7064            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7065                if let Some(summary) = envelope.payload.summary {
7066                    let project_path = ProjectPath {
7067                        worktree_id,
7068                        path: Path::new(&summary.path).into(),
7069                    };
7070                    worktree.update(cx, |worktree, _| {
7071                        worktree
7072                            .as_remote_mut()
7073                            .unwrap()
7074                            .update_diagnostic_summary(project_path.path.clone(), &summary);
7075                    });
7076                    cx.emit(Event::DiagnosticsUpdated {
7077                        language_server_id: LanguageServerId(summary.language_server_id as usize),
7078                        path: project_path,
7079                    });
7080                }
7081            }
7082            Ok(())
7083        })?
7084    }
7085
7086    async fn handle_start_language_server(
7087        this: Model<Self>,
7088        envelope: TypedEnvelope<proto::StartLanguageServer>,
7089        _: Arc<Client>,
7090        mut cx: AsyncAppContext,
7091    ) -> Result<()> {
7092        let server = envelope
7093            .payload
7094            .server
7095            .ok_or_else(|| anyhow!("invalid server"))?;
7096        this.update(&mut cx, |this, cx| {
7097            this.language_server_statuses.insert(
7098                LanguageServerId(server.id as usize),
7099                LanguageServerStatus {
7100                    name: server.name,
7101                    pending_work: Default::default(),
7102                    has_pending_diagnostic_updates: false,
7103                    progress_tokens: Default::default(),
7104                },
7105            );
7106            cx.notify();
7107        })?;
7108        Ok(())
7109    }
7110
7111    async fn handle_update_language_server(
7112        this: Model<Self>,
7113        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7114        _: Arc<Client>,
7115        mut cx: AsyncAppContext,
7116    ) -> Result<()> {
7117        this.update(&mut cx, |this, cx| {
7118            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7119
7120            match envelope
7121                .payload
7122                .variant
7123                .ok_or_else(|| anyhow!("invalid variant"))?
7124            {
7125                proto::update_language_server::Variant::WorkStart(payload) => {
7126                    this.on_lsp_work_start(
7127                        language_server_id,
7128                        payload.token,
7129                        LanguageServerProgress {
7130                            message: payload.message,
7131                            percentage: payload.percentage.map(|p| p as usize),
7132                            last_update_at: Instant::now(),
7133                        },
7134                        cx,
7135                    );
7136                }
7137
7138                proto::update_language_server::Variant::WorkProgress(payload) => {
7139                    this.on_lsp_work_progress(
7140                        language_server_id,
7141                        payload.token,
7142                        LanguageServerProgress {
7143                            message: payload.message,
7144                            percentage: payload.percentage.map(|p| p as usize),
7145                            last_update_at: Instant::now(),
7146                        },
7147                        cx,
7148                    );
7149                }
7150
7151                proto::update_language_server::Variant::WorkEnd(payload) => {
7152                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7153                }
7154
7155                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7156                    this.disk_based_diagnostics_started(language_server_id, cx);
7157                }
7158
7159                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7160                    this.disk_based_diagnostics_finished(language_server_id, cx)
7161                }
7162            }
7163
7164            Ok(())
7165        })?
7166    }
7167
7168    async fn handle_update_buffer(
7169        this: Model<Self>,
7170        envelope: TypedEnvelope<proto::UpdateBuffer>,
7171        _: Arc<Client>,
7172        mut cx: AsyncAppContext,
7173    ) -> Result<proto::Ack> {
7174        this.update(&mut cx, |this, cx| {
7175            let payload = envelope.payload.clone();
7176            let buffer_id = payload.buffer_id;
7177            let ops = payload
7178                .operations
7179                .into_iter()
7180                .map(language::proto::deserialize_operation)
7181                .collect::<Result<Vec<_>, _>>()?;
7182            let is_remote = this.is_remote();
7183            match this.opened_buffers.entry(buffer_id) {
7184                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7185                    OpenBuffer::Strong(buffer) => {
7186                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7187                    }
7188                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7189                    OpenBuffer::Weak(_) => {}
7190                },
7191                hash_map::Entry::Vacant(e) => {
7192                    assert!(
7193                        is_remote,
7194                        "received buffer update from {:?}",
7195                        envelope.original_sender_id
7196                    );
7197                    e.insert(OpenBuffer::Operations(ops));
7198                }
7199            }
7200            Ok(proto::Ack {})
7201        })?
7202    }
7203
7204    async fn handle_create_buffer_for_peer(
7205        this: Model<Self>,
7206        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7207        _: Arc<Client>,
7208        mut cx: AsyncAppContext,
7209    ) -> Result<()> {
7210        this.update(&mut cx, |this, cx| {
7211            match envelope
7212                .payload
7213                .variant
7214                .ok_or_else(|| anyhow!("missing variant"))?
7215            {
7216                proto::create_buffer_for_peer::Variant::State(mut state) => {
7217                    let mut buffer_file = None;
7218                    if let Some(file) = state.file.take() {
7219                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7220                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7221                            anyhow!("no worktree found for id {}", file.worktree_id)
7222                        })?;
7223                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7224                            as Arc<dyn language::File>);
7225                    }
7226
7227                    let buffer_id = state.id;
7228                    let buffer = cx.new_model(|_| {
7229                        Buffer::from_proto(this.replica_id(), this.capability(), state, buffer_file)
7230                            .unwrap()
7231                    });
7232                    this.incomplete_remote_buffers
7233                        .insert(buffer_id, Some(buffer));
7234                }
7235                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7236                    let buffer = this
7237                        .incomplete_remote_buffers
7238                        .get(&chunk.buffer_id)
7239                        .cloned()
7240                        .flatten()
7241                        .ok_or_else(|| {
7242                            anyhow!(
7243                                "received chunk for buffer {} without initial state",
7244                                chunk.buffer_id
7245                            )
7246                        })?;
7247                    let operations = chunk
7248                        .operations
7249                        .into_iter()
7250                        .map(language::proto::deserialize_operation)
7251                        .collect::<Result<Vec<_>>>()?;
7252                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7253
7254                    if chunk.is_last {
7255                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
7256                        this.register_buffer(&buffer, cx)?;
7257                    }
7258                }
7259            }
7260
7261            Ok(())
7262        })?
7263    }
7264
7265    async fn handle_update_diff_base(
7266        this: Model<Self>,
7267        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7268        _: Arc<Client>,
7269        mut cx: AsyncAppContext,
7270    ) -> Result<()> {
7271        this.update(&mut cx, |this, cx| {
7272            let buffer_id = envelope.payload.buffer_id;
7273            let diff_base = envelope.payload.diff_base;
7274            if let Some(buffer) = this
7275                .opened_buffers
7276                .get_mut(&buffer_id)
7277                .and_then(|b| b.upgrade())
7278                .or_else(|| {
7279                    this.incomplete_remote_buffers
7280                        .get(&buffer_id)
7281                        .cloned()
7282                        .flatten()
7283                })
7284            {
7285                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7286            }
7287            Ok(())
7288        })?
7289    }
7290
7291    async fn handle_update_buffer_file(
7292        this: Model<Self>,
7293        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7294        _: Arc<Client>,
7295        mut cx: AsyncAppContext,
7296    ) -> Result<()> {
7297        let buffer_id = envelope.payload.buffer_id;
7298
7299        this.update(&mut cx, |this, cx| {
7300            let payload = envelope.payload.clone();
7301            if let Some(buffer) = this
7302                .opened_buffers
7303                .get(&buffer_id)
7304                .and_then(|b| b.upgrade())
7305                .or_else(|| {
7306                    this.incomplete_remote_buffers
7307                        .get(&buffer_id)
7308                        .cloned()
7309                        .flatten()
7310                })
7311            {
7312                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7313                let worktree = this
7314                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7315                    .ok_or_else(|| anyhow!("no such worktree"))?;
7316                let file = File::from_proto(file, worktree, cx)?;
7317                buffer.update(cx, |buffer, cx| {
7318                    buffer.file_updated(Arc::new(file), cx);
7319                });
7320                this.detect_language_for_buffer(&buffer, cx);
7321            }
7322            Ok(())
7323        })?
7324    }
7325
7326    async fn handle_save_buffer(
7327        this: Model<Self>,
7328        envelope: TypedEnvelope<proto::SaveBuffer>,
7329        _: Arc<Client>,
7330        mut cx: AsyncAppContext,
7331    ) -> Result<proto::BufferSaved> {
7332        let buffer_id = envelope.payload.buffer_id;
7333        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7334            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7335            let buffer = this
7336                .opened_buffers
7337                .get(&buffer_id)
7338                .and_then(|buffer| buffer.upgrade())
7339                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7340            anyhow::Ok((project_id, buffer))
7341        })??;
7342        buffer
7343            .update(&mut cx, |buffer, _| {
7344                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7345            })?
7346            .await?;
7347        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7348
7349        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7350            .await?;
7351        Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7352            project_id,
7353            buffer_id,
7354            version: serialize_version(buffer.saved_version()),
7355            mtime: Some(buffer.saved_mtime().into()),
7356            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7357        })?)
7358    }
7359
7360    async fn handle_reload_buffers(
7361        this: Model<Self>,
7362        envelope: TypedEnvelope<proto::ReloadBuffers>,
7363        _: Arc<Client>,
7364        mut cx: AsyncAppContext,
7365    ) -> Result<proto::ReloadBuffersResponse> {
7366        let sender_id = envelope.original_sender_id()?;
7367        let reload = this.update(&mut cx, |this, cx| {
7368            let mut buffers = HashSet::default();
7369            for buffer_id in &envelope.payload.buffer_ids {
7370                buffers.insert(
7371                    this.opened_buffers
7372                        .get(buffer_id)
7373                        .and_then(|buffer| buffer.upgrade())
7374                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7375                );
7376            }
7377            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7378        })??;
7379
7380        let project_transaction = reload.await?;
7381        let project_transaction = this.update(&mut cx, |this, cx| {
7382            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7383        })?;
7384        Ok(proto::ReloadBuffersResponse {
7385            transaction: Some(project_transaction),
7386        })
7387    }
7388
7389    async fn handle_synchronize_buffers(
7390        this: Model<Self>,
7391        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7392        _: Arc<Client>,
7393        mut cx: AsyncAppContext,
7394    ) -> Result<proto::SynchronizeBuffersResponse> {
7395        let project_id = envelope.payload.project_id;
7396        let mut response = proto::SynchronizeBuffersResponse {
7397            buffers: Default::default(),
7398        };
7399
7400        this.update(&mut cx, |this, cx| {
7401            let Some(guest_id) = envelope.original_sender_id else {
7402                error!("missing original_sender_id on SynchronizeBuffers request");
7403                return;
7404            };
7405
7406            this.shared_buffers.entry(guest_id).or_default().clear();
7407            for buffer in envelope.payload.buffers {
7408                let buffer_id = buffer.id;
7409                let remote_version = language::proto::deserialize_version(&buffer.version);
7410                if let Some(buffer) = this.buffer_for_id(buffer_id) {
7411                    this.shared_buffers
7412                        .entry(guest_id)
7413                        .or_default()
7414                        .insert(buffer_id);
7415
7416                    let buffer = buffer.read(cx);
7417                    response.buffers.push(proto::BufferVersion {
7418                        id: buffer_id,
7419                        version: language::proto::serialize_version(&buffer.version),
7420                    });
7421
7422                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7423                    let client = this.client.clone();
7424                    if let Some(file) = buffer.file() {
7425                        client
7426                            .send(proto::UpdateBufferFile {
7427                                project_id,
7428                                buffer_id: buffer_id as u64,
7429                                file: Some(file.to_proto()),
7430                            })
7431                            .log_err();
7432                    }
7433
7434                    client
7435                        .send(proto::UpdateDiffBase {
7436                            project_id,
7437                            buffer_id: buffer_id as u64,
7438                            diff_base: buffer.diff_base().map(Into::into),
7439                        })
7440                        .log_err();
7441
7442                    client
7443                        .send(proto::BufferReloaded {
7444                            project_id,
7445                            buffer_id,
7446                            version: language::proto::serialize_version(buffer.saved_version()),
7447                            mtime: Some(buffer.saved_mtime().into()),
7448                            fingerprint: language::proto::serialize_fingerprint(
7449                                buffer.saved_version_fingerprint(),
7450                            ),
7451                            line_ending: language::proto::serialize_line_ending(
7452                                buffer.line_ending(),
7453                            ) as i32,
7454                        })
7455                        .log_err();
7456
7457                    cx.background_executor()
7458                        .spawn(
7459                            async move {
7460                                let operations = operations.await;
7461                                for chunk in split_operations(operations) {
7462                                    client
7463                                        .request(proto::UpdateBuffer {
7464                                            project_id,
7465                                            buffer_id,
7466                                            operations: chunk,
7467                                        })
7468                                        .await?;
7469                                }
7470                                anyhow::Ok(())
7471                            }
7472                            .log_err(),
7473                        )
7474                        .detach();
7475                }
7476            }
7477        })?;
7478
7479        Ok(response)
7480    }
7481
7482    async fn handle_format_buffers(
7483        this: Model<Self>,
7484        envelope: TypedEnvelope<proto::FormatBuffers>,
7485        _: Arc<Client>,
7486        mut cx: AsyncAppContext,
7487    ) -> Result<proto::FormatBuffersResponse> {
7488        let sender_id = envelope.original_sender_id()?;
7489        let format = this.update(&mut cx, |this, cx| {
7490            let mut buffers = HashSet::default();
7491            for buffer_id in &envelope.payload.buffer_ids {
7492                buffers.insert(
7493                    this.opened_buffers
7494                        .get(buffer_id)
7495                        .and_then(|buffer| buffer.upgrade())
7496                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7497                );
7498            }
7499            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7500            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7501        })??;
7502
7503        let project_transaction = format.await?;
7504        let project_transaction = this.update(&mut cx, |this, cx| {
7505            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7506        })?;
7507        Ok(proto::FormatBuffersResponse {
7508            transaction: Some(project_transaction),
7509        })
7510    }
7511
7512    async fn handle_apply_additional_edits_for_completion(
7513        this: Model<Self>,
7514        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7515        _: Arc<Client>,
7516        mut cx: AsyncAppContext,
7517    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7518        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7519            let buffer = this
7520                .opened_buffers
7521                .get(&envelope.payload.buffer_id)
7522                .and_then(|buffer| buffer.upgrade())
7523                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7524            let language = buffer.read(cx).language();
7525            let completion = language::proto::deserialize_completion(
7526                envelope
7527                    .payload
7528                    .completion
7529                    .ok_or_else(|| anyhow!("invalid completion"))?,
7530                language.cloned(),
7531            );
7532            Ok::<_, anyhow::Error>((buffer, completion))
7533        })??;
7534
7535        let completion = completion.await?;
7536
7537        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7538            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7539        })?;
7540
7541        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7542            transaction: apply_additional_edits
7543                .await?
7544                .as_ref()
7545                .map(language::proto::serialize_transaction),
7546        })
7547    }
7548
7549    async fn handle_apply_code_action(
7550        this: Model<Self>,
7551        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7552        _: Arc<Client>,
7553        mut cx: AsyncAppContext,
7554    ) -> Result<proto::ApplyCodeActionResponse> {
7555        let sender_id = envelope.original_sender_id()?;
7556        let action = language::proto::deserialize_code_action(
7557            envelope
7558                .payload
7559                .action
7560                .ok_or_else(|| anyhow!("invalid action"))?,
7561        )?;
7562        let apply_code_action = this.update(&mut cx, |this, cx| {
7563            let buffer = this
7564                .opened_buffers
7565                .get(&envelope.payload.buffer_id)
7566                .and_then(|buffer| buffer.upgrade())
7567                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7568            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7569        })??;
7570
7571        let project_transaction = apply_code_action.await?;
7572        let project_transaction = this.update(&mut cx, |this, cx| {
7573            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7574        })?;
7575        Ok(proto::ApplyCodeActionResponse {
7576            transaction: Some(project_transaction),
7577        })
7578    }
7579
7580    async fn handle_on_type_formatting(
7581        this: Model<Self>,
7582        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7583        _: Arc<Client>,
7584        mut cx: AsyncAppContext,
7585    ) -> Result<proto::OnTypeFormattingResponse> {
7586        let on_type_formatting = this.update(&mut cx, |this, cx| {
7587            let buffer = this
7588                .opened_buffers
7589                .get(&envelope.payload.buffer_id)
7590                .and_then(|buffer| buffer.upgrade())
7591                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7592            let position = envelope
7593                .payload
7594                .position
7595                .and_then(deserialize_anchor)
7596                .ok_or_else(|| anyhow!("invalid position"))?;
7597            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7598                buffer,
7599                position,
7600                envelope.payload.trigger.clone(),
7601                cx,
7602            ))
7603        })??;
7604
7605        let transaction = on_type_formatting
7606            .await?
7607            .as_ref()
7608            .map(language::proto::serialize_transaction);
7609        Ok(proto::OnTypeFormattingResponse { transaction })
7610    }
7611
7612    async fn handle_inlay_hints(
7613        this: Model<Self>,
7614        envelope: TypedEnvelope<proto::InlayHints>,
7615        _: Arc<Client>,
7616        mut cx: AsyncAppContext,
7617    ) -> Result<proto::InlayHintsResponse> {
7618        let sender_id = envelope.original_sender_id()?;
7619        let buffer = this.update(&mut cx, |this, _| {
7620            this.opened_buffers
7621                .get(&envelope.payload.buffer_id)
7622                .and_then(|buffer| buffer.upgrade())
7623                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7624        })??;
7625        let buffer_version = deserialize_version(&envelope.payload.version);
7626
7627        buffer
7628            .update(&mut cx, |buffer, _| {
7629                buffer.wait_for_version(buffer_version.clone())
7630            })?
7631            .await
7632            .with_context(|| {
7633                format!(
7634                    "waiting for version {:?} for buffer {}",
7635                    buffer_version,
7636                    buffer.entity_id()
7637                )
7638            })?;
7639
7640        let start = envelope
7641            .payload
7642            .start
7643            .and_then(deserialize_anchor)
7644            .context("missing range start")?;
7645        let end = envelope
7646            .payload
7647            .end
7648            .and_then(deserialize_anchor)
7649            .context("missing range end")?;
7650        let buffer_hints = this
7651            .update(&mut cx, |project, cx| {
7652                project.inlay_hints(buffer, start..end, cx)
7653            })?
7654            .await
7655            .context("inlay hints fetch")?;
7656
7657        Ok(this.update(&mut cx, |project, cx| {
7658            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7659        })?)
7660    }
7661
7662    async fn handle_resolve_inlay_hint(
7663        this: Model<Self>,
7664        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7665        _: Arc<Client>,
7666        mut cx: AsyncAppContext,
7667    ) -> Result<proto::ResolveInlayHintResponse> {
7668        let proto_hint = envelope
7669            .payload
7670            .hint
7671            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7672        let hint = InlayHints::proto_to_project_hint(proto_hint)
7673            .context("resolved proto inlay hint conversion")?;
7674        let buffer = this.update(&mut cx, |this, _cx| {
7675            this.opened_buffers
7676                .get(&envelope.payload.buffer_id)
7677                .and_then(|buffer| buffer.upgrade())
7678                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7679        })??;
7680        let response_hint = this
7681            .update(&mut cx, |project, cx| {
7682                project.resolve_inlay_hint(
7683                    hint,
7684                    buffer,
7685                    LanguageServerId(envelope.payload.language_server_id as usize),
7686                    cx,
7687                )
7688            })?
7689            .await
7690            .context("inlay hints fetch")?;
7691        Ok(proto::ResolveInlayHintResponse {
7692            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7693        })
7694    }
7695
7696    async fn handle_refresh_inlay_hints(
7697        this: Model<Self>,
7698        _: TypedEnvelope<proto::RefreshInlayHints>,
7699        _: Arc<Client>,
7700        mut cx: AsyncAppContext,
7701    ) -> Result<proto::Ack> {
7702        this.update(&mut cx, |_, cx| {
7703            cx.emit(Event::RefreshInlayHints);
7704        })?;
7705        Ok(proto::Ack {})
7706    }
7707
7708    async fn handle_lsp_command<T: LspCommand>(
7709        this: Model<Self>,
7710        envelope: TypedEnvelope<T::ProtoRequest>,
7711        _: Arc<Client>,
7712        mut cx: AsyncAppContext,
7713    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7714    where
7715        <T::LspRequest as lsp::request::Request>::Params: Send,
7716        <T::LspRequest as lsp::request::Request>::Result: Send,
7717    {
7718        let sender_id = envelope.original_sender_id()?;
7719        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7720        let buffer_handle = this.update(&mut cx, |this, _cx| {
7721            this.opened_buffers
7722                .get(&buffer_id)
7723                .and_then(|buffer| buffer.upgrade())
7724                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7725        })??;
7726        let request = T::from_proto(
7727            envelope.payload,
7728            this.clone(),
7729            buffer_handle.clone(),
7730            cx.clone(),
7731        )
7732        .await?;
7733        let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
7734        let response = this
7735            .update(&mut cx, |this, cx| {
7736                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7737            })?
7738            .await?;
7739        this.update(&mut cx, |this, cx| {
7740            Ok(T::response_to_proto(
7741                response,
7742                this,
7743                sender_id,
7744                &buffer_version,
7745                cx,
7746            ))
7747        })?
7748    }
7749
7750    async fn handle_get_project_symbols(
7751        this: Model<Self>,
7752        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7753        _: Arc<Client>,
7754        mut cx: AsyncAppContext,
7755    ) -> Result<proto::GetProjectSymbolsResponse> {
7756        let symbols = this
7757            .update(&mut cx, |this, cx| {
7758                this.symbols(&envelope.payload.query, cx)
7759            })?
7760            .await?;
7761
7762        Ok(proto::GetProjectSymbolsResponse {
7763            symbols: symbols.iter().map(serialize_symbol).collect(),
7764        })
7765    }
7766
7767    async fn handle_search_project(
7768        this: Model<Self>,
7769        envelope: TypedEnvelope<proto::SearchProject>,
7770        _: Arc<Client>,
7771        mut cx: AsyncAppContext,
7772    ) -> Result<proto::SearchProjectResponse> {
7773        let peer_id = envelope.original_sender_id()?;
7774        let query = SearchQuery::from_proto(envelope.payload)?;
7775        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
7776
7777        cx.spawn(move |mut cx| async move {
7778            let mut locations = Vec::new();
7779            while let Some((buffer, ranges)) = result.next().await {
7780                for range in ranges {
7781                    let start = serialize_anchor(&range.start);
7782                    let end = serialize_anchor(&range.end);
7783                    let buffer_id = this.update(&mut cx, |this, cx| {
7784                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7785                    })?;
7786                    locations.push(proto::Location {
7787                        buffer_id,
7788                        start: Some(start),
7789                        end: Some(end),
7790                    });
7791                }
7792            }
7793            Ok(proto::SearchProjectResponse { locations })
7794        })
7795        .await
7796    }
7797
7798    async fn handle_open_buffer_for_symbol(
7799        this: Model<Self>,
7800        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7801        _: Arc<Client>,
7802        mut cx: AsyncAppContext,
7803    ) -> Result<proto::OpenBufferForSymbolResponse> {
7804        let peer_id = envelope.original_sender_id()?;
7805        let symbol = envelope
7806            .payload
7807            .symbol
7808            .ok_or_else(|| anyhow!("invalid symbol"))?;
7809        let symbol = this
7810            .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
7811            .await?;
7812        let symbol = this.update(&mut cx, |this, _| {
7813            let signature = this.symbol_signature(&symbol.path);
7814            if signature == symbol.signature {
7815                Ok(symbol)
7816            } else {
7817                Err(anyhow!("invalid symbol signature"))
7818            }
7819        })??;
7820        let buffer = this
7821            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
7822            .await?;
7823
7824        Ok(proto::OpenBufferForSymbolResponse {
7825            buffer_id: this.update(&mut cx, |this, cx| {
7826                this.create_buffer_for_peer(&buffer, peer_id, cx)
7827            })?,
7828        })
7829    }
7830
7831    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7832        let mut hasher = Sha256::new();
7833        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7834        hasher.update(project_path.path.to_string_lossy().as_bytes());
7835        hasher.update(self.nonce.to_be_bytes());
7836        hasher.finalize().as_slice().try_into().unwrap()
7837    }
7838
7839    async fn handle_open_buffer_by_id(
7840        this: Model<Self>,
7841        envelope: TypedEnvelope<proto::OpenBufferById>,
7842        _: Arc<Client>,
7843        mut cx: AsyncAppContext,
7844    ) -> Result<proto::OpenBufferResponse> {
7845        let peer_id = envelope.original_sender_id()?;
7846        let buffer = this
7847            .update(&mut cx, |this, cx| {
7848                this.open_buffer_by_id(envelope.payload.id, cx)
7849            })?
7850            .await?;
7851        this.update(&mut cx, |this, cx| {
7852            Ok(proto::OpenBufferResponse {
7853                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7854            })
7855        })?
7856    }
7857
7858    async fn handle_open_buffer_by_path(
7859        this: Model<Self>,
7860        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7861        _: Arc<Client>,
7862        mut cx: AsyncAppContext,
7863    ) -> Result<proto::OpenBufferResponse> {
7864        let peer_id = envelope.original_sender_id()?;
7865        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7866        let open_buffer = this.update(&mut cx, |this, cx| {
7867            this.open_buffer(
7868                ProjectPath {
7869                    worktree_id,
7870                    path: PathBuf::from(envelope.payload.path).into(),
7871                },
7872                cx,
7873            )
7874        })?;
7875
7876        let buffer = open_buffer.await?;
7877        this.update(&mut cx, |this, cx| {
7878            Ok(proto::OpenBufferResponse {
7879                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7880            })
7881        })?
7882    }
7883
7884    fn serialize_project_transaction_for_peer(
7885        &mut self,
7886        project_transaction: ProjectTransaction,
7887        peer_id: proto::PeerId,
7888        cx: &mut AppContext,
7889    ) -> proto::ProjectTransaction {
7890        let mut serialized_transaction = proto::ProjectTransaction {
7891            buffer_ids: Default::default(),
7892            transactions: Default::default(),
7893        };
7894        for (buffer, transaction) in project_transaction.0 {
7895            serialized_transaction
7896                .buffer_ids
7897                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7898            serialized_transaction
7899                .transactions
7900                .push(language::proto::serialize_transaction(&transaction));
7901        }
7902        serialized_transaction
7903    }
7904
7905    fn deserialize_project_transaction(
7906        &mut self,
7907        message: proto::ProjectTransaction,
7908        push_to_history: bool,
7909        cx: &mut ModelContext<Self>,
7910    ) -> Task<Result<ProjectTransaction>> {
7911        cx.spawn(move |this, mut cx| async move {
7912            let mut project_transaction = ProjectTransaction::default();
7913            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7914            {
7915                let buffer = this
7916                    .update(&mut cx, |this, cx| {
7917                        this.wait_for_remote_buffer(buffer_id, cx)
7918                    })?
7919                    .await?;
7920                let transaction = language::proto::deserialize_transaction(transaction)?;
7921                project_transaction.0.insert(buffer, transaction);
7922            }
7923
7924            for (buffer, transaction) in &project_transaction.0 {
7925                buffer
7926                    .update(&mut cx, |buffer, _| {
7927                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7928                    })?
7929                    .await?;
7930
7931                if push_to_history {
7932                    buffer.update(&mut cx, |buffer, _| {
7933                        buffer.push_transaction(transaction.clone(), Instant::now());
7934                    })?;
7935                }
7936            }
7937
7938            Ok(project_transaction)
7939        })
7940    }
7941
7942    fn create_buffer_for_peer(
7943        &mut self,
7944        buffer: &Model<Buffer>,
7945        peer_id: proto::PeerId,
7946        cx: &mut AppContext,
7947    ) -> u64 {
7948        let buffer_id = buffer.read(cx).remote_id();
7949        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7950            updates_tx
7951                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7952                .ok();
7953        }
7954        buffer_id
7955    }
7956
7957    fn wait_for_remote_buffer(
7958        &mut self,
7959        id: u64,
7960        cx: &mut ModelContext<Self>,
7961    ) -> Task<Result<Model<Buffer>>> {
7962        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7963
7964        cx.spawn(move |this, mut cx| async move {
7965            let buffer = loop {
7966                let Some(this) = this.upgrade() else {
7967                    return Err(anyhow!("project dropped"));
7968                };
7969
7970                let buffer = this.update(&mut cx, |this, _cx| {
7971                    this.opened_buffers
7972                        .get(&id)
7973                        .and_then(|buffer| buffer.upgrade())
7974                })?;
7975
7976                if let Some(buffer) = buffer {
7977                    break buffer;
7978                } else if this.update(&mut cx, |this, _| this.is_disconnected())? {
7979                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7980                }
7981
7982                this.update(&mut cx, |this, _| {
7983                    this.incomplete_remote_buffers.entry(id).or_default();
7984                })?;
7985                drop(this);
7986
7987                opened_buffer_rx
7988                    .next()
7989                    .await
7990                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7991            };
7992
7993            Ok(buffer)
7994        })
7995    }
7996
7997    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7998        let project_id = match self.client_state.as_ref() {
7999            Some(ProjectClientState::Remote {
8000                sharing_has_stopped,
8001                remote_id,
8002                ..
8003            }) => {
8004                if *sharing_has_stopped {
8005                    return Task::ready(Err(anyhow!(
8006                        "can't synchronize remote buffers on a readonly project"
8007                    )));
8008                } else {
8009                    *remote_id
8010                }
8011            }
8012            Some(ProjectClientState::Local { .. }) | None => {
8013                return Task::ready(Err(anyhow!(
8014                    "can't synchronize remote buffers on a local project"
8015                )))
8016            }
8017        };
8018
8019        let client = self.client.clone();
8020        cx.spawn(move |this, mut cx| async move {
8021            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
8022                let buffers = this
8023                    .opened_buffers
8024                    .iter()
8025                    .filter_map(|(id, buffer)| {
8026                        let buffer = buffer.upgrade()?;
8027                        Some(proto::BufferVersion {
8028                            id: *id,
8029                            version: language::proto::serialize_version(&buffer.read(cx).version),
8030                        })
8031                    })
8032                    .collect();
8033                let incomplete_buffer_ids = this
8034                    .incomplete_remote_buffers
8035                    .keys()
8036                    .copied()
8037                    .collect::<Vec<_>>();
8038
8039                (buffers, incomplete_buffer_ids)
8040            })?;
8041            let response = client
8042                .request(proto::SynchronizeBuffers {
8043                    project_id,
8044                    buffers,
8045                })
8046                .await?;
8047
8048            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8049                response
8050                    .buffers
8051                    .into_iter()
8052                    .map(|buffer| {
8053                        let client = client.clone();
8054                        let buffer_id = buffer.id;
8055                        let remote_version = language::proto::deserialize_version(&buffer.version);
8056                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
8057                            let operations =
8058                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
8059                            cx.background_executor().spawn(async move {
8060                                let operations = operations.await;
8061                                for chunk in split_operations(operations) {
8062                                    client
8063                                        .request(proto::UpdateBuffer {
8064                                            project_id,
8065                                            buffer_id,
8066                                            operations: chunk,
8067                                        })
8068                                        .await?;
8069                                }
8070                                anyhow::Ok(())
8071                            })
8072                        } else {
8073                            Task::ready(Ok(()))
8074                        }
8075                    })
8076                    .collect::<Vec<_>>()
8077            })?;
8078
8079            // Any incomplete buffers have open requests waiting. Request that the host sends
8080            // creates these buffers for us again to unblock any waiting futures.
8081            for id in incomplete_buffer_ids {
8082                cx.background_executor()
8083                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
8084                    .detach();
8085            }
8086
8087            futures::future::join_all(send_updates_for_buffers)
8088                .await
8089                .into_iter()
8090                .collect()
8091        })
8092    }
8093
8094    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8095        self.worktrees()
8096            .map(|worktree| {
8097                let worktree = worktree.read(cx);
8098                proto::WorktreeMetadata {
8099                    id: worktree.id().to_proto(),
8100                    root_name: worktree.root_name().into(),
8101                    visible: worktree.is_visible(),
8102                    abs_path: worktree.abs_path().to_string_lossy().into(),
8103                }
8104            })
8105            .collect()
8106    }
8107
8108    fn set_worktrees_from_proto(
8109        &mut self,
8110        worktrees: Vec<proto::WorktreeMetadata>,
8111        cx: &mut ModelContext<Project>,
8112    ) -> Result<()> {
8113        let replica_id = self.replica_id();
8114        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8115
8116        let mut old_worktrees_by_id = self
8117            .worktrees
8118            .drain(..)
8119            .filter_map(|worktree| {
8120                let worktree = worktree.upgrade()?;
8121                Some((worktree.read(cx).id(), worktree))
8122            })
8123            .collect::<HashMap<_, _>>();
8124
8125        for worktree in worktrees {
8126            if let Some(old_worktree) =
8127                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8128            {
8129                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8130            } else {
8131                let worktree =
8132                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8133                let _ = self.add_worktree(&worktree, cx);
8134            }
8135        }
8136
8137        self.metadata_changed(cx);
8138        for id in old_worktrees_by_id.keys() {
8139            cx.emit(Event::WorktreeRemoved(*id));
8140        }
8141
8142        Ok(())
8143    }
8144
8145    fn set_collaborators_from_proto(
8146        &mut self,
8147        messages: Vec<proto::Collaborator>,
8148        cx: &mut ModelContext<Self>,
8149    ) -> Result<()> {
8150        let mut collaborators = HashMap::default();
8151        for message in messages {
8152            let collaborator = Collaborator::from_proto(message)?;
8153            collaborators.insert(collaborator.peer_id, collaborator);
8154        }
8155        for old_peer_id in self.collaborators.keys() {
8156            if !collaborators.contains_key(old_peer_id) {
8157                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8158            }
8159        }
8160        self.collaborators = collaborators;
8161        Ok(())
8162    }
8163
8164    fn deserialize_symbol(
8165        &self,
8166        serialized_symbol: proto::Symbol,
8167    ) -> impl Future<Output = Result<Symbol>> {
8168        let languages = self.languages.clone();
8169        async move {
8170            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8171            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8172            let start = serialized_symbol
8173                .start
8174                .ok_or_else(|| anyhow!("invalid start"))?;
8175            let end = serialized_symbol
8176                .end
8177                .ok_or_else(|| anyhow!("invalid end"))?;
8178            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8179            let path = ProjectPath {
8180                worktree_id,
8181                path: PathBuf::from(serialized_symbol.path).into(),
8182            };
8183            let language = languages
8184                .language_for_file(&path.path, None)
8185                .await
8186                .log_err();
8187            Ok(Symbol {
8188                language_server_name: LanguageServerName(
8189                    serialized_symbol.language_server_name.into(),
8190                ),
8191                source_worktree_id,
8192                path,
8193                label: {
8194                    match language {
8195                        Some(language) => {
8196                            language
8197                                .label_for_symbol(&serialized_symbol.name, kind)
8198                                .await
8199                        }
8200                        None => None,
8201                    }
8202                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8203                },
8204
8205                name: serialized_symbol.name,
8206                range: Unclipped(PointUtf16::new(start.row, start.column))
8207                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8208                kind,
8209                signature: serialized_symbol
8210                    .signature
8211                    .try_into()
8212                    .map_err(|_| anyhow!("invalid signature"))?,
8213            })
8214        }
8215    }
8216
8217    async fn handle_buffer_saved(
8218        this: Model<Self>,
8219        envelope: TypedEnvelope<proto::BufferSaved>,
8220        _: Arc<Client>,
8221        mut cx: AsyncAppContext,
8222    ) -> Result<()> {
8223        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8224        let version = deserialize_version(&envelope.payload.version);
8225        let mtime = envelope
8226            .payload
8227            .mtime
8228            .ok_or_else(|| anyhow!("missing mtime"))?
8229            .into();
8230
8231        this.update(&mut cx, |this, cx| {
8232            let buffer = this
8233                .opened_buffers
8234                .get(&envelope.payload.buffer_id)
8235                .and_then(|buffer| buffer.upgrade())
8236                .or_else(|| {
8237                    this.incomplete_remote_buffers
8238                        .get(&envelope.payload.buffer_id)
8239                        .and_then(|b| b.clone())
8240                });
8241            if let Some(buffer) = buffer {
8242                buffer.update(cx, |buffer, cx| {
8243                    buffer.did_save(version, fingerprint, mtime, cx);
8244                });
8245            }
8246            Ok(())
8247        })?
8248    }
8249
8250    async fn handle_buffer_reloaded(
8251        this: Model<Self>,
8252        envelope: TypedEnvelope<proto::BufferReloaded>,
8253        _: Arc<Client>,
8254        mut cx: AsyncAppContext,
8255    ) -> Result<()> {
8256        let payload = envelope.payload;
8257        let version = deserialize_version(&payload.version);
8258        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8259        let line_ending = deserialize_line_ending(
8260            proto::LineEnding::from_i32(payload.line_ending)
8261                .ok_or_else(|| anyhow!("missing line ending"))?,
8262        );
8263        let mtime = payload
8264            .mtime
8265            .ok_or_else(|| anyhow!("missing mtime"))?
8266            .into();
8267        this.update(&mut cx, |this, cx| {
8268            let buffer = this
8269                .opened_buffers
8270                .get(&payload.buffer_id)
8271                .and_then(|buffer| buffer.upgrade())
8272                .or_else(|| {
8273                    this.incomplete_remote_buffers
8274                        .get(&payload.buffer_id)
8275                        .cloned()
8276                        .flatten()
8277                });
8278            if let Some(buffer) = buffer {
8279                buffer.update(cx, |buffer, cx| {
8280                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8281                });
8282            }
8283            Ok(())
8284        })?
8285    }
8286
8287    #[allow(clippy::type_complexity)]
8288    fn edits_from_lsp(
8289        &mut self,
8290        buffer: &Model<Buffer>,
8291        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8292        server_id: LanguageServerId,
8293        version: Option<i32>,
8294        cx: &mut ModelContext<Self>,
8295    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8296        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8297        cx.background_executor().spawn(async move {
8298            let snapshot = snapshot?;
8299            let mut lsp_edits = lsp_edits
8300                .into_iter()
8301                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8302                .collect::<Vec<_>>();
8303            lsp_edits.sort_by_key(|(range, _)| range.start);
8304
8305            let mut lsp_edits = lsp_edits.into_iter().peekable();
8306            let mut edits = Vec::new();
8307            while let Some((range, mut new_text)) = lsp_edits.next() {
8308                // Clip invalid ranges provided by the language server.
8309                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8310                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8311
8312                // Combine any LSP edits that are adjacent.
8313                //
8314                // Also, combine LSP edits that are separated from each other by only
8315                // a newline. This is important because for some code actions,
8316                // Rust-analyzer rewrites the entire buffer via a series of edits that
8317                // are separated by unchanged newline characters.
8318                //
8319                // In order for the diffing logic below to work properly, any edits that
8320                // cancel each other out must be combined into one.
8321                while let Some((next_range, next_text)) = lsp_edits.peek() {
8322                    if next_range.start.0 > range.end {
8323                        if next_range.start.0.row > range.end.row + 1
8324                            || next_range.start.0.column > 0
8325                            || snapshot.clip_point_utf16(
8326                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8327                                Bias::Left,
8328                            ) > range.end
8329                        {
8330                            break;
8331                        }
8332                        new_text.push('\n');
8333                    }
8334                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8335                    new_text.push_str(next_text);
8336                    lsp_edits.next();
8337                }
8338
8339                // For multiline edits, perform a diff of the old and new text so that
8340                // we can identify the changes more precisely, preserving the locations
8341                // of any anchors positioned in the unchanged regions.
8342                if range.end.row > range.start.row {
8343                    let mut offset = range.start.to_offset(&snapshot);
8344                    let old_text = snapshot.text_for_range(range).collect::<String>();
8345
8346                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8347                    let mut moved_since_edit = true;
8348                    for change in diff.iter_all_changes() {
8349                        let tag = change.tag();
8350                        let value = change.value();
8351                        match tag {
8352                            ChangeTag::Equal => {
8353                                offset += value.len();
8354                                moved_since_edit = true;
8355                            }
8356                            ChangeTag::Delete => {
8357                                let start = snapshot.anchor_after(offset);
8358                                let end = snapshot.anchor_before(offset + value.len());
8359                                if moved_since_edit {
8360                                    edits.push((start..end, String::new()));
8361                                } else {
8362                                    edits.last_mut().unwrap().0.end = end;
8363                                }
8364                                offset += value.len();
8365                                moved_since_edit = false;
8366                            }
8367                            ChangeTag::Insert => {
8368                                if moved_since_edit {
8369                                    let anchor = snapshot.anchor_after(offset);
8370                                    edits.push((anchor..anchor, value.to_string()));
8371                                } else {
8372                                    edits.last_mut().unwrap().1.push_str(value);
8373                                }
8374                                moved_since_edit = false;
8375                            }
8376                        }
8377                    }
8378                } else if range.end == range.start {
8379                    let anchor = snapshot.anchor_after(range.start);
8380                    edits.push((anchor..anchor, new_text));
8381                } else {
8382                    let edit_start = snapshot.anchor_after(range.start);
8383                    let edit_end = snapshot.anchor_before(range.end);
8384                    edits.push((edit_start..edit_end, new_text));
8385                }
8386            }
8387
8388            Ok(edits)
8389        })
8390    }
8391
8392    fn buffer_snapshot_for_lsp_version(
8393        &mut self,
8394        buffer: &Model<Buffer>,
8395        server_id: LanguageServerId,
8396        version: Option<i32>,
8397        cx: &AppContext,
8398    ) -> Result<TextBufferSnapshot> {
8399        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8400
8401        if let Some(version) = version {
8402            let buffer_id = buffer.read(cx).remote_id();
8403            let snapshots = self
8404                .buffer_snapshots
8405                .get_mut(&buffer_id)
8406                .and_then(|m| m.get_mut(&server_id))
8407                .ok_or_else(|| {
8408                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8409                })?;
8410
8411            let found_snapshot = snapshots
8412                .binary_search_by_key(&version, |e| e.version)
8413                .map(|ix| snapshots[ix].snapshot.clone())
8414                .map_err(|_| {
8415                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8416                })?;
8417
8418            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8419            Ok(found_snapshot)
8420        } else {
8421            Ok((buffer.read(cx)).text_snapshot())
8422        }
8423    }
8424
8425    pub fn language_servers(
8426        &self,
8427    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8428        self.language_server_ids
8429            .iter()
8430            .map(|((worktree_id, server_name), server_id)| {
8431                (*server_id, server_name.clone(), *worktree_id)
8432            })
8433    }
8434
8435    pub fn supplementary_language_servers(
8436        &self,
8437    ) -> impl '_
8438           + Iterator<
8439        Item = (
8440            &LanguageServerId,
8441            &(LanguageServerName, Arc<LanguageServer>),
8442        ),
8443    > {
8444        self.supplementary_language_servers.iter()
8445    }
8446
8447    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8448        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8449            Some(server.clone())
8450        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8451            Some(Arc::clone(server))
8452        } else {
8453            None
8454        }
8455    }
8456
8457    pub fn language_servers_for_buffer(
8458        &self,
8459        buffer: &Buffer,
8460        cx: &AppContext,
8461    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8462        self.language_server_ids_for_buffer(buffer, cx)
8463            .into_iter()
8464            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8465                LanguageServerState::Running {
8466                    adapter, server, ..
8467                } => Some((adapter, server)),
8468                _ => None,
8469            })
8470    }
8471
8472    fn primary_language_server_for_buffer(
8473        &self,
8474        buffer: &Buffer,
8475        cx: &AppContext,
8476    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8477        self.language_servers_for_buffer(buffer, cx).next()
8478    }
8479
8480    pub fn language_server_for_buffer(
8481        &self,
8482        buffer: &Buffer,
8483        server_id: LanguageServerId,
8484        cx: &AppContext,
8485    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8486        self.language_servers_for_buffer(buffer, cx)
8487            .find(|(_, s)| s.server_id() == server_id)
8488    }
8489
8490    fn language_server_ids_for_buffer(
8491        &self,
8492        buffer: &Buffer,
8493        cx: &AppContext,
8494    ) -> Vec<LanguageServerId> {
8495        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8496            let worktree_id = file.worktree_id(cx);
8497            language
8498                .lsp_adapters()
8499                .iter()
8500                .flat_map(|adapter| {
8501                    let key = (worktree_id, adapter.name.clone());
8502                    self.language_server_ids.get(&key).copied()
8503                })
8504                .collect()
8505        } else {
8506            Vec::new()
8507        }
8508    }
8509}
8510
8511fn subscribe_for_copilot_events(
8512    copilot: &Model<Copilot>,
8513    cx: &mut ModelContext<'_, Project>,
8514) -> gpui::Subscription {
8515    cx.subscribe(
8516        copilot,
8517        |project, copilot, copilot_event, cx| match copilot_event {
8518            copilot::Event::CopilotLanguageServerStarted => {
8519                match copilot.read(cx).language_server() {
8520                    Some((name, copilot_server)) => {
8521                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8522                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8523                            let new_server_id = copilot_server.server_id();
8524                            let weak_project = cx.weak_model();
8525                            let copilot_log_subscription = copilot_server
8526                                .on_notification::<copilot::request::LogMessage, _>(
8527                                    move |params, mut cx| {
8528                                        weak_project.update(&mut cx, |_, cx| {
8529                                            cx.emit(Event::LanguageServerLog(
8530                                                new_server_id,
8531                                                params.message,
8532                                            ));
8533                                        }).ok();
8534                                    },
8535                                );
8536                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8537                            project.copilot_log_subscription = Some(copilot_log_subscription);
8538                            cx.emit(Event::LanguageServerAdded(new_server_id));
8539                        }
8540                    }
8541                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8542                }
8543            }
8544        },
8545    )
8546}
8547
8548fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8549    let mut literal_end = 0;
8550    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8551        if part.contains(&['*', '?', '{', '}']) {
8552            break;
8553        } else {
8554            if i > 0 {
8555                // Acount for separator prior to this part
8556                literal_end += path::MAIN_SEPARATOR.len_utf8();
8557            }
8558            literal_end += part.len();
8559        }
8560    }
8561    &glob[..literal_end]
8562}
8563
8564impl WorktreeHandle {
8565    pub fn upgrade(&self) -> Option<Model<Worktree>> {
8566        match self {
8567            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8568            WorktreeHandle::Weak(handle) => handle.upgrade(),
8569        }
8570    }
8571
8572    pub fn handle_id(&self) -> usize {
8573        match self {
8574            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
8575            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
8576        }
8577    }
8578}
8579
8580impl OpenBuffer {
8581    pub fn upgrade(&self) -> Option<Model<Buffer>> {
8582        match self {
8583            OpenBuffer::Strong(handle) => Some(handle.clone()),
8584            OpenBuffer::Weak(handle) => handle.upgrade(),
8585            OpenBuffer::Operations(_) => None,
8586        }
8587    }
8588}
8589
8590pub struct PathMatchCandidateSet {
8591    pub snapshot: Snapshot,
8592    pub include_ignored: bool,
8593    pub include_root_name: bool,
8594}
8595
8596impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8597    type Candidates = PathMatchCandidateSetIter<'a>;
8598
8599    fn id(&self) -> usize {
8600        self.snapshot.id().to_usize()
8601    }
8602
8603    fn len(&self) -> usize {
8604        if self.include_ignored {
8605            self.snapshot.file_count()
8606        } else {
8607            self.snapshot.visible_file_count()
8608        }
8609    }
8610
8611    fn prefix(&self) -> Arc<str> {
8612        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8613            self.snapshot.root_name().into()
8614        } else if self.include_root_name {
8615            format!("{}/", self.snapshot.root_name()).into()
8616        } else {
8617            "".into()
8618        }
8619    }
8620
8621    fn candidates(&'a self, start: usize) -> Self::Candidates {
8622        PathMatchCandidateSetIter {
8623            traversal: self.snapshot.files(self.include_ignored, start),
8624        }
8625    }
8626}
8627
8628pub struct PathMatchCandidateSetIter<'a> {
8629    traversal: Traversal<'a>,
8630}
8631
8632impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8633    type Item = fuzzy::PathMatchCandidate<'a>;
8634
8635    fn next(&mut self) -> Option<Self::Item> {
8636        self.traversal.next().map(|entry| {
8637            if let EntryKind::File(char_bag) = entry.kind {
8638                fuzzy::PathMatchCandidate {
8639                    path: &entry.path,
8640                    char_bag,
8641                }
8642            } else {
8643                unreachable!()
8644            }
8645        })
8646    }
8647}
8648
8649impl EventEmitter<Event> for Project {}
8650
8651impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8652    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8653        Self {
8654            worktree_id,
8655            path: path.as_ref().into(),
8656        }
8657    }
8658}
8659
8660impl ProjectLspAdapterDelegate {
8661    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8662        Arc::new(Self {
8663            project: cx.handle(),
8664            http_client: project.client.http_client(),
8665        })
8666    }
8667}
8668
8669impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8670    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8671        self.project
8672            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8673    }
8674
8675    fn http_client(&self) -> Arc<dyn HttpClient> {
8676        self.http_client.clone()
8677    }
8678}
8679
8680fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8681    proto::Symbol {
8682        language_server_name: symbol.language_server_name.0.to_string(),
8683        source_worktree_id: symbol.source_worktree_id.to_proto(),
8684        worktree_id: symbol.path.worktree_id.to_proto(),
8685        path: symbol.path.path.to_string_lossy().to_string(),
8686        name: symbol.name.clone(),
8687        kind: unsafe { mem::transmute(symbol.kind) },
8688        start: Some(proto::PointUtf16 {
8689            row: symbol.range.start.0.row,
8690            column: symbol.range.start.0.column,
8691        }),
8692        end: Some(proto::PointUtf16 {
8693            row: symbol.range.end.0.row,
8694            column: symbol.range.end.0.column,
8695        }),
8696        signature: symbol.signature.to_vec(),
8697    }
8698}
8699
8700fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8701    let mut path_components = path.components();
8702    let mut base_components = base.components();
8703    let mut components: Vec<Component> = Vec::new();
8704    loop {
8705        match (path_components.next(), base_components.next()) {
8706            (None, None) => break,
8707            (Some(a), None) => {
8708                components.push(a);
8709                components.extend(path_components.by_ref());
8710                break;
8711            }
8712            (None, _) => components.push(Component::ParentDir),
8713            (Some(a), Some(b)) if components.is_empty() && a == b => (),
8714            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8715            (Some(a), Some(_)) => {
8716                components.push(Component::ParentDir);
8717                for _ in base_components {
8718                    components.push(Component::ParentDir);
8719                }
8720                components.push(a);
8721                components.extend(path_components.by_ref());
8722                break;
8723            }
8724        }
8725    }
8726    components.iter().map(|c| c.as_os_str()).collect()
8727}
8728
8729fn resolve_path(base: &Path, path: &Path) -> PathBuf {
8730    let mut result = base.to_path_buf();
8731    for component in path.components() {
8732        match component {
8733            Component::ParentDir => {
8734                result.pop();
8735            }
8736            Component::CurDir => (),
8737            _ => result.push(component),
8738        }
8739    }
8740    result
8741}
8742
8743impl Item for Buffer {
8744    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8745        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8746    }
8747
8748    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8749        File::from_dyn(self.file()).map(|file| ProjectPath {
8750            worktree_id: file.worktree_id(cx),
8751            path: file.path().clone(),
8752        })
8753    }
8754}
8755
8756async fn wait_for_loading_buffer(
8757    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
8758) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
8759    loop {
8760        if let Some(result) = receiver.borrow().as_ref() {
8761            match result {
8762                Ok(buffer) => return Ok(buffer.to_owned()),
8763                Err(e) => return Err(e.to_owned()),
8764            }
8765        }
8766        receiver.next().await;
8767    }
8768}
8769
8770fn include_text(server: &lsp::LanguageServer) -> bool {
8771    server
8772        .capabilities()
8773        .text_document_sync
8774        .as_ref()
8775        .and_then(|sync| match sync {
8776            lsp::TextDocumentSyncCapability::Kind(_) => None,
8777            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
8778        })
8779        .and_then(|save_options| match save_options {
8780            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
8781            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
8782        })
8783        .unwrap_or(false)
8784}