project.rs

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