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