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