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