project.rs

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