project2.rs

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