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