project.rs

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