project.rs

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