project2.rs

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