project.rs

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