project.rs

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