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