project.rs

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