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