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