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