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
5622            .iter()
5623            .map(|s| {
5624                if query.include_ignored() {
5625                    s.file_count()
5626                } else {
5627                    s.visible_file_count()
5628                }
5629            })
5630            .sum();
5631        if path_count == 0 {
5632            let (_, rx) = smol::channel::bounded(1024);
5633            return rx;
5634        }
5635        let workers = background.num_cpus().min(path_count);
5636        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5637        let mut unnamed_files = vec![];
5638        let opened_buffers = self
5639            .opened_buffers
5640            .iter()
5641            .filter_map(|(_, b)| {
5642                let buffer = b.upgrade()?;
5643                let (is_ignored, snapshot) = buffer.update(cx, |buffer, cx| {
5644                    let is_ignored = buffer
5645                        .project_path(cx)
5646                        .and_then(|path| self.entry_for_path(&path, cx))
5647                        .map_or(false, |entry| entry.is_ignored);
5648                    (is_ignored, buffer.snapshot())
5649                });
5650                if is_ignored && !query.include_ignored() {
5651                    return None;
5652                } else if let Some(path) = snapshot.file().map(|file| file.path()) {
5653                    Some((path.clone(), (buffer, snapshot)))
5654                } else {
5655                    unnamed_files.push(buffer);
5656                    None
5657                }
5658            })
5659            .collect();
5660        cx.background_executor()
5661            .spawn(Self::background_search(
5662                unnamed_files,
5663                opened_buffers,
5664                cx.background_executor().clone(),
5665                self.fs.clone(),
5666                workers,
5667                query.clone(),
5668                path_count,
5669                snapshots,
5670                matching_paths_tx,
5671            ))
5672            .detach();
5673
5674        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5675        let background = cx.background_executor().clone();
5676        let (result_tx, result_rx) = smol::channel::bounded(1024);
5677        cx.background_executor()
5678            .spawn(async move {
5679                let Ok(buffers) = buffers.await else {
5680                    return;
5681                };
5682
5683                let buffers_len = buffers.len();
5684                if buffers_len == 0 {
5685                    return;
5686                }
5687                let query = &query;
5688                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5689                background
5690                    .scoped(|scope| {
5691                        #[derive(Clone)]
5692                        struct FinishedStatus {
5693                            entry: Option<(Model<Buffer>, Vec<Range<Anchor>>)>,
5694                            buffer_index: SearchMatchCandidateIndex,
5695                        }
5696
5697                        for _ in 0..workers {
5698                            let finished_tx = finished_tx.clone();
5699                            let mut buffers_rx = buffers_rx.clone();
5700                            scope.spawn(async move {
5701                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5702                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5703                                    {
5704                                        if query.file_matches(
5705                                            snapshot.file().map(|file| file.path().as_ref()),
5706                                        ) {
5707                                            query
5708                                                .search(&snapshot, None)
5709                                                .await
5710                                                .iter()
5711                                                .map(|range| {
5712                                                    snapshot.anchor_before(range.start)
5713                                                        ..snapshot.anchor_after(range.end)
5714                                                })
5715                                                .collect()
5716                                        } else {
5717                                            Vec::new()
5718                                        }
5719                                    } else {
5720                                        Vec::new()
5721                                    };
5722
5723                                    let status = if !buffer_matches.is_empty() {
5724                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5725                                            Some((buffer.clone(), buffer_matches))
5726                                        } else {
5727                                            None
5728                                        };
5729                                        FinishedStatus {
5730                                            entry,
5731                                            buffer_index,
5732                                        }
5733                                    } else {
5734                                        FinishedStatus {
5735                                            entry: None,
5736                                            buffer_index,
5737                                        }
5738                                    };
5739                                    if finished_tx.send(status).await.is_err() {
5740                                        break;
5741                                    }
5742                                }
5743                            });
5744                        }
5745                        // Report sorted matches
5746                        scope.spawn(async move {
5747                            let mut current_index = 0;
5748                            let mut scratch = vec![None; buffers_len];
5749                            while let Some(status) = finished_rx.next().await {
5750                                debug_assert!(
5751                                    scratch[status.buffer_index].is_none(),
5752                                    "Got match status of position {} twice",
5753                                    status.buffer_index
5754                                );
5755                                let index = status.buffer_index;
5756                                scratch[index] = Some(status);
5757                                while current_index < buffers_len {
5758                                    let Some(current_entry) = scratch[current_index].take() else {
5759                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5760                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5761                                        // this time.
5762                                        break;
5763                                    };
5764                                    if let Some(entry) = current_entry.entry {
5765                                        result_tx.send(entry).await.log_err();
5766                                    }
5767                                    current_index += 1;
5768                                }
5769                                if current_index == buffers_len {
5770                                    break;
5771                                }
5772                            }
5773                        });
5774                    })
5775                    .await;
5776            })
5777            .detach();
5778        result_rx
5779    }
5780
5781    /// Pick paths that might potentially contain a match of a given search query.
5782    async fn background_search(
5783        unnamed_buffers: Vec<Model<Buffer>>,
5784        opened_buffers: HashMap<Arc<Path>, (Model<Buffer>, BufferSnapshot)>,
5785        executor: BackgroundExecutor,
5786        fs: Arc<dyn Fs>,
5787        workers: usize,
5788        query: SearchQuery,
5789        path_count: usize,
5790        snapshots: Vec<LocalSnapshot>,
5791        matching_paths_tx: Sender<SearchMatchCandidate>,
5792    ) {
5793        let fs = &fs;
5794        let query = &query;
5795        let matching_paths_tx = &matching_paths_tx;
5796        let snapshots = &snapshots;
5797        let paths_per_worker = (path_count + workers - 1) / workers;
5798        for buffer in unnamed_buffers {
5799            matching_paths_tx
5800                .send(SearchMatchCandidate::OpenBuffer {
5801                    buffer: buffer.clone(),
5802                    path: None,
5803                })
5804                .await
5805                .log_err();
5806        }
5807        for (path, (buffer, _)) in opened_buffers.iter() {
5808            matching_paths_tx
5809                .send(SearchMatchCandidate::OpenBuffer {
5810                    buffer: buffer.clone(),
5811                    path: Some(path.clone()),
5812                })
5813                .await
5814                .log_err();
5815        }
5816        executor
5817            .scoped(|scope| {
5818                for worker_ix in 0..workers {
5819                    let worker_start_ix = worker_ix * paths_per_worker;
5820                    let worker_end_ix = worker_start_ix + paths_per_worker;
5821                    let unnamed_buffers = opened_buffers.clone();
5822                    scope.spawn(async move {
5823                        let mut snapshot_start_ix = 0;
5824                        let mut abs_path = PathBuf::new();
5825                        for snapshot in snapshots {
5826                            let snapshot_end_ix = snapshot_start_ix
5827                                + if query.include_ignored() {
5828                                    snapshot.file_count()
5829                                } else {
5830                                    snapshot.visible_file_count()
5831                                };
5832                            if worker_end_ix <= snapshot_start_ix {
5833                                break;
5834                            } else if worker_start_ix > snapshot_end_ix {
5835                                snapshot_start_ix = snapshot_end_ix;
5836                                continue;
5837                            } else {
5838                                let start_in_snapshot =
5839                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5840                                let end_in_snapshot =
5841                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5842
5843                                for entry in snapshot
5844                                    .files(query.include_ignored(), start_in_snapshot)
5845                                    .take(end_in_snapshot - start_in_snapshot)
5846                                {
5847                                    if matching_paths_tx.is_closed() {
5848                                        break;
5849                                    }
5850                                    if unnamed_buffers.contains_key(&entry.path) {
5851                                        continue;
5852                                    }
5853                                    let matches = if query.file_matches(Some(&entry.path)) {
5854                                        abs_path.clear();
5855                                        abs_path.push(&snapshot.abs_path());
5856                                        abs_path.push(&entry.path);
5857                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5858                                        {
5859                                            query.detect(file).unwrap_or(false)
5860                                        } else {
5861                                            false
5862                                        }
5863                                    } else {
5864                                        false
5865                                    };
5866
5867                                    if matches {
5868                                        let project_path = SearchMatchCandidate::Path {
5869                                            worktree_id: snapshot.id(),
5870                                            path: entry.path.clone(),
5871                                        };
5872                                        if matching_paths_tx.send(project_path).await.is_err() {
5873                                            break;
5874                                        }
5875                                    }
5876                                }
5877
5878                                snapshot_start_ix = snapshot_end_ix;
5879                            }
5880                        }
5881                    });
5882                }
5883            })
5884            .await;
5885    }
5886
5887    fn request_lsp<R: LspCommand>(
5888        &self,
5889        buffer_handle: Model<Buffer>,
5890        server: LanguageServerToQuery,
5891        request: R,
5892        cx: &mut ModelContext<Self>,
5893    ) -> Task<Result<R::Response>>
5894    where
5895        <R::LspRequest as lsp::request::Request>::Result: Send,
5896        <R::LspRequest as lsp::request::Request>::Params: Send,
5897    {
5898        let buffer = buffer_handle.read(cx);
5899        if self.is_local() {
5900            let language_server = match server {
5901                LanguageServerToQuery::Primary => {
5902                    match self.primary_language_server_for_buffer(buffer, cx) {
5903                        Some((_, server)) => Some(Arc::clone(server)),
5904                        None => return Task::ready(Ok(Default::default())),
5905                    }
5906                }
5907                LanguageServerToQuery::Other(id) => self
5908                    .language_server_for_buffer(buffer, id, cx)
5909                    .map(|(_, server)| Arc::clone(server)),
5910            };
5911            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5912            if let (Some(file), Some(language_server)) = (file, language_server) {
5913                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5914                return cx.spawn(move |this, cx| async move {
5915                    if !request.check_capabilities(language_server.capabilities()) {
5916                        return Ok(Default::default());
5917                    }
5918
5919                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5920                    let response = match result {
5921                        Ok(response) => response,
5922
5923                        Err(err) => {
5924                            log::warn!(
5925                                "Generic lsp request to {} failed: {}",
5926                                language_server.name(),
5927                                err
5928                            );
5929                            return Err(err);
5930                        }
5931                    };
5932
5933                    request
5934                        .response_from_lsp(
5935                            response,
5936                            this.upgrade().ok_or_else(|| anyhow!("no app context"))?,
5937                            buffer_handle,
5938                            language_server.server_id(),
5939                            cx,
5940                        )
5941                        .await
5942                });
5943            }
5944        } else if let Some(project_id) = self.remote_id() {
5945            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
5946        }
5947
5948        Task::ready(Ok(Default::default()))
5949    }
5950
5951    fn send_lsp_proto_request<R: LspCommand>(
5952        &self,
5953        buffer: Model<Buffer>,
5954        project_id: u64,
5955        request: R,
5956        cx: &mut ModelContext<'_, Project>,
5957    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
5958        let rpc = self.client.clone();
5959        let message = request.to_proto(project_id, buffer.read(cx));
5960        cx.spawn(move |this, mut cx| async move {
5961            // Ensure the project is still alive by the time the task
5962            // is scheduled.
5963            this.upgrade().context("project dropped")?;
5964            let response = rpc.request(message).await?;
5965            let this = this.upgrade().context("project dropped")?;
5966            if this.update(&mut cx, |this, _| this.is_read_only())? {
5967                Err(anyhow!("disconnected before completing request"))
5968            } else {
5969                request
5970                    .response_from_proto(response, this, buffer, cx)
5971                    .await
5972            }
5973        })
5974    }
5975
5976    fn sort_candidates_and_open_buffers(
5977        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
5978        cx: &mut ModelContext<Self>,
5979    ) -> (
5980        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
5981        Receiver<(
5982            Option<(Model<Buffer>, BufferSnapshot)>,
5983            SearchMatchCandidateIndex,
5984        )>,
5985    ) {
5986        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5987        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
5988        cx.spawn(move |this, cx| async move {
5989            let mut buffers = vec![];
5990            while let Some(entry) = matching_paths_rx.next().await {
5991                buffers.push(entry);
5992            }
5993            buffers.sort_by_key(|candidate| candidate.path());
5994            let matching_paths = buffers.clone();
5995            let _ = sorted_buffers_tx.send(buffers);
5996            for (index, candidate) in matching_paths.into_iter().enumerate() {
5997                if buffers_tx.is_closed() {
5998                    break;
5999                }
6000                let this = this.clone();
6001                let buffers_tx = buffers_tx.clone();
6002                cx.spawn(move |mut cx| async move {
6003                    let buffer = match candidate {
6004                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
6005                        SearchMatchCandidate::Path { worktree_id, path } => this
6006                            .update(&mut cx, |this, cx| {
6007                                this.open_buffer((worktree_id, path), cx)
6008                            })?
6009                            .await
6010                            .log_err(),
6011                    };
6012                    if let Some(buffer) = buffer {
6013                        let snapshot = buffer.update(&mut cx, |buffer, _| buffer.snapshot())?;
6014                        buffers_tx
6015                            .send((Some((buffer, snapshot)), index))
6016                            .await
6017                            .log_err();
6018                    } else {
6019                        buffers_tx.send((None, index)).await.log_err();
6020                    }
6021
6022                    Ok::<_, anyhow::Error>(())
6023                })
6024                .detach();
6025            }
6026        })
6027        .detach();
6028        (sorted_buffers_rx, buffers_rx)
6029    }
6030
6031    pub fn find_or_create_local_worktree(
6032        &mut self,
6033        abs_path: impl AsRef<Path>,
6034        visible: bool,
6035        cx: &mut ModelContext<Self>,
6036    ) -> Task<Result<(Model<Worktree>, PathBuf)>> {
6037        let abs_path = abs_path.as_ref();
6038        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
6039            Task::ready(Ok((tree, relative_path)))
6040        } else {
6041            let worktree = self.create_local_worktree(abs_path, visible, cx);
6042            cx.background_executor()
6043                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
6044        }
6045    }
6046
6047    pub fn find_local_worktree(
6048        &self,
6049        abs_path: &Path,
6050        cx: &AppContext,
6051    ) -> Option<(Model<Worktree>, PathBuf)> {
6052        for tree in &self.worktrees {
6053            if let Some(tree) = tree.upgrade() {
6054                if let Some(relative_path) = tree
6055                    .read(cx)
6056                    .as_local()
6057                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
6058                {
6059                    return Some((tree.clone(), relative_path.into()));
6060                }
6061            }
6062        }
6063        None
6064    }
6065
6066    pub fn is_shared(&self) -> bool {
6067        match &self.client_state {
6068            Some(ProjectClientState::Local { .. }) => true,
6069            _ => false,
6070        }
6071    }
6072
6073    fn create_local_worktree(
6074        &mut self,
6075        abs_path: impl AsRef<Path>,
6076        visible: bool,
6077        cx: &mut ModelContext<Self>,
6078    ) -> Task<Result<Model<Worktree>>> {
6079        let fs = self.fs.clone();
6080        let client = self.client.clone();
6081        let next_entry_id = self.next_entry_id.clone();
6082        let path: Arc<Path> = abs_path.as_ref().into();
6083        let task = self
6084            .loading_local_worktrees
6085            .entry(path.clone())
6086            .or_insert_with(|| {
6087                cx.spawn(move |project, mut cx| {
6088                    async move {
6089                        let worktree = Worktree::local(
6090                            client.clone(),
6091                            path.clone(),
6092                            visible,
6093                            fs,
6094                            next_entry_id,
6095                            &mut cx,
6096                        )
6097                        .await;
6098
6099                        project.update(&mut cx, |project, _| {
6100                            project.loading_local_worktrees.remove(&path);
6101                        })?;
6102
6103                        let worktree = worktree?;
6104                        project
6105                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))?;
6106                        Ok(worktree)
6107                    }
6108                    .map_err(Arc::new)
6109                })
6110                .shared()
6111            })
6112            .clone();
6113        cx.background_executor().spawn(async move {
6114            match task.await {
6115                Ok(worktree) => Ok(worktree),
6116                Err(err) => Err(anyhow!("{}", err)),
6117            }
6118        })
6119    }
6120
6121    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6122        self.worktrees.retain(|worktree| {
6123            if let Some(worktree) = worktree.upgrade() {
6124                let id = worktree.read(cx).id();
6125                if id == id_to_remove {
6126                    cx.emit(Event::WorktreeRemoved(id));
6127                    false
6128                } else {
6129                    true
6130                }
6131            } else {
6132                false
6133            }
6134        });
6135        self.metadata_changed(cx);
6136    }
6137
6138    fn add_worktree(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
6139        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6140        if worktree.read(cx).is_local() {
6141            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6142                worktree::Event::UpdatedEntries(changes) => {
6143                    this.update_local_worktree_buffers(&worktree, changes, cx);
6144                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6145                    this.update_local_worktree_settings(&worktree, changes, cx);
6146                    this.update_prettier_settings(&worktree, changes, cx);
6147                    cx.emit(Event::WorktreeUpdatedEntries(
6148                        worktree.read(cx).id(),
6149                        changes.clone(),
6150                    ));
6151                }
6152                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6153                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6154                }
6155            })
6156            .detach();
6157        }
6158
6159        let push_strong_handle = {
6160            let worktree = worktree.read(cx);
6161            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6162        };
6163        if push_strong_handle {
6164            self.worktrees
6165                .push(WorktreeHandle::Strong(worktree.clone()));
6166        } else {
6167            self.worktrees
6168                .push(WorktreeHandle::Weak(worktree.downgrade()));
6169        }
6170
6171        let handle_id = worktree.entity_id();
6172        cx.observe_release(worktree, move |this, worktree, cx| {
6173            let _ = this.remove_worktree(worktree.id(), cx);
6174            cx.update_global::<SettingsStore, _>(|store, cx| {
6175                store
6176                    .clear_local_settings(handle_id.as_u64() as usize, cx)
6177                    .log_err()
6178            });
6179        })
6180        .detach();
6181
6182        cx.emit(Event::WorktreeAdded);
6183        self.metadata_changed(cx);
6184    }
6185
6186    fn update_local_worktree_buffers(
6187        &mut self,
6188        worktree_handle: &Model<Worktree>,
6189        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6190        cx: &mut ModelContext<Self>,
6191    ) {
6192        let snapshot = worktree_handle.read(cx).snapshot();
6193
6194        let mut renamed_buffers = Vec::new();
6195        for (path, entry_id, _) in changes {
6196            let worktree_id = worktree_handle.read(cx).id();
6197            let project_path = ProjectPath {
6198                worktree_id,
6199                path: path.clone(),
6200            };
6201
6202            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6203                Some(&buffer_id) => buffer_id,
6204                None => match self.local_buffer_ids_by_path.get(&project_path) {
6205                    Some(&buffer_id) => buffer_id,
6206                    None => {
6207                        continue;
6208                    }
6209                },
6210            };
6211
6212            let open_buffer = self.opened_buffers.get(&buffer_id);
6213            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade()) {
6214                buffer
6215            } else {
6216                self.opened_buffers.remove(&buffer_id);
6217                self.local_buffer_ids_by_path.remove(&project_path);
6218                self.local_buffer_ids_by_entry_id.remove(entry_id);
6219                continue;
6220            };
6221
6222            buffer.update(cx, |buffer, cx| {
6223                if let Some(old_file) = File::from_dyn(buffer.file()) {
6224                    if old_file.worktree != *worktree_handle {
6225                        return;
6226                    }
6227
6228                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
6229                        File {
6230                            is_local: true,
6231                            entry_id: entry.id,
6232                            mtime: entry.mtime,
6233                            path: entry.path.clone(),
6234                            worktree: worktree_handle.clone(),
6235                            is_deleted: false,
6236                        }
6237                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6238                        File {
6239                            is_local: true,
6240                            entry_id: entry.id,
6241                            mtime: entry.mtime,
6242                            path: entry.path.clone(),
6243                            worktree: worktree_handle.clone(),
6244                            is_deleted: false,
6245                        }
6246                    } else {
6247                        File {
6248                            is_local: true,
6249                            entry_id: old_file.entry_id,
6250                            path: old_file.path().clone(),
6251                            mtime: old_file.mtime(),
6252                            worktree: worktree_handle.clone(),
6253                            is_deleted: true,
6254                        }
6255                    };
6256
6257                    let old_path = old_file.abs_path(cx);
6258                    if new_file.abs_path(cx) != old_path {
6259                        renamed_buffers.push((cx.handle(), old_file.clone()));
6260                        self.local_buffer_ids_by_path.remove(&project_path);
6261                        self.local_buffer_ids_by_path.insert(
6262                            ProjectPath {
6263                                worktree_id,
6264                                path: path.clone(),
6265                            },
6266                            buffer_id,
6267                        );
6268                    }
6269
6270                    if new_file.entry_id != *entry_id {
6271                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6272                        self.local_buffer_ids_by_entry_id
6273                            .insert(new_file.entry_id, buffer_id);
6274                    }
6275
6276                    if new_file != *old_file {
6277                        if let Some(project_id) = self.remote_id() {
6278                            self.client
6279                                .send(proto::UpdateBufferFile {
6280                                    project_id,
6281                                    buffer_id: buffer_id as u64,
6282                                    file: Some(new_file.to_proto()),
6283                                })
6284                                .log_err();
6285                        }
6286
6287                        buffer.file_updated(Arc::new(new_file), cx);
6288                    }
6289                }
6290            });
6291        }
6292
6293        for (buffer, old_file) in renamed_buffers {
6294            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6295            self.detect_language_for_buffer(&buffer, cx);
6296            self.register_buffer_with_language_servers(&buffer, cx);
6297        }
6298    }
6299
6300    fn update_local_worktree_language_servers(
6301        &mut self,
6302        worktree_handle: &Model<Worktree>,
6303        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6304        cx: &mut ModelContext<Self>,
6305    ) {
6306        if changes.is_empty() {
6307            return;
6308        }
6309
6310        let worktree_id = worktree_handle.read(cx).id();
6311        let mut language_server_ids = self
6312            .language_server_ids
6313            .iter()
6314            .filter_map(|((server_worktree_id, _), server_id)| {
6315                (*server_worktree_id == worktree_id).then_some(*server_id)
6316            })
6317            .collect::<Vec<_>>();
6318        language_server_ids.sort();
6319        language_server_ids.dedup();
6320
6321        let abs_path = worktree_handle.read(cx).abs_path();
6322        for server_id in &language_server_ids {
6323            if let Some(LanguageServerState::Running {
6324                server,
6325                watched_paths,
6326                ..
6327            }) = self.language_servers.get(server_id)
6328            {
6329                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6330                    let params = lsp::DidChangeWatchedFilesParams {
6331                        changes: changes
6332                            .iter()
6333                            .filter_map(|(path, _, change)| {
6334                                if !watched_paths.is_match(&path) {
6335                                    return None;
6336                                }
6337                                let typ = match change {
6338                                    PathChange::Loaded => return None,
6339                                    PathChange::Added => lsp::FileChangeType::CREATED,
6340                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6341                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6342                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6343                                };
6344                                Some(lsp::FileEvent {
6345                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6346                                    typ,
6347                                })
6348                            })
6349                            .collect(),
6350                    };
6351
6352                    if !params.changes.is_empty() {
6353                        server
6354                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6355                            .log_err();
6356                    }
6357                }
6358            }
6359        }
6360    }
6361
6362    fn update_local_worktree_buffers_git_repos(
6363        &mut self,
6364        worktree_handle: Model<Worktree>,
6365        changed_repos: &UpdatedGitRepositoriesSet,
6366        cx: &mut ModelContext<Self>,
6367    ) {
6368        debug_assert!(worktree_handle.read(cx).is_local());
6369
6370        // Identify the loading buffers whose containing repository that has changed.
6371        let future_buffers = self
6372            .loading_buffers_by_path
6373            .iter()
6374            .filter_map(|(project_path, receiver)| {
6375                if project_path.worktree_id != worktree_handle.read(cx).id() {
6376                    return None;
6377                }
6378                let path = &project_path.path;
6379                changed_repos
6380                    .iter()
6381                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6382                let receiver = receiver.clone();
6383                let path = path.clone();
6384                Some(async move {
6385                    wait_for_loading_buffer(receiver)
6386                        .await
6387                        .ok()
6388                        .map(|buffer| (buffer, path))
6389                })
6390            })
6391            .collect::<FuturesUnordered<_>>();
6392
6393        // Identify the current buffers whose containing repository has changed.
6394        let current_buffers = self
6395            .opened_buffers
6396            .values()
6397            .filter_map(|buffer| {
6398                let buffer = buffer.upgrade()?;
6399                let file = File::from_dyn(buffer.read(cx).file())?;
6400                if file.worktree != worktree_handle {
6401                    return None;
6402                }
6403                let path = file.path();
6404                changed_repos
6405                    .iter()
6406                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6407                Some((buffer, path.clone()))
6408            })
6409            .collect::<Vec<_>>();
6410
6411        if future_buffers.len() + current_buffers.len() == 0 {
6412            return;
6413        }
6414
6415        let remote_id = self.remote_id();
6416        let client = self.client.clone();
6417        cx.spawn(move |_, mut cx| async move {
6418            // Wait for all of the buffers to load.
6419            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6420
6421            // Reload the diff base for every buffer whose containing git repository has changed.
6422            let snapshot =
6423                worktree_handle.update(&mut cx, |tree, _| tree.as_local().unwrap().snapshot())?;
6424            let diff_bases_by_buffer = cx
6425                .background_executor()
6426                .spawn(async move {
6427                    future_buffers
6428                        .into_iter()
6429                        .filter_map(|e| e)
6430                        .chain(current_buffers)
6431                        .filter_map(|(buffer, path)| {
6432                            let (work_directory, repo) =
6433                                snapshot.repository_and_work_directory_for_path(&path)?;
6434                            let repo = snapshot.get_local_repo(&repo)?;
6435                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6436                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6437                            Some((buffer, base_text))
6438                        })
6439                        .collect::<Vec<_>>()
6440                })
6441                .await;
6442
6443            // Assign the new diff bases on all of the buffers.
6444            for (buffer, diff_base) in diff_bases_by_buffer {
6445                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6446                    buffer.set_diff_base(diff_base.clone(), cx);
6447                    buffer.remote_id()
6448                })?;
6449                if let Some(project_id) = remote_id {
6450                    client
6451                        .send(proto::UpdateDiffBase {
6452                            project_id,
6453                            buffer_id,
6454                            diff_base,
6455                        })
6456                        .log_err();
6457                }
6458            }
6459
6460            anyhow::Ok(())
6461        })
6462        .detach();
6463    }
6464
6465    fn update_local_worktree_settings(
6466        &mut self,
6467        worktree: &Model<Worktree>,
6468        changes: &UpdatedEntriesSet,
6469        cx: &mut ModelContext<Self>,
6470    ) {
6471        let project_id = self.remote_id();
6472        let worktree_id = worktree.entity_id();
6473        let worktree = worktree.read(cx).as_local().unwrap();
6474        let remote_worktree_id = worktree.id();
6475
6476        let mut settings_contents = Vec::new();
6477        for (path, _, change) in changes.iter() {
6478            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6479                let settings_dir = Arc::from(
6480                    path.ancestors()
6481                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6482                        .unwrap(),
6483                );
6484                let fs = self.fs.clone();
6485                let removed = *change == PathChange::Removed;
6486                let abs_path = worktree.absolutize(path);
6487                settings_contents.push(async move {
6488                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6489                });
6490            }
6491        }
6492
6493        if settings_contents.is_empty() {
6494            return;
6495        }
6496
6497        let client = self.client.clone();
6498        cx.spawn(move |_, cx| async move {
6499            let settings_contents: Vec<(Arc<Path>, _)> =
6500                futures::future::join_all(settings_contents).await;
6501            cx.update(|cx| {
6502                cx.update_global::<SettingsStore, _>(|store, cx| {
6503                    for (directory, file_content) in settings_contents {
6504                        let file_content = file_content.and_then(|content| content.log_err());
6505                        store
6506                            .set_local_settings(
6507                                worktree_id.as_u64() as usize,
6508                                directory.clone(),
6509                                file_content.as_ref().map(String::as_str),
6510                                cx,
6511                            )
6512                            .log_err();
6513                        if let Some(remote_id) = project_id {
6514                            client
6515                                .send(proto::UpdateWorktreeSettings {
6516                                    project_id: remote_id,
6517                                    worktree_id: remote_worktree_id.to_proto(),
6518                                    path: directory.to_string_lossy().into_owned(),
6519                                    content: file_content,
6520                                })
6521                                .log_err();
6522                        }
6523                    }
6524                });
6525            })
6526            .ok();
6527        })
6528        .detach();
6529    }
6530
6531    fn update_prettier_settings(
6532        &self,
6533        worktree: &Model<Worktree>,
6534        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6535        cx: &mut ModelContext<'_, Project>,
6536    ) {
6537        let prettier_config_files = Prettier::CONFIG_FILE_NAMES
6538            .iter()
6539            .map(Path::new)
6540            .collect::<HashSet<_>>();
6541
6542        let prettier_config_file_changed = changes
6543            .iter()
6544            .filter(|(_, _, change)| !matches!(change, PathChange::Loaded))
6545            .filter(|(path, _, _)| {
6546                !path
6547                    .components()
6548                    .any(|component| component.as_os_str().to_string_lossy() == "node_modules")
6549            })
6550            .find(|(path, _, _)| prettier_config_files.contains(path.as_ref()));
6551        let current_worktree_id = worktree.read(cx).id();
6552        if let Some((config_path, _, _)) = prettier_config_file_changed {
6553            log::info!(
6554                "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}"
6555            );
6556            let prettiers_to_reload = self
6557                .prettiers_per_worktree
6558                .get(&current_worktree_id)
6559                .iter()
6560                .flat_map(|prettier_paths| prettier_paths.iter())
6561                .flatten()
6562                .filter_map(|prettier_path| {
6563                    Some((
6564                        current_worktree_id,
6565                        Some(prettier_path.clone()),
6566                        self.prettier_instances.get(prettier_path)?.clone(),
6567                    ))
6568                })
6569                .chain(self.default_prettier.iter().filter_map(|default_prettier| {
6570                    Some((
6571                        current_worktree_id,
6572                        None,
6573                        default_prettier.instance.clone()?,
6574                    ))
6575                }))
6576                .collect::<Vec<_>>();
6577
6578            cx.background_executor()
6579                .spawn(async move {
6580                    for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| {
6581                        async move {
6582                            prettier_task.await?
6583                                .clear_cache()
6584                                .await
6585                                .with_context(|| {
6586                                    match prettier_path {
6587                                        Some(prettier_path) => format!(
6588                                            "clearing prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update"
6589                                        ),
6590                                        None => format!(
6591                                            "clearing default prettier cache for worktree {worktree_id:?} on prettier settings update"
6592                                        ),
6593                                    }
6594                                })
6595                                .map_err(Arc::new)
6596                        }
6597                    }))
6598                    .await
6599                    {
6600                        if let Err(e) = task_result {
6601                            log::error!("Failed to clear cache for prettier: {e:#}");
6602                        }
6603                    }
6604                })
6605                .detach();
6606        }
6607    }
6608
6609    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6610        let new_active_entry = entry.and_then(|project_path| {
6611            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6612            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6613            Some(entry.id)
6614        });
6615        if new_active_entry != self.active_entry {
6616            self.active_entry = new_active_entry;
6617            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6618        }
6619    }
6620
6621    pub fn language_servers_running_disk_based_diagnostics(
6622        &self,
6623    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6624        self.language_server_statuses
6625            .iter()
6626            .filter_map(|(id, status)| {
6627                if status.has_pending_diagnostic_updates {
6628                    Some(*id)
6629                } else {
6630                    None
6631                }
6632            })
6633    }
6634
6635    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
6636        let mut summary = DiagnosticSummary::default();
6637        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
6638            summary.error_count += path_summary.error_count;
6639            summary.warning_count += path_summary.warning_count;
6640        }
6641        summary
6642    }
6643
6644    pub fn diagnostic_summaries<'a>(
6645        &'a self,
6646        cx: &'a AppContext,
6647    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6648        self.visible_worktrees(cx).flat_map(move |worktree| {
6649            let worktree = worktree.read(cx);
6650            let worktree_id = worktree.id();
6651            worktree
6652                .diagnostic_summaries()
6653                .map(move |(path, server_id, summary)| {
6654                    (ProjectPath { worktree_id, path }, server_id, summary)
6655                })
6656        })
6657    }
6658
6659    pub fn disk_based_diagnostics_started(
6660        &mut self,
6661        language_server_id: LanguageServerId,
6662        cx: &mut ModelContext<Self>,
6663    ) {
6664        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6665    }
6666
6667    pub fn disk_based_diagnostics_finished(
6668        &mut self,
6669        language_server_id: LanguageServerId,
6670        cx: &mut ModelContext<Self>,
6671    ) {
6672        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6673    }
6674
6675    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6676        self.active_entry
6677    }
6678
6679    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6680        self.worktree_for_id(path.worktree_id, cx)?
6681            .read(cx)
6682            .entry_for_path(&path.path)
6683            .cloned()
6684    }
6685
6686    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6687        let worktree = self.worktree_for_entry(entry_id, cx)?;
6688        let worktree = worktree.read(cx);
6689        let worktree_id = worktree.id();
6690        let path = worktree.entry_for_id(entry_id)?.path.clone();
6691        Some(ProjectPath { worktree_id, path })
6692    }
6693
6694    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6695        let workspace_root = self
6696            .worktree_for_id(project_path.worktree_id, cx)?
6697            .read(cx)
6698            .abs_path();
6699        let project_path = project_path.path.as_ref();
6700
6701        Some(if project_path == Path::new("") {
6702            workspace_root.to_path_buf()
6703        } else {
6704            workspace_root.join(project_path)
6705        })
6706    }
6707
6708    // RPC message handlers
6709
6710    async fn handle_unshare_project(
6711        this: Model<Self>,
6712        _: TypedEnvelope<proto::UnshareProject>,
6713        _: Arc<Client>,
6714        mut cx: AsyncAppContext,
6715    ) -> Result<()> {
6716        this.update(&mut cx, |this, cx| {
6717            if this.is_local() {
6718                this.unshare(cx)?;
6719            } else {
6720                this.disconnected_from_host(cx);
6721            }
6722            Ok(())
6723        })?
6724    }
6725
6726    async fn handle_add_collaborator(
6727        this: Model<Self>,
6728        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6729        _: Arc<Client>,
6730        mut cx: AsyncAppContext,
6731    ) -> Result<()> {
6732        let collaborator = envelope
6733            .payload
6734            .collaborator
6735            .take()
6736            .ok_or_else(|| anyhow!("empty collaborator"))?;
6737
6738        let collaborator = Collaborator::from_proto(collaborator)?;
6739        this.update(&mut cx, |this, cx| {
6740            this.shared_buffers.remove(&collaborator.peer_id);
6741            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6742            this.collaborators
6743                .insert(collaborator.peer_id, collaborator);
6744            cx.notify();
6745        })?;
6746
6747        Ok(())
6748    }
6749
6750    async fn handle_update_project_collaborator(
6751        this: Model<Self>,
6752        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6753        _: Arc<Client>,
6754        mut cx: AsyncAppContext,
6755    ) -> Result<()> {
6756        let old_peer_id = envelope
6757            .payload
6758            .old_peer_id
6759            .ok_or_else(|| anyhow!("missing old peer id"))?;
6760        let new_peer_id = envelope
6761            .payload
6762            .new_peer_id
6763            .ok_or_else(|| anyhow!("missing new peer id"))?;
6764        this.update(&mut cx, |this, cx| {
6765            let collaborator = this
6766                .collaborators
6767                .remove(&old_peer_id)
6768                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6769            let is_host = collaborator.replica_id == 0;
6770            this.collaborators.insert(new_peer_id, collaborator);
6771
6772            let buffers = this.shared_buffers.remove(&old_peer_id);
6773            log::info!(
6774                "peer {} became {}. moving buffers {:?}",
6775                old_peer_id,
6776                new_peer_id,
6777                &buffers
6778            );
6779            if let Some(buffers) = buffers {
6780                this.shared_buffers.insert(new_peer_id, buffers);
6781            }
6782
6783            if is_host {
6784                this.opened_buffers
6785                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6786                this.buffer_ordered_messages_tx
6787                    .unbounded_send(BufferOrderedMessage::Resync)
6788                    .unwrap();
6789            }
6790
6791            cx.emit(Event::CollaboratorUpdated {
6792                old_peer_id,
6793                new_peer_id,
6794            });
6795            cx.notify();
6796            Ok(())
6797        })?
6798    }
6799
6800    async fn handle_remove_collaborator(
6801        this: Model<Self>,
6802        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6803        _: Arc<Client>,
6804        mut cx: AsyncAppContext,
6805    ) -> Result<()> {
6806        this.update(&mut cx, |this, cx| {
6807            let peer_id = envelope
6808                .payload
6809                .peer_id
6810                .ok_or_else(|| anyhow!("invalid peer id"))?;
6811            let replica_id = this
6812                .collaborators
6813                .remove(&peer_id)
6814                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6815                .replica_id;
6816            for buffer in this.opened_buffers.values() {
6817                if let Some(buffer) = buffer.upgrade() {
6818                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6819                }
6820            }
6821            this.shared_buffers.remove(&peer_id);
6822
6823            cx.emit(Event::CollaboratorLeft(peer_id));
6824            cx.notify();
6825            Ok(())
6826        })?
6827    }
6828
6829    async fn handle_update_project(
6830        this: Model<Self>,
6831        envelope: TypedEnvelope<proto::UpdateProject>,
6832        _: Arc<Client>,
6833        mut cx: AsyncAppContext,
6834    ) -> Result<()> {
6835        this.update(&mut cx, |this, cx| {
6836            // Don't handle messages that were sent before the response to us joining the project
6837            if envelope.message_id > this.join_project_response_message_id {
6838                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6839            }
6840            Ok(())
6841        })?
6842    }
6843
6844    async fn handle_update_worktree(
6845        this: Model<Self>,
6846        envelope: TypedEnvelope<proto::UpdateWorktree>,
6847        _: Arc<Client>,
6848        mut cx: AsyncAppContext,
6849    ) -> Result<()> {
6850        this.update(&mut cx, |this, cx| {
6851            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6852            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6853                worktree.update(cx, |worktree, _| {
6854                    let worktree = worktree.as_remote_mut().unwrap();
6855                    worktree.update_from_remote(envelope.payload);
6856                });
6857            }
6858            Ok(())
6859        })?
6860    }
6861
6862    async fn handle_update_worktree_settings(
6863        this: Model<Self>,
6864        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6865        _: Arc<Client>,
6866        mut cx: AsyncAppContext,
6867    ) -> Result<()> {
6868        this.update(&mut cx, |this, cx| {
6869            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6870            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6871                cx.update_global::<SettingsStore, _>(|store, cx| {
6872                    store
6873                        .set_local_settings(
6874                            worktree.entity_id().as_u64() as usize,
6875                            PathBuf::from(&envelope.payload.path).into(),
6876                            envelope.payload.content.as_ref().map(String::as_str),
6877                            cx,
6878                        )
6879                        .log_err();
6880                });
6881            }
6882            Ok(())
6883        })?
6884    }
6885
6886    async fn handle_create_project_entry(
6887        this: Model<Self>,
6888        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6889        _: Arc<Client>,
6890        mut cx: AsyncAppContext,
6891    ) -> Result<proto::ProjectEntryResponse> {
6892        let worktree = this.update(&mut cx, |this, cx| {
6893            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6894            this.worktree_for_id(worktree_id, cx)
6895                .ok_or_else(|| anyhow!("worktree not found"))
6896        })??;
6897        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6898        let entry = worktree
6899            .update(&mut cx, |worktree, cx| {
6900                let worktree = worktree.as_local_mut().unwrap();
6901                let path = PathBuf::from(envelope.payload.path);
6902                worktree.create_entry(path, envelope.payload.is_directory, cx)
6903            })?
6904            .await?;
6905        Ok(proto::ProjectEntryResponse {
6906            entry: Some((&entry).into()),
6907            worktree_scan_id: worktree_scan_id as u64,
6908        })
6909    }
6910
6911    async fn handle_rename_project_entry(
6912        this: Model<Self>,
6913        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6914        _: Arc<Client>,
6915        mut cx: AsyncAppContext,
6916    ) -> Result<proto::ProjectEntryResponse> {
6917        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6918        let worktree = this.update(&mut cx, |this, cx| {
6919            this.worktree_for_entry(entry_id, cx)
6920                .ok_or_else(|| anyhow!("worktree not found"))
6921        })??;
6922        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6923        let entry = worktree
6924            .update(&mut cx, |worktree, cx| {
6925                let new_path = PathBuf::from(envelope.payload.new_path);
6926                worktree
6927                    .as_local_mut()
6928                    .unwrap()
6929                    .rename_entry(entry_id, new_path, cx)
6930                    .ok_or_else(|| anyhow!("invalid entry"))
6931            })??
6932            .await?;
6933        Ok(proto::ProjectEntryResponse {
6934            entry: Some((&entry).into()),
6935            worktree_scan_id: worktree_scan_id as u64,
6936        })
6937    }
6938
6939    async fn handle_copy_project_entry(
6940        this: Model<Self>,
6941        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6942        _: Arc<Client>,
6943        mut cx: AsyncAppContext,
6944    ) -> Result<proto::ProjectEntryResponse> {
6945        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6946        let worktree = this.update(&mut cx, |this, cx| {
6947            this.worktree_for_entry(entry_id, cx)
6948                .ok_or_else(|| anyhow!("worktree not found"))
6949        })??;
6950        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6951        let entry = worktree
6952            .update(&mut cx, |worktree, cx| {
6953                let new_path = PathBuf::from(envelope.payload.new_path);
6954                worktree
6955                    .as_local_mut()
6956                    .unwrap()
6957                    .copy_entry(entry_id, new_path, cx)
6958                    .ok_or_else(|| anyhow!("invalid entry"))
6959            })??
6960            .await?;
6961        Ok(proto::ProjectEntryResponse {
6962            entry: Some((&entry).into()),
6963            worktree_scan_id: worktree_scan_id as u64,
6964        })
6965    }
6966
6967    async fn handle_delete_project_entry(
6968        this: Model<Self>,
6969        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6970        _: Arc<Client>,
6971        mut cx: AsyncAppContext,
6972    ) -> Result<proto::ProjectEntryResponse> {
6973        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6974
6975        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)))?;
6976
6977        let worktree = this.update(&mut cx, |this, cx| {
6978            this.worktree_for_entry(entry_id, cx)
6979                .ok_or_else(|| anyhow!("worktree not found"))
6980        })??;
6981        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())?;
6982        worktree
6983            .update(&mut cx, |worktree, cx| {
6984                worktree
6985                    .as_local_mut()
6986                    .unwrap()
6987                    .delete_entry(entry_id, cx)
6988                    .ok_or_else(|| anyhow!("invalid entry"))
6989            })??
6990            .await?;
6991        Ok(proto::ProjectEntryResponse {
6992            entry: None,
6993            worktree_scan_id: worktree_scan_id as u64,
6994        })
6995    }
6996
6997    async fn handle_expand_project_entry(
6998        this: Model<Self>,
6999        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
7000        _: Arc<Client>,
7001        mut cx: AsyncAppContext,
7002    ) -> Result<proto::ExpandProjectEntryResponse> {
7003        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
7004        let worktree = this
7005            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
7006            .ok_or_else(|| anyhow!("invalid request"))?;
7007        worktree
7008            .update(&mut cx, |worktree, cx| {
7009                worktree
7010                    .as_local_mut()
7011                    .unwrap()
7012                    .expand_entry(entry_id, cx)
7013                    .ok_or_else(|| anyhow!("invalid entry"))
7014            })??
7015            .await?;
7016        let worktree_scan_id = worktree.update(&mut cx, |worktree, _| worktree.scan_id())? as u64;
7017        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
7018    }
7019
7020    async fn handle_update_diagnostic_summary(
7021        this: Model<Self>,
7022        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
7023        _: Arc<Client>,
7024        mut cx: AsyncAppContext,
7025    ) -> Result<()> {
7026        this.update(&mut cx, |this, cx| {
7027            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7028            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
7029                if let Some(summary) = envelope.payload.summary {
7030                    let project_path = ProjectPath {
7031                        worktree_id,
7032                        path: Path::new(&summary.path).into(),
7033                    };
7034                    worktree.update(cx, |worktree, _| {
7035                        worktree
7036                            .as_remote_mut()
7037                            .unwrap()
7038                            .update_diagnostic_summary(project_path.path.clone(), &summary);
7039                    });
7040                    cx.emit(Event::DiagnosticsUpdated {
7041                        language_server_id: LanguageServerId(summary.language_server_id as usize),
7042                        path: project_path,
7043                    });
7044                }
7045            }
7046            Ok(())
7047        })?
7048    }
7049
7050    async fn handle_start_language_server(
7051        this: Model<Self>,
7052        envelope: TypedEnvelope<proto::StartLanguageServer>,
7053        _: Arc<Client>,
7054        mut cx: AsyncAppContext,
7055    ) -> Result<()> {
7056        let server = envelope
7057            .payload
7058            .server
7059            .ok_or_else(|| anyhow!("invalid server"))?;
7060        this.update(&mut cx, |this, cx| {
7061            this.language_server_statuses.insert(
7062                LanguageServerId(server.id as usize),
7063                LanguageServerStatus {
7064                    name: server.name,
7065                    pending_work: Default::default(),
7066                    has_pending_diagnostic_updates: false,
7067                    progress_tokens: Default::default(),
7068                },
7069            );
7070            cx.notify();
7071        })?;
7072        Ok(())
7073    }
7074
7075    async fn handle_update_language_server(
7076        this: Model<Self>,
7077        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
7078        _: Arc<Client>,
7079        mut cx: AsyncAppContext,
7080    ) -> Result<()> {
7081        this.update(&mut cx, |this, cx| {
7082            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
7083
7084            match envelope
7085                .payload
7086                .variant
7087                .ok_or_else(|| anyhow!("invalid variant"))?
7088            {
7089                proto::update_language_server::Variant::WorkStart(payload) => {
7090                    this.on_lsp_work_start(
7091                        language_server_id,
7092                        payload.token,
7093                        LanguageServerProgress {
7094                            message: payload.message,
7095                            percentage: payload.percentage.map(|p| p as usize),
7096                            last_update_at: Instant::now(),
7097                        },
7098                        cx,
7099                    );
7100                }
7101
7102                proto::update_language_server::Variant::WorkProgress(payload) => {
7103                    this.on_lsp_work_progress(
7104                        language_server_id,
7105                        payload.token,
7106                        LanguageServerProgress {
7107                            message: payload.message,
7108                            percentage: payload.percentage.map(|p| p as usize),
7109                            last_update_at: Instant::now(),
7110                        },
7111                        cx,
7112                    );
7113                }
7114
7115                proto::update_language_server::Variant::WorkEnd(payload) => {
7116                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7117                }
7118
7119                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7120                    this.disk_based_diagnostics_started(language_server_id, cx);
7121                }
7122
7123                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7124                    this.disk_based_diagnostics_finished(language_server_id, cx)
7125                }
7126            }
7127
7128            Ok(())
7129        })?
7130    }
7131
7132    async fn handle_update_buffer(
7133        this: Model<Self>,
7134        envelope: TypedEnvelope<proto::UpdateBuffer>,
7135        _: Arc<Client>,
7136        mut cx: AsyncAppContext,
7137    ) -> Result<proto::Ack> {
7138        this.update(&mut cx, |this, cx| {
7139            let payload = envelope.payload.clone();
7140            let buffer_id = payload.buffer_id;
7141            let ops = payload
7142                .operations
7143                .into_iter()
7144                .map(language::proto::deserialize_operation)
7145                .collect::<Result<Vec<_>, _>>()?;
7146            let is_remote = this.is_remote();
7147            match this.opened_buffers.entry(buffer_id) {
7148                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7149                    OpenBuffer::Strong(buffer) => {
7150                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7151                    }
7152                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7153                    OpenBuffer::Weak(_) => {}
7154                },
7155                hash_map::Entry::Vacant(e) => {
7156                    assert!(
7157                        is_remote,
7158                        "received buffer update from {:?}",
7159                        envelope.original_sender_id
7160                    );
7161                    e.insert(OpenBuffer::Operations(ops));
7162                }
7163            }
7164            Ok(proto::Ack {})
7165        })?
7166    }
7167
7168    async fn handle_create_buffer_for_peer(
7169        this: Model<Self>,
7170        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7171        _: Arc<Client>,
7172        mut cx: AsyncAppContext,
7173    ) -> Result<()> {
7174        this.update(&mut cx, |this, cx| {
7175            match envelope
7176                .payload
7177                .variant
7178                .ok_or_else(|| anyhow!("missing variant"))?
7179            {
7180                proto::create_buffer_for_peer::Variant::State(mut state) => {
7181                    let mut buffer_file = None;
7182                    if let Some(file) = state.file.take() {
7183                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7184                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7185                            anyhow!("no worktree found for id {}", file.worktree_id)
7186                        })?;
7187                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7188                            as Arc<dyn language::File>);
7189                    }
7190
7191                    let buffer_id = state.id;
7192                    let buffer = cx.build_model(|_| {
7193                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
7194                    });
7195                    this.incomplete_remote_buffers
7196                        .insert(buffer_id, Some(buffer));
7197                }
7198                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7199                    let buffer = this
7200                        .incomplete_remote_buffers
7201                        .get(&chunk.buffer_id)
7202                        .cloned()
7203                        .flatten()
7204                        .ok_or_else(|| {
7205                            anyhow!(
7206                                "received chunk for buffer {} without initial state",
7207                                chunk.buffer_id
7208                            )
7209                        })?;
7210                    let operations = chunk
7211                        .operations
7212                        .into_iter()
7213                        .map(language::proto::deserialize_operation)
7214                        .collect::<Result<Vec<_>>>()?;
7215                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7216
7217                    if chunk.is_last {
7218                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
7219                        this.register_buffer(&buffer, cx)?;
7220                    }
7221                }
7222            }
7223
7224            Ok(())
7225        })?
7226    }
7227
7228    async fn handle_update_diff_base(
7229        this: Model<Self>,
7230        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7231        _: Arc<Client>,
7232        mut cx: AsyncAppContext,
7233    ) -> Result<()> {
7234        this.update(&mut cx, |this, cx| {
7235            let buffer_id = envelope.payload.buffer_id;
7236            let diff_base = envelope.payload.diff_base;
7237            if let Some(buffer) = this
7238                .opened_buffers
7239                .get_mut(&buffer_id)
7240                .and_then(|b| b.upgrade())
7241                .or_else(|| {
7242                    this.incomplete_remote_buffers
7243                        .get(&buffer_id)
7244                        .cloned()
7245                        .flatten()
7246                })
7247            {
7248                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7249            }
7250            Ok(())
7251        })?
7252    }
7253
7254    async fn handle_update_buffer_file(
7255        this: Model<Self>,
7256        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7257        _: Arc<Client>,
7258        mut cx: AsyncAppContext,
7259    ) -> Result<()> {
7260        let buffer_id = envelope.payload.buffer_id;
7261
7262        this.update(&mut cx, |this, cx| {
7263            let payload = envelope.payload.clone();
7264            if let Some(buffer) = this
7265                .opened_buffers
7266                .get(&buffer_id)
7267                .and_then(|b| b.upgrade())
7268                .or_else(|| {
7269                    this.incomplete_remote_buffers
7270                        .get(&buffer_id)
7271                        .cloned()
7272                        .flatten()
7273                })
7274            {
7275                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7276                let worktree = this
7277                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7278                    .ok_or_else(|| anyhow!("no such worktree"))?;
7279                let file = File::from_proto(file, worktree, cx)?;
7280                buffer.update(cx, |buffer, cx| {
7281                    buffer.file_updated(Arc::new(file), cx);
7282                });
7283                this.detect_language_for_buffer(&buffer, cx);
7284            }
7285            Ok(())
7286        })?
7287    }
7288
7289    async fn handle_save_buffer(
7290        this: Model<Self>,
7291        envelope: TypedEnvelope<proto::SaveBuffer>,
7292        _: Arc<Client>,
7293        mut cx: AsyncAppContext,
7294    ) -> Result<proto::BufferSaved> {
7295        let buffer_id = envelope.payload.buffer_id;
7296        let (project_id, buffer) = this.update(&mut cx, |this, _cx| {
7297            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7298            let buffer = this
7299                .opened_buffers
7300                .get(&buffer_id)
7301                .and_then(|buffer| buffer.upgrade())
7302                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7303            anyhow::Ok((project_id, buffer))
7304        })??;
7305        buffer
7306            .update(&mut cx, |buffer, _| {
7307                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7308            })?
7309            .await?;
7310        let buffer_id = buffer.update(&mut cx, |buffer, _| buffer.remote_id())?;
7311
7312        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))?
7313            .await?;
7314        Ok(buffer.update(&mut cx, |buffer, _| proto::BufferSaved {
7315            project_id,
7316            buffer_id,
7317            version: serialize_version(buffer.saved_version()),
7318            mtime: Some(buffer.saved_mtime().into()),
7319            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7320        })?)
7321    }
7322
7323    async fn handle_reload_buffers(
7324        this: Model<Self>,
7325        envelope: TypedEnvelope<proto::ReloadBuffers>,
7326        _: Arc<Client>,
7327        mut cx: AsyncAppContext,
7328    ) -> Result<proto::ReloadBuffersResponse> {
7329        let sender_id = envelope.original_sender_id()?;
7330        let reload = this.update(&mut cx, |this, cx| {
7331            let mut buffers = HashSet::default();
7332            for buffer_id in &envelope.payload.buffer_ids {
7333                buffers.insert(
7334                    this.opened_buffers
7335                        .get(buffer_id)
7336                        .and_then(|buffer| buffer.upgrade())
7337                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7338                );
7339            }
7340            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7341        })??;
7342
7343        let project_transaction = reload.await?;
7344        let project_transaction = this.update(&mut cx, |this, cx| {
7345            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7346        })?;
7347        Ok(proto::ReloadBuffersResponse {
7348            transaction: Some(project_transaction),
7349        })
7350    }
7351
7352    async fn handle_synchronize_buffers(
7353        this: Model<Self>,
7354        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7355        _: Arc<Client>,
7356        mut cx: AsyncAppContext,
7357    ) -> Result<proto::SynchronizeBuffersResponse> {
7358        let project_id = envelope.payload.project_id;
7359        let mut response = proto::SynchronizeBuffersResponse {
7360            buffers: Default::default(),
7361        };
7362
7363        this.update(&mut cx, |this, cx| {
7364            let Some(guest_id) = envelope.original_sender_id else {
7365                error!("missing original_sender_id on SynchronizeBuffers request");
7366                return;
7367            };
7368
7369            this.shared_buffers.entry(guest_id).or_default().clear();
7370            for buffer in envelope.payload.buffers {
7371                let buffer_id = buffer.id;
7372                let remote_version = language::proto::deserialize_version(&buffer.version);
7373                if let Some(buffer) = this.buffer_for_id(buffer_id) {
7374                    this.shared_buffers
7375                        .entry(guest_id)
7376                        .or_default()
7377                        .insert(buffer_id);
7378
7379                    let buffer = buffer.read(cx);
7380                    response.buffers.push(proto::BufferVersion {
7381                        id: buffer_id,
7382                        version: language::proto::serialize_version(&buffer.version),
7383                    });
7384
7385                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7386                    let client = this.client.clone();
7387                    if let Some(file) = buffer.file() {
7388                        client
7389                            .send(proto::UpdateBufferFile {
7390                                project_id,
7391                                buffer_id: buffer_id as u64,
7392                                file: Some(file.to_proto()),
7393                            })
7394                            .log_err();
7395                    }
7396
7397                    client
7398                        .send(proto::UpdateDiffBase {
7399                            project_id,
7400                            buffer_id: buffer_id as u64,
7401                            diff_base: buffer.diff_base().map(Into::into),
7402                        })
7403                        .log_err();
7404
7405                    client
7406                        .send(proto::BufferReloaded {
7407                            project_id,
7408                            buffer_id,
7409                            version: language::proto::serialize_version(buffer.saved_version()),
7410                            mtime: Some(buffer.saved_mtime().into()),
7411                            fingerprint: language::proto::serialize_fingerprint(
7412                                buffer.saved_version_fingerprint(),
7413                            ),
7414                            line_ending: language::proto::serialize_line_ending(
7415                                buffer.line_ending(),
7416                            ) as i32,
7417                        })
7418                        .log_err();
7419
7420                    cx.background_executor()
7421                        .spawn(
7422                            async move {
7423                                let operations = operations.await;
7424                                for chunk in split_operations(operations) {
7425                                    client
7426                                        .request(proto::UpdateBuffer {
7427                                            project_id,
7428                                            buffer_id,
7429                                            operations: chunk,
7430                                        })
7431                                        .await?;
7432                                }
7433                                anyhow::Ok(())
7434                            }
7435                            .log_err(),
7436                        )
7437                        .detach();
7438                }
7439            }
7440        })?;
7441
7442        Ok(response)
7443    }
7444
7445    async fn handle_format_buffers(
7446        this: Model<Self>,
7447        envelope: TypedEnvelope<proto::FormatBuffers>,
7448        _: Arc<Client>,
7449        mut cx: AsyncAppContext,
7450    ) -> Result<proto::FormatBuffersResponse> {
7451        let sender_id = envelope.original_sender_id()?;
7452        let format = this.update(&mut cx, |this, cx| {
7453            let mut buffers = HashSet::default();
7454            for buffer_id in &envelope.payload.buffer_ids {
7455                buffers.insert(
7456                    this.opened_buffers
7457                        .get(buffer_id)
7458                        .and_then(|buffer| buffer.upgrade())
7459                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7460                );
7461            }
7462            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7463            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7464        })??;
7465
7466        let project_transaction = format.await?;
7467        let project_transaction = this.update(&mut cx, |this, cx| {
7468            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7469        })?;
7470        Ok(proto::FormatBuffersResponse {
7471            transaction: Some(project_transaction),
7472        })
7473    }
7474
7475    async fn handle_apply_additional_edits_for_completion(
7476        this: Model<Self>,
7477        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7478        _: Arc<Client>,
7479        mut cx: AsyncAppContext,
7480    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7481        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7482            let buffer = this
7483                .opened_buffers
7484                .get(&envelope.payload.buffer_id)
7485                .and_then(|buffer| buffer.upgrade())
7486                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7487            let language = buffer.read(cx).language();
7488            let completion = language::proto::deserialize_completion(
7489                envelope
7490                    .payload
7491                    .completion
7492                    .ok_or_else(|| anyhow!("invalid completion"))?,
7493                language.cloned(),
7494            );
7495            Ok::<_, anyhow::Error>((buffer, completion))
7496        })??;
7497
7498        let completion = completion.await?;
7499
7500        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7501            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7502        })?;
7503
7504        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7505            transaction: apply_additional_edits
7506                .await?
7507                .as_ref()
7508                .map(language::proto::serialize_transaction),
7509        })
7510    }
7511
7512    async fn handle_apply_code_action(
7513        this: Model<Self>,
7514        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7515        _: Arc<Client>,
7516        mut cx: AsyncAppContext,
7517    ) -> Result<proto::ApplyCodeActionResponse> {
7518        let sender_id = envelope.original_sender_id()?;
7519        let action = language::proto::deserialize_code_action(
7520            envelope
7521                .payload
7522                .action
7523                .ok_or_else(|| anyhow!("invalid action"))?,
7524        )?;
7525        let apply_code_action = this.update(&mut cx, |this, cx| {
7526            let buffer = this
7527                .opened_buffers
7528                .get(&envelope.payload.buffer_id)
7529                .and_then(|buffer| buffer.upgrade())
7530                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7531            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7532        })??;
7533
7534        let project_transaction = apply_code_action.await?;
7535        let project_transaction = this.update(&mut cx, |this, cx| {
7536            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7537        })?;
7538        Ok(proto::ApplyCodeActionResponse {
7539            transaction: Some(project_transaction),
7540        })
7541    }
7542
7543    async fn handle_on_type_formatting(
7544        this: Model<Self>,
7545        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7546        _: Arc<Client>,
7547        mut cx: AsyncAppContext,
7548    ) -> Result<proto::OnTypeFormattingResponse> {
7549        let on_type_formatting = this.update(&mut cx, |this, cx| {
7550            let buffer = this
7551                .opened_buffers
7552                .get(&envelope.payload.buffer_id)
7553                .and_then(|buffer| buffer.upgrade())
7554                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7555            let position = envelope
7556                .payload
7557                .position
7558                .and_then(deserialize_anchor)
7559                .ok_or_else(|| anyhow!("invalid position"))?;
7560            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7561                buffer,
7562                position,
7563                envelope.payload.trigger.clone(),
7564                cx,
7565            ))
7566        })??;
7567
7568        let transaction = on_type_formatting
7569            .await?
7570            .as_ref()
7571            .map(language::proto::serialize_transaction);
7572        Ok(proto::OnTypeFormattingResponse { transaction })
7573    }
7574
7575    async fn handle_inlay_hints(
7576        this: Model<Self>,
7577        envelope: TypedEnvelope<proto::InlayHints>,
7578        _: Arc<Client>,
7579        mut cx: AsyncAppContext,
7580    ) -> Result<proto::InlayHintsResponse> {
7581        let sender_id = envelope.original_sender_id()?;
7582        let buffer = this.update(&mut cx, |this, _| {
7583            this.opened_buffers
7584                .get(&envelope.payload.buffer_id)
7585                .and_then(|buffer| buffer.upgrade())
7586                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7587        })??;
7588        let buffer_version = deserialize_version(&envelope.payload.version);
7589
7590        buffer
7591            .update(&mut cx, |buffer, _| {
7592                buffer.wait_for_version(buffer_version.clone())
7593            })?
7594            .await
7595            .with_context(|| {
7596                format!(
7597                    "waiting for version {:?} for buffer {}",
7598                    buffer_version,
7599                    buffer.entity_id()
7600                )
7601            })?;
7602
7603        let start = envelope
7604            .payload
7605            .start
7606            .and_then(deserialize_anchor)
7607            .context("missing range start")?;
7608        let end = envelope
7609            .payload
7610            .end
7611            .and_then(deserialize_anchor)
7612            .context("missing range end")?;
7613        let buffer_hints = this
7614            .update(&mut cx, |project, cx| {
7615                project.inlay_hints(buffer, start..end, cx)
7616            })?
7617            .await
7618            .context("inlay hints fetch")?;
7619
7620        Ok(this.update(&mut cx, |project, cx| {
7621            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7622        })?)
7623    }
7624
7625    async fn handle_resolve_inlay_hint(
7626        this: Model<Self>,
7627        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7628        _: Arc<Client>,
7629        mut cx: AsyncAppContext,
7630    ) -> Result<proto::ResolveInlayHintResponse> {
7631        let proto_hint = envelope
7632            .payload
7633            .hint
7634            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7635        let hint = InlayHints::proto_to_project_hint(proto_hint)
7636            .context("resolved proto inlay hint conversion")?;
7637        let buffer = this.update(&mut cx, |this, _cx| {
7638            this.opened_buffers
7639                .get(&envelope.payload.buffer_id)
7640                .and_then(|buffer| buffer.upgrade())
7641                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7642        })??;
7643        let response_hint = this
7644            .update(&mut cx, |project, cx| {
7645                project.resolve_inlay_hint(
7646                    hint,
7647                    buffer,
7648                    LanguageServerId(envelope.payload.language_server_id as usize),
7649                    cx,
7650                )
7651            })?
7652            .await
7653            .context("inlay hints fetch")?;
7654        Ok(proto::ResolveInlayHintResponse {
7655            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7656        })
7657    }
7658
7659    async fn handle_refresh_inlay_hints(
7660        this: Model<Self>,
7661        _: TypedEnvelope<proto::RefreshInlayHints>,
7662        _: Arc<Client>,
7663        mut cx: AsyncAppContext,
7664    ) -> Result<proto::Ack> {
7665        this.update(&mut cx, |_, cx| {
7666            cx.emit(Event::RefreshInlayHints);
7667        })?;
7668        Ok(proto::Ack {})
7669    }
7670
7671    async fn handle_lsp_command<T: LspCommand>(
7672        this: Model<Self>,
7673        envelope: TypedEnvelope<T::ProtoRequest>,
7674        _: Arc<Client>,
7675        mut cx: AsyncAppContext,
7676    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7677    where
7678        <T::LspRequest as lsp::request::Request>::Params: Send,
7679        <T::LspRequest as lsp::request::Request>::Result: Send,
7680    {
7681        let sender_id = envelope.original_sender_id()?;
7682        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7683        let buffer_handle = this.update(&mut cx, |this, _cx| {
7684            this.opened_buffers
7685                .get(&buffer_id)
7686                .and_then(|buffer| buffer.upgrade())
7687                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7688        })??;
7689        let request = T::from_proto(
7690            envelope.payload,
7691            this.clone(),
7692            buffer_handle.clone(),
7693            cx.clone(),
7694        )
7695        .await?;
7696        let buffer_version = buffer_handle.update(&mut cx, |buffer, _| buffer.version())?;
7697        let response = this
7698            .update(&mut cx, |this, cx| {
7699                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7700            })?
7701            .await?;
7702        this.update(&mut cx, |this, cx| {
7703            Ok(T::response_to_proto(
7704                response,
7705                this,
7706                sender_id,
7707                &buffer_version,
7708                cx,
7709            ))
7710        })?
7711    }
7712
7713    async fn handle_get_project_symbols(
7714        this: Model<Self>,
7715        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7716        _: Arc<Client>,
7717        mut cx: AsyncAppContext,
7718    ) -> Result<proto::GetProjectSymbolsResponse> {
7719        let symbols = this
7720            .update(&mut cx, |this, cx| {
7721                this.symbols(&envelope.payload.query, cx)
7722            })?
7723            .await?;
7724
7725        Ok(proto::GetProjectSymbolsResponse {
7726            symbols: symbols.iter().map(serialize_symbol).collect(),
7727        })
7728    }
7729
7730    async fn handle_search_project(
7731        this: Model<Self>,
7732        envelope: TypedEnvelope<proto::SearchProject>,
7733        _: Arc<Client>,
7734        mut cx: AsyncAppContext,
7735    ) -> Result<proto::SearchProjectResponse> {
7736        let peer_id = envelope.original_sender_id()?;
7737        let query = SearchQuery::from_proto(envelope.payload)?;
7738        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx))?;
7739
7740        cx.spawn(move |mut cx| async move {
7741            let mut locations = Vec::new();
7742            while let Some((buffer, ranges)) = result.next().await {
7743                for range in ranges {
7744                    let start = serialize_anchor(&range.start);
7745                    let end = serialize_anchor(&range.end);
7746                    let buffer_id = this.update(&mut cx, |this, cx| {
7747                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7748                    })?;
7749                    locations.push(proto::Location {
7750                        buffer_id,
7751                        start: Some(start),
7752                        end: Some(end),
7753                    });
7754                }
7755            }
7756            Ok(proto::SearchProjectResponse { locations })
7757        })
7758        .await
7759    }
7760
7761    async fn handle_open_buffer_for_symbol(
7762        this: Model<Self>,
7763        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7764        _: Arc<Client>,
7765        mut cx: AsyncAppContext,
7766    ) -> Result<proto::OpenBufferForSymbolResponse> {
7767        let peer_id = envelope.original_sender_id()?;
7768        let symbol = envelope
7769            .payload
7770            .symbol
7771            .ok_or_else(|| anyhow!("invalid symbol"))?;
7772        let symbol = this
7773            .update(&mut cx, |this, _| this.deserialize_symbol(symbol))?
7774            .await?;
7775        let symbol = this.update(&mut cx, |this, _| {
7776            let signature = this.symbol_signature(&symbol.path);
7777            if signature == symbol.signature {
7778                Ok(symbol)
7779            } else {
7780                Err(anyhow!("invalid symbol signature"))
7781            }
7782        })??;
7783        let buffer = this
7784            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))?
7785            .await?;
7786
7787        Ok(proto::OpenBufferForSymbolResponse {
7788            buffer_id: this.update(&mut cx, |this, cx| {
7789                this.create_buffer_for_peer(&buffer, peer_id, cx)
7790            })?,
7791        })
7792    }
7793
7794    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7795        let mut hasher = Sha256::new();
7796        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7797        hasher.update(project_path.path.to_string_lossy().as_bytes());
7798        hasher.update(self.nonce.to_be_bytes());
7799        hasher.finalize().as_slice().try_into().unwrap()
7800    }
7801
7802    async fn handle_open_buffer_by_id(
7803        this: Model<Self>,
7804        envelope: TypedEnvelope<proto::OpenBufferById>,
7805        _: Arc<Client>,
7806        mut cx: AsyncAppContext,
7807    ) -> Result<proto::OpenBufferResponse> {
7808        let peer_id = envelope.original_sender_id()?;
7809        let buffer = this
7810            .update(&mut cx, |this, cx| {
7811                this.open_buffer_by_id(envelope.payload.id, cx)
7812            })?
7813            .await?;
7814        this.update(&mut cx, |this, cx| {
7815            Ok(proto::OpenBufferResponse {
7816                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7817            })
7818        })?
7819    }
7820
7821    async fn handle_open_buffer_by_path(
7822        this: Model<Self>,
7823        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7824        _: Arc<Client>,
7825        mut cx: AsyncAppContext,
7826    ) -> Result<proto::OpenBufferResponse> {
7827        let peer_id = envelope.original_sender_id()?;
7828        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7829        let open_buffer = this.update(&mut cx, |this, cx| {
7830            this.open_buffer(
7831                ProjectPath {
7832                    worktree_id,
7833                    path: PathBuf::from(envelope.payload.path).into(),
7834                },
7835                cx,
7836            )
7837        })?;
7838
7839        let buffer = open_buffer.await?;
7840        this.update(&mut cx, |this, cx| {
7841            Ok(proto::OpenBufferResponse {
7842                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7843            })
7844        })?
7845    }
7846
7847    fn serialize_project_transaction_for_peer(
7848        &mut self,
7849        project_transaction: ProjectTransaction,
7850        peer_id: proto::PeerId,
7851        cx: &mut AppContext,
7852    ) -> proto::ProjectTransaction {
7853        let mut serialized_transaction = proto::ProjectTransaction {
7854            buffer_ids: Default::default(),
7855            transactions: Default::default(),
7856        };
7857        for (buffer, transaction) in project_transaction.0 {
7858            serialized_transaction
7859                .buffer_ids
7860                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7861            serialized_transaction
7862                .transactions
7863                .push(language::proto::serialize_transaction(&transaction));
7864        }
7865        serialized_transaction
7866    }
7867
7868    fn deserialize_project_transaction(
7869        &mut self,
7870        message: proto::ProjectTransaction,
7871        push_to_history: bool,
7872        cx: &mut ModelContext<Self>,
7873    ) -> Task<Result<ProjectTransaction>> {
7874        cx.spawn(move |this, mut cx| async move {
7875            let mut project_transaction = ProjectTransaction::default();
7876            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7877            {
7878                let buffer = this
7879                    .update(&mut cx, |this, cx| {
7880                        this.wait_for_remote_buffer(buffer_id, cx)
7881                    })?
7882                    .await?;
7883                let transaction = language::proto::deserialize_transaction(transaction)?;
7884                project_transaction.0.insert(buffer, transaction);
7885            }
7886
7887            for (buffer, transaction) in &project_transaction.0 {
7888                buffer
7889                    .update(&mut cx, |buffer, _| {
7890                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7891                    })?
7892                    .await?;
7893
7894                if push_to_history {
7895                    buffer.update(&mut cx, |buffer, _| {
7896                        buffer.push_transaction(transaction.clone(), Instant::now());
7897                    })?;
7898                }
7899            }
7900
7901            Ok(project_transaction)
7902        })
7903    }
7904
7905    fn create_buffer_for_peer(
7906        &mut self,
7907        buffer: &Model<Buffer>,
7908        peer_id: proto::PeerId,
7909        cx: &mut AppContext,
7910    ) -> u64 {
7911        let buffer_id = buffer.read(cx).remote_id();
7912        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7913            updates_tx
7914                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7915                .ok();
7916        }
7917        buffer_id
7918    }
7919
7920    fn wait_for_remote_buffer(
7921        &mut self,
7922        id: u64,
7923        cx: &mut ModelContext<Self>,
7924    ) -> Task<Result<Model<Buffer>>> {
7925        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7926
7927        cx.spawn(move |this, mut cx| async move {
7928            let buffer = loop {
7929                let Some(this) = this.upgrade() else {
7930                    return Err(anyhow!("project dropped"));
7931                };
7932
7933                let buffer = this.update(&mut cx, |this, _cx| {
7934                    this.opened_buffers
7935                        .get(&id)
7936                        .and_then(|buffer| buffer.upgrade())
7937                })?;
7938
7939                if let Some(buffer) = buffer {
7940                    break buffer;
7941                } else if this.update(&mut cx, |this, _| this.is_read_only())? {
7942                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7943                }
7944
7945                this.update(&mut cx, |this, _| {
7946                    this.incomplete_remote_buffers.entry(id).or_default();
7947                })?;
7948                drop(this);
7949
7950                opened_buffer_rx
7951                    .next()
7952                    .await
7953                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7954            };
7955
7956            Ok(buffer)
7957        })
7958    }
7959
7960    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7961        let project_id = match self.client_state.as_ref() {
7962            Some(ProjectClientState::Remote {
7963                sharing_has_stopped,
7964                remote_id,
7965                ..
7966            }) => {
7967                if *sharing_has_stopped {
7968                    return Task::ready(Err(anyhow!(
7969                        "can't synchronize remote buffers on a readonly project"
7970                    )));
7971                } else {
7972                    *remote_id
7973                }
7974            }
7975            Some(ProjectClientState::Local { .. }) | None => {
7976                return Task::ready(Err(anyhow!(
7977                    "can't synchronize remote buffers on a local project"
7978                )))
7979            }
7980        };
7981
7982        let client = self.client.clone();
7983        cx.spawn(move |this, mut cx| async move {
7984            let (buffers, incomplete_buffer_ids) = this.update(&mut cx, |this, cx| {
7985                let buffers = this
7986                    .opened_buffers
7987                    .iter()
7988                    .filter_map(|(id, buffer)| {
7989                        let buffer = buffer.upgrade()?;
7990                        Some(proto::BufferVersion {
7991                            id: *id,
7992                            version: language::proto::serialize_version(&buffer.read(cx).version),
7993                        })
7994                    })
7995                    .collect();
7996                let incomplete_buffer_ids = this
7997                    .incomplete_remote_buffers
7998                    .keys()
7999                    .copied()
8000                    .collect::<Vec<_>>();
8001
8002                (buffers, incomplete_buffer_ids)
8003            })?;
8004            let response = client
8005                .request(proto::SynchronizeBuffers {
8006                    project_id,
8007                    buffers,
8008                })
8009                .await?;
8010
8011            let send_updates_for_buffers = this.update(&mut cx, |this, cx| {
8012                response
8013                    .buffers
8014                    .into_iter()
8015                    .map(|buffer| {
8016                        let client = client.clone();
8017                        let buffer_id = buffer.id;
8018                        let remote_version = language::proto::deserialize_version(&buffer.version);
8019                        if let Some(buffer) = this.buffer_for_id(buffer_id) {
8020                            let operations =
8021                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
8022                            cx.background_executor().spawn(async move {
8023                                let operations = operations.await;
8024                                for chunk in split_operations(operations) {
8025                                    client
8026                                        .request(proto::UpdateBuffer {
8027                                            project_id,
8028                                            buffer_id,
8029                                            operations: chunk,
8030                                        })
8031                                        .await?;
8032                                }
8033                                anyhow::Ok(())
8034                            })
8035                        } else {
8036                            Task::ready(Ok(()))
8037                        }
8038                    })
8039                    .collect::<Vec<_>>()
8040            })?;
8041
8042            // Any incomplete buffers have open requests waiting. Request that the host sends
8043            // creates these buffers for us again to unblock any waiting futures.
8044            for id in incomplete_buffer_ids {
8045                cx.background_executor()
8046                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
8047                    .detach();
8048            }
8049
8050            futures::future::join_all(send_updates_for_buffers)
8051                .await
8052                .into_iter()
8053                .collect()
8054        })
8055    }
8056
8057    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
8058        self.worktrees()
8059            .map(|worktree| {
8060                let worktree = worktree.read(cx);
8061                proto::WorktreeMetadata {
8062                    id: worktree.id().to_proto(),
8063                    root_name: worktree.root_name().into(),
8064                    visible: worktree.is_visible(),
8065                    abs_path: worktree.abs_path().to_string_lossy().into(),
8066                }
8067            })
8068            .collect()
8069    }
8070
8071    fn set_worktrees_from_proto(
8072        &mut self,
8073        worktrees: Vec<proto::WorktreeMetadata>,
8074        cx: &mut ModelContext<Project>,
8075    ) -> Result<()> {
8076        let replica_id = self.replica_id();
8077        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8078
8079        let mut old_worktrees_by_id = self
8080            .worktrees
8081            .drain(..)
8082            .filter_map(|worktree| {
8083                let worktree = worktree.upgrade()?;
8084                Some((worktree.read(cx).id(), worktree))
8085            })
8086            .collect::<HashMap<_, _>>();
8087
8088        for worktree in worktrees {
8089            if let Some(old_worktree) =
8090                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8091            {
8092                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8093            } else {
8094                let worktree =
8095                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8096                let _ = self.add_worktree(&worktree, cx);
8097            }
8098        }
8099
8100        self.metadata_changed(cx);
8101        for id in old_worktrees_by_id.keys() {
8102            cx.emit(Event::WorktreeRemoved(*id));
8103        }
8104
8105        Ok(())
8106    }
8107
8108    fn set_collaborators_from_proto(
8109        &mut self,
8110        messages: Vec<proto::Collaborator>,
8111        cx: &mut ModelContext<Self>,
8112    ) -> Result<()> {
8113        let mut collaborators = HashMap::default();
8114        for message in messages {
8115            let collaborator = Collaborator::from_proto(message)?;
8116            collaborators.insert(collaborator.peer_id, collaborator);
8117        }
8118        for old_peer_id in self.collaborators.keys() {
8119            if !collaborators.contains_key(old_peer_id) {
8120                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8121            }
8122        }
8123        self.collaborators = collaborators;
8124        Ok(())
8125    }
8126
8127    fn deserialize_symbol(
8128        &self,
8129        serialized_symbol: proto::Symbol,
8130    ) -> impl Future<Output = Result<Symbol>> {
8131        let languages = self.languages.clone();
8132        async move {
8133            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8134            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8135            let start = serialized_symbol
8136                .start
8137                .ok_or_else(|| anyhow!("invalid start"))?;
8138            let end = serialized_symbol
8139                .end
8140                .ok_or_else(|| anyhow!("invalid end"))?;
8141            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8142            let path = ProjectPath {
8143                worktree_id,
8144                path: PathBuf::from(serialized_symbol.path).into(),
8145            };
8146            let language = languages
8147                .language_for_file(&path.path, None)
8148                .await
8149                .log_err();
8150            Ok(Symbol {
8151                language_server_name: LanguageServerName(
8152                    serialized_symbol.language_server_name.into(),
8153                ),
8154                source_worktree_id,
8155                path,
8156                label: {
8157                    match language {
8158                        Some(language) => {
8159                            language
8160                                .label_for_symbol(&serialized_symbol.name, kind)
8161                                .await
8162                        }
8163                        None => None,
8164                    }
8165                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8166                },
8167
8168                name: serialized_symbol.name,
8169                range: Unclipped(PointUtf16::new(start.row, start.column))
8170                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8171                kind,
8172                signature: serialized_symbol
8173                    .signature
8174                    .try_into()
8175                    .map_err(|_| anyhow!("invalid signature"))?,
8176            })
8177        }
8178    }
8179
8180    async fn handle_buffer_saved(
8181        this: Model<Self>,
8182        envelope: TypedEnvelope<proto::BufferSaved>,
8183        _: Arc<Client>,
8184        mut cx: AsyncAppContext,
8185    ) -> Result<()> {
8186        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8187        let version = deserialize_version(&envelope.payload.version);
8188        let mtime = envelope
8189            .payload
8190            .mtime
8191            .ok_or_else(|| anyhow!("missing mtime"))?
8192            .into();
8193
8194        this.update(&mut cx, |this, cx| {
8195            let buffer = this
8196                .opened_buffers
8197                .get(&envelope.payload.buffer_id)
8198                .and_then(|buffer| buffer.upgrade())
8199                .or_else(|| {
8200                    this.incomplete_remote_buffers
8201                        .get(&envelope.payload.buffer_id)
8202                        .and_then(|b| b.clone())
8203                });
8204            if let Some(buffer) = buffer {
8205                buffer.update(cx, |buffer, cx| {
8206                    buffer.did_save(version, fingerprint, mtime, cx);
8207                });
8208            }
8209            Ok(())
8210        })?
8211    }
8212
8213    async fn handle_buffer_reloaded(
8214        this: Model<Self>,
8215        envelope: TypedEnvelope<proto::BufferReloaded>,
8216        _: Arc<Client>,
8217        mut cx: AsyncAppContext,
8218    ) -> Result<()> {
8219        let payload = envelope.payload;
8220        let version = deserialize_version(&payload.version);
8221        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8222        let line_ending = deserialize_line_ending(
8223            proto::LineEnding::from_i32(payload.line_ending)
8224                .ok_or_else(|| anyhow!("missing line ending"))?,
8225        );
8226        let mtime = payload
8227            .mtime
8228            .ok_or_else(|| anyhow!("missing mtime"))?
8229            .into();
8230        this.update(&mut cx, |this, cx| {
8231            let buffer = this
8232                .opened_buffers
8233                .get(&payload.buffer_id)
8234                .and_then(|buffer| buffer.upgrade())
8235                .or_else(|| {
8236                    this.incomplete_remote_buffers
8237                        .get(&payload.buffer_id)
8238                        .cloned()
8239                        .flatten()
8240                });
8241            if let Some(buffer) = buffer {
8242                buffer.update(cx, |buffer, cx| {
8243                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8244                });
8245            }
8246            Ok(())
8247        })?
8248    }
8249
8250    #[allow(clippy::type_complexity)]
8251    fn edits_from_lsp(
8252        &mut self,
8253        buffer: &Model<Buffer>,
8254        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8255        server_id: LanguageServerId,
8256        version: Option<i32>,
8257        cx: &mut ModelContext<Self>,
8258    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8259        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8260        cx.background_executor().spawn(async move {
8261            let snapshot = snapshot?;
8262            let mut lsp_edits = lsp_edits
8263                .into_iter()
8264                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8265                .collect::<Vec<_>>();
8266            lsp_edits.sort_by_key(|(range, _)| range.start);
8267
8268            let mut lsp_edits = lsp_edits.into_iter().peekable();
8269            let mut edits = Vec::new();
8270            while let Some((range, mut new_text)) = lsp_edits.next() {
8271                // Clip invalid ranges provided by the language server.
8272                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8273                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8274
8275                // Combine any LSP edits that are adjacent.
8276                //
8277                // Also, combine LSP edits that are separated from each other by only
8278                // a newline. This is important because for some code actions,
8279                // Rust-analyzer rewrites the entire buffer via a series of edits that
8280                // are separated by unchanged newline characters.
8281                //
8282                // In order for the diffing logic below to work properly, any edits that
8283                // cancel each other out must be combined into one.
8284                while let Some((next_range, next_text)) = lsp_edits.peek() {
8285                    if next_range.start.0 > range.end {
8286                        if next_range.start.0.row > range.end.row + 1
8287                            || next_range.start.0.column > 0
8288                            || snapshot.clip_point_utf16(
8289                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8290                                Bias::Left,
8291                            ) > range.end
8292                        {
8293                            break;
8294                        }
8295                        new_text.push('\n');
8296                    }
8297                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8298                    new_text.push_str(next_text);
8299                    lsp_edits.next();
8300                }
8301
8302                // For multiline edits, perform a diff of the old and new text so that
8303                // we can identify the changes more precisely, preserving the locations
8304                // of any anchors positioned in the unchanged regions.
8305                if range.end.row > range.start.row {
8306                    let mut offset = range.start.to_offset(&snapshot);
8307                    let old_text = snapshot.text_for_range(range).collect::<String>();
8308
8309                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8310                    let mut moved_since_edit = true;
8311                    for change in diff.iter_all_changes() {
8312                        let tag = change.tag();
8313                        let value = change.value();
8314                        match tag {
8315                            ChangeTag::Equal => {
8316                                offset += value.len();
8317                                moved_since_edit = true;
8318                            }
8319                            ChangeTag::Delete => {
8320                                let start = snapshot.anchor_after(offset);
8321                                let end = snapshot.anchor_before(offset + value.len());
8322                                if moved_since_edit {
8323                                    edits.push((start..end, String::new()));
8324                                } else {
8325                                    edits.last_mut().unwrap().0.end = end;
8326                                }
8327                                offset += value.len();
8328                                moved_since_edit = false;
8329                            }
8330                            ChangeTag::Insert => {
8331                                if moved_since_edit {
8332                                    let anchor = snapshot.anchor_after(offset);
8333                                    edits.push((anchor..anchor, value.to_string()));
8334                                } else {
8335                                    edits.last_mut().unwrap().1.push_str(value);
8336                                }
8337                                moved_since_edit = false;
8338                            }
8339                        }
8340                    }
8341                } else if range.end == range.start {
8342                    let anchor = snapshot.anchor_after(range.start);
8343                    edits.push((anchor..anchor, new_text));
8344                } else {
8345                    let edit_start = snapshot.anchor_after(range.start);
8346                    let edit_end = snapshot.anchor_before(range.end);
8347                    edits.push((edit_start..edit_end, new_text));
8348                }
8349            }
8350
8351            Ok(edits)
8352        })
8353    }
8354
8355    fn buffer_snapshot_for_lsp_version(
8356        &mut self,
8357        buffer: &Model<Buffer>,
8358        server_id: LanguageServerId,
8359        version: Option<i32>,
8360        cx: &AppContext,
8361    ) -> Result<TextBufferSnapshot> {
8362        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8363
8364        if let Some(version) = version {
8365            let buffer_id = buffer.read(cx).remote_id();
8366            let snapshots = self
8367                .buffer_snapshots
8368                .get_mut(&buffer_id)
8369                .and_then(|m| m.get_mut(&server_id))
8370                .ok_or_else(|| {
8371                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8372                })?;
8373
8374            let found_snapshot = snapshots
8375                .binary_search_by_key(&version, |e| e.version)
8376                .map(|ix| snapshots[ix].snapshot.clone())
8377                .map_err(|_| {
8378                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8379                })?;
8380
8381            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8382            Ok(found_snapshot)
8383        } else {
8384            Ok((buffer.read(cx)).text_snapshot())
8385        }
8386    }
8387
8388    pub fn language_servers(
8389        &self,
8390    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8391        self.language_server_ids
8392            .iter()
8393            .map(|((worktree_id, server_name), server_id)| {
8394                (*server_id, server_name.clone(), *worktree_id)
8395            })
8396    }
8397
8398    pub fn supplementary_language_servers(
8399        &self,
8400    ) -> impl '_
8401           + Iterator<
8402        Item = (
8403            &LanguageServerId,
8404            &(LanguageServerName, Arc<LanguageServer>),
8405        ),
8406    > {
8407        self.supplementary_language_servers.iter()
8408    }
8409
8410    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8411        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8412            Some(server.clone())
8413        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8414            Some(Arc::clone(server))
8415        } else {
8416            None
8417        }
8418    }
8419
8420    pub fn language_servers_for_buffer(
8421        &self,
8422        buffer: &Buffer,
8423        cx: &AppContext,
8424    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8425        self.language_server_ids_for_buffer(buffer, cx)
8426            .into_iter()
8427            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8428                LanguageServerState::Running {
8429                    adapter, server, ..
8430                } => Some((adapter, server)),
8431                _ => None,
8432            })
8433    }
8434
8435    fn primary_language_server_for_buffer(
8436        &self,
8437        buffer: &Buffer,
8438        cx: &AppContext,
8439    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8440        self.language_servers_for_buffer(buffer, cx).next()
8441    }
8442
8443    pub fn language_server_for_buffer(
8444        &self,
8445        buffer: &Buffer,
8446        server_id: LanguageServerId,
8447        cx: &AppContext,
8448    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8449        self.language_servers_for_buffer(buffer, cx)
8450            .find(|(_, s)| s.server_id() == server_id)
8451    }
8452
8453    fn language_server_ids_for_buffer(
8454        &self,
8455        buffer: &Buffer,
8456        cx: &AppContext,
8457    ) -> Vec<LanguageServerId> {
8458        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8459            let worktree_id = file.worktree_id(cx);
8460            language
8461                .lsp_adapters()
8462                .iter()
8463                .flat_map(|adapter| {
8464                    let key = (worktree_id, adapter.name.clone());
8465                    self.language_server_ids.get(&key).copied()
8466                })
8467                .collect()
8468        } else {
8469            Vec::new()
8470        }
8471    }
8472
8473    fn prettier_instance_for_buffer(
8474        &mut self,
8475        buffer: &Model<Buffer>,
8476        cx: &mut ModelContext<Self>,
8477    ) -> Task<
8478        Option<(
8479            Option<PathBuf>,
8480            Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>,
8481        )>,
8482    > {
8483        let buffer = buffer.read(cx);
8484        let buffer_file = buffer.file();
8485        let Some(buffer_language) = buffer.language() else {
8486            return Task::ready(None);
8487        };
8488        if buffer_language.prettier_parser_name().is_none() {
8489            return Task::ready(None);
8490        }
8491
8492        if self.is_local() {
8493            let Some(node) = self.node.as_ref().map(Arc::clone) else {
8494                return Task::ready(None);
8495            };
8496            match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx)))
8497            {
8498                Some((worktree_id, buffer_path)) => {
8499                    let fs = Arc::clone(&self.fs);
8500                    let installed_prettiers = self.prettier_instances.keys().cloned().collect();
8501                    return cx.spawn(|project, mut cx| async move {
8502                        match cx
8503                            .background_executor()
8504                            .spawn(async move {
8505                                Prettier::locate_prettier_installation(
8506                                    fs.as_ref(),
8507                                    &installed_prettiers,
8508                                    &buffer_path,
8509                                )
8510                                .await
8511                            })
8512                            .await
8513                        {
8514                            Ok(ControlFlow::Break(())) => {
8515                                return None;
8516                            }
8517                            Ok(ControlFlow::Continue(None)) => {
8518                                match project.update(&mut cx, |project, _| {
8519                                    project
8520                                        .prettiers_per_worktree
8521                                        .entry(worktree_id)
8522                                        .or_default()
8523                                        .insert(None);
8524                                    project.default_prettier.as_ref().and_then(
8525                                        |default_prettier| default_prettier.instance.clone(),
8526                                    )
8527                                }) {
8528                                    Ok(Some(old_task)) => Some((None, old_task)),
8529                                    Ok(None) => {
8530                                        match project.update(&mut cx, |_, cx| {
8531                                            start_default_prettier(node, Some(worktree_id), cx)
8532                                        }) {
8533                                            Ok(new_default_prettier) => {
8534                                                return Some((None, new_default_prettier.await))
8535                                            }
8536                                            Err(e) => {
8537                                                Some((
8538                                                    None,
8539                                                    Task::ready(Err(Arc::new(e.context("project is gone during default prettier startup"))))
8540                                                        .shared(),
8541                                                ))
8542                                            }
8543                                        }
8544                                    }
8545                                    Err(e) => Some((None, Task::ready(Err(Arc::new(e.context("project is gone during default prettier checks"))))
8546                                        .shared())),
8547                                }
8548                            }
8549                            Ok(ControlFlow::Continue(Some(prettier_dir))) => {
8550                                match project.update(&mut cx, |project, _| {
8551                                    project
8552                                        .prettiers_per_worktree
8553                                        .entry(worktree_id)
8554                                        .or_default()
8555                                        .insert(Some(prettier_dir.clone()));
8556                                    project.prettier_instances.get(&prettier_dir).cloned()
8557                                }) {
8558                                    Ok(Some(existing_prettier)) => {
8559                                        log::debug!(
8560                                            "Found already started prettier in {prettier_dir:?}"
8561                                        );
8562                                        return Some((Some(prettier_dir), existing_prettier));
8563                                    }
8564                                    Err(e) => {
8565                                        return Some((
8566                                            Some(prettier_dir),
8567                                            Task::ready(Err(Arc::new(e.context("project is gone during custom prettier checks"))))
8568                                            .shared(),
8569                                        ))
8570                                    }
8571                                    _ => {},
8572                                }
8573
8574                                log::info!("Found prettier in {prettier_dir:?}, starting.");
8575                                let new_prettier_task =
8576                                    match project.update(&mut cx, |project, cx| {
8577                                        let new_prettier_task = start_prettier(
8578                                            node,
8579                                            prettier_dir.clone(),
8580                                            Some(worktree_id),
8581                                            cx,
8582                                        );
8583                                        project.prettier_instances.insert(
8584                                            prettier_dir.clone(),
8585                                            new_prettier_task.clone(),
8586                                        );
8587                                        new_prettier_task
8588                                    }) {
8589                                        Ok(task) => task,
8590                                        Err(e) => return Some((
8591                                            Some(prettier_dir),
8592                                            Task::ready(Err(Arc::new(e.context("project is gone during custom prettier startup"))))
8593                                            .shared()
8594                                        )),
8595                                    };
8596                                Some((Some(prettier_dir), new_prettier_task))
8597                            }
8598                            Err(e) => {
8599                                return Some((
8600                                    None,
8601                                    Task::ready(Err(Arc::new(
8602                                        e.context("determining prettier path"),
8603                                    )))
8604                                    .shared(),
8605                                ));
8606                            }
8607                        }
8608                    });
8609                }
8610                None => {
8611                    let started_default_prettier = self
8612                        .default_prettier
8613                        .as_ref()
8614                        .and_then(|default_prettier| default_prettier.instance.clone());
8615                    match started_default_prettier {
8616                        Some(old_task) => return Task::ready(Some((None, old_task))),
8617                        None => {
8618                            let new_task = start_default_prettier(node, None, cx);
8619                            return cx.spawn(|_, _| async move { Some((None, new_task.await)) });
8620                        }
8621                    }
8622                }
8623            }
8624        } else if self.remote_id().is_some() {
8625            return Task::ready(None);
8626        } else {
8627            Task::ready(Some((
8628                None,
8629                Task::ready(Err(Arc::new(anyhow!("project does not have a remote id")))).shared(),
8630            )))
8631        }
8632    }
8633
8634    #[cfg(any(test, feature = "test-support"))]
8635    fn install_default_formatters(
8636        &mut self,
8637        _: Option<WorktreeId>,
8638        _: &Language,
8639        _: &LanguageSettings,
8640        _: &mut ModelContext<Self>,
8641    ) {
8642    }
8643
8644    #[cfg(not(any(test, feature = "test-support")))]
8645    fn install_default_formatters(
8646        &mut self,
8647        worktree: Option<WorktreeId>,
8648        new_language: &Language,
8649        language_settings: &LanguageSettings,
8650        cx: &mut ModelContext<Self>,
8651    ) {
8652        match &language_settings.formatter {
8653            Formatter::Prettier { .. } | Formatter::Auto => {}
8654            Formatter::LanguageServer | Formatter::External { .. } => return,
8655        };
8656        let Some(node) = self.node.as_ref().cloned() else {
8657            return;
8658        };
8659
8660        let mut prettier_plugins = None;
8661        if new_language.prettier_parser_name().is_some() {
8662            prettier_plugins
8663                .get_or_insert_with(|| HashSet::<&'static str>::default())
8664                .extend(
8665                    new_language
8666                        .lsp_adapters()
8667                        .iter()
8668                        .flat_map(|adapter| adapter.prettier_plugins()),
8669                )
8670        }
8671        let Some(prettier_plugins) = prettier_plugins else {
8672            return;
8673        };
8674
8675        let fs = Arc::clone(&self.fs);
8676        let locate_prettier_installation = match worktree.and_then(|worktree_id| {
8677            self.worktree_for_id(worktree_id, cx)
8678                .map(|worktree| worktree.read(cx).abs_path())
8679        }) {
8680            Some(locate_from) => {
8681                let installed_prettiers = self.prettier_instances.keys().cloned().collect();
8682                cx.background_executor().spawn(async move {
8683                    Prettier::locate_prettier_installation(
8684                        fs.as_ref(),
8685                        &installed_prettiers,
8686                        locate_from.as_ref(),
8687                    )
8688                    .await
8689                })
8690            }
8691            None => Task::ready(Ok(ControlFlow::Break(()))),
8692        };
8693        let mut plugins_to_install = prettier_plugins;
8694        let previous_installation_process =
8695            if let Some(default_prettier) = &mut self.default_prettier {
8696                plugins_to_install
8697                    .retain(|plugin| !default_prettier.installed_plugins.contains(plugin));
8698                if plugins_to_install.is_empty() {
8699                    return;
8700                }
8701                default_prettier.installation_process.clone()
8702            } else {
8703                None
8704            };
8705
8706        let fs = Arc::clone(&self.fs);
8707        let default_prettier = self
8708            .default_prettier
8709            .get_or_insert_with(|| DefaultPrettier {
8710                instance: None,
8711                installation_process: None,
8712                installed_plugins: HashSet::default(),
8713            });
8714        default_prettier.installation_process = Some(
8715            cx.spawn(|this, mut cx| async move {
8716                match locate_prettier_installation
8717                    .await
8718                    .context("locate prettier installation")
8719                    .map_err(Arc::new)?
8720                {
8721                    ControlFlow::Break(()) => return Ok(()),
8722                    ControlFlow::Continue(Some(_non_default_prettier)) => return Ok(()),
8723                    ControlFlow::Continue(None) => {
8724                        let mut needs_install = match previous_installation_process {
8725                            Some(previous_installation_process) => {
8726                                previous_installation_process.await.is_err()
8727                            }
8728                            None => true,
8729                        };
8730                        this.update(&mut cx, |this, _| {
8731                            if let Some(default_prettier) = &mut this.default_prettier {
8732                                plugins_to_install.retain(|plugin| {
8733                                    !default_prettier.installed_plugins.contains(plugin)
8734                                });
8735                                needs_install |= !plugins_to_install.is_empty();
8736                            }
8737                        })?;
8738                        if needs_install {
8739                            let installed_plugins = plugins_to_install.clone();
8740                            cx.background_executor()
8741                                .spawn(async move {
8742                                    install_default_prettier(plugins_to_install, node, fs).await
8743                                })
8744                                .await
8745                                .context("prettier & plugins install")
8746                                .map_err(Arc::new)?;
8747                            this.update(&mut cx, |this, _| {
8748                                let default_prettier =
8749                                    this.default_prettier
8750                                        .get_or_insert_with(|| DefaultPrettier {
8751                                            instance: None,
8752                                            installation_process: Some(
8753                                                Task::ready(Ok(())).shared(),
8754                                            ),
8755                                            installed_plugins: HashSet::default(),
8756                                        });
8757                                default_prettier.instance = None;
8758                                default_prettier.installed_plugins.extend(installed_plugins);
8759                            })?;
8760                        }
8761                    }
8762                }
8763                Ok(())
8764            })
8765            .shared(),
8766        );
8767    }
8768}
8769
8770fn start_default_prettier(
8771    node: Arc<dyn NodeRuntime>,
8772    worktree_id: Option<WorktreeId>,
8773    cx: &mut ModelContext<'_, Project>,
8774) -> Task<Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>> {
8775    cx.spawn(|project, mut cx| async move {
8776        loop {
8777            let default_prettier_installing = match project.update(&mut cx, |project, _| {
8778                project
8779                    .default_prettier
8780                    .as_ref()
8781                    .and_then(|default_prettier| default_prettier.installation_process.clone())
8782            }) {
8783                Ok(installation) => installation,
8784                Err(e) => {
8785                    return Task::ready(Err(Arc::new(
8786                        e.context("project is gone during default prettier installation"),
8787                    )))
8788                    .shared()
8789                }
8790            };
8791            match default_prettier_installing {
8792                Some(installation_task) => {
8793                    if installation_task.await.is_ok() {
8794                        break;
8795                    }
8796                }
8797                None => break,
8798            }
8799        }
8800
8801        match project.update(&mut cx, |project, cx| {
8802            match project
8803                .default_prettier
8804                .as_mut()
8805                .and_then(|default_prettier| default_prettier.instance.as_mut())
8806            {
8807                Some(default_prettier) => default_prettier.clone(),
8808                None => {
8809                    let new_default_prettier =
8810                        start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), worktree_id, cx);
8811                    project
8812                        .default_prettier
8813                        .get_or_insert_with(|| DefaultPrettier {
8814                            instance: None,
8815                            installation_process: None,
8816                            #[cfg(not(any(test, feature = "test-support")))]
8817                            installed_plugins: HashSet::default(),
8818                        })
8819                        .instance = Some(new_default_prettier.clone());
8820                    new_default_prettier
8821                }
8822            }
8823        }) {
8824            Ok(task) => task,
8825            Err(e) => Task::ready(Err(Arc::new(
8826                e.context("project is gone during default prettier startup"),
8827            )))
8828            .shared(),
8829        }
8830    })
8831}
8832
8833fn start_prettier(
8834    node: Arc<dyn NodeRuntime>,
8835    prettier_dir: PathBuf,
8836    worktree_id: Option<WorktreeId>,
8837    cx: &mut ModelContext<'_, Project>,
8838) -> Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>> {
8839    cx.spawn(|project, mut cx| async move {
8840        let new_server_id = project.update(&mut cx, |project, _| {
8841            project.languages.next_language_server_id()
8842        })?;
8843        let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone())
8844            .await
8845            .context("default prettier spawn")
8846            .map(Arc::new)
8847            .map_err(Arc::new)?;
8848        register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx);
8849        Ok(new_prettier)
8850    })
8851    .shared()
8852}
8853
8854fn register_new_prettier(
8855    project: &WeakModel<Project>,
8856    prettier: &Prettier,
8857    worktree_id: Option<WorktreeId>,
8858    new_server_id: LanguageServerId,
8859    cx: &mut AsyncAppContext,
8860) {
8861    let prettier_dir = prettier.prettier_dir();
8862    let is_default = prettier.is_default();
8863    if is_default {
8864        log::info!("Started default prettier in {prettier_dir:?}");
8865    } else {
8866        log::info!("Started prettier in {prettier_dir:?}");
8867    }
8868    if let Some(prettier_server) = prettier.server() {
8869        project
8870            .update(cx, |project, cx| {
8871                let name = if is_default {
8872                    LanguageServerName(Arc::from("prettier (default)"))
8873                } else {
8874                    let worktree_path = worktree_id
8875                        .and_then(|id| project.worktree_for_id(id, cx))
8876                        .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path()));
8877                    let name = match worktree_path {
8878                        Some(worktree_path) => {
8879                            if prettier_dir == worktree_path.as_ref() {
8880                                let name = prettier_dir
8881                                    .file_name()
8882                                    .and_then(|name| name.to_str())
8883                                    .unwrap_or_default();
8884                                format!("prettier ({name})")
8885                            } else {
8886                                let dir_to_display = prettier_dir
8887                                    .strip_prefix(worktree_path.as_ref())
8888                                    .ok()
8889                                    .unwrap_or(prettier_dir);
8890                                format!("prettier ({})", dir_to_display.display())
8891                            }
8892                        }
8893                        None => format!("prettier ({})", prettier_dir.display()),
8894                    };
8895                    LanguageServerName(Arc::from(name))
8896                };
8897                project
8898                    .supplementary_language_servers
8899                    .insert(new_server_id, (name, Arc::clone(prettier_server)));
8900                cx.emit(Event::LanguageServerAdded(new_server_id));
8901            })
8902            .ok();
8903    }
8904}
8905
8906#[cfg(not(any(test, feature = "test-support")))]
8907async fn install_default_prettier(
8908    plugins_to_install: HashSet<&'static str>,
8909    node: Arc<dyn NodeRuntime>,
8910    fs: Arc<dyn Fs>,
8911) -> anyhow::Result<()> {
8912    let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE);
8913    // method creates parent directory if it doesn't exist
8914    fs.save(
8915        &prettier_wrapper_path,
8916        &text::Rope::from(prettier::PRETTIER_SERVER_JS),
8917        text::LineEnding::Unix,
8918    )
8919    .await
8920    .with_context(|| {
8921        format!(
8922            "writing {} file at {prettier_wrapper_path:?}",
8923            prettier::PRETTIER_SERVER_FILE
8924        )
8925    })?;
8926
8927    let packages_to_versions =
8928        future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map(
8929            |package_name| async {
8930                let returned_package_name = package_name.to_string();
8931                let latest_version = node
8932                    .npm_package_latest_version(package_name)
8933                    .await
8934                    .with_context(|| {
8935                        format!("fetching latest npm version for package {returned_package_name}")
8936                    })?;
8937                anyhow::Ok((returned_package_name, latest_version))
8938            },
8939        ))
8940        .await
8941        .context("fetching latest npm versions")?;
8942
8943    log::info!("Fetching default prettier and plugins: {packages_to_versions:?}");
8944    let borrowed_packages = packages_to_versions
8945        .iter()
8946        .map(|(package, version)| (package.as_str(), version.as_str()))
8947        .collect::<Vec<_>>();
8948    node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages)
8949        .await
8950        .context("fetching formatter packages")?;
8951    anyhow::Ok(())
8952}
8953
8954fn subscribe_for_copilot_events(
8955    copilot: &Model<Copilot>,
8956    cx: &mut ModelContext<'_, Project>,
8957) -> gpui::Subscription {
8958    cx.subscribe(
8959        copilot,
8960        |project, copilot, copilot_event, cx| match copilot_event {
8961            copilot::Event::CopilotLanguageServerStarted => {
8962                match copilot.read(cx).language_server() {
8963                    Some((name, copilot_server)) => {
8964                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8965                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8966                            let new_server_id = copilot_server.server_id();
8967                            let weak_project = cx.weak_model();
8968                            let copilot_log_subscription = copilot_server
8969                                .on_notification::<copilot::request::LogMessage, _>(
8970                                    move |params, mut cx| {
8971                                        weak_project.update(&mut cx, |_, cx| {
8972                                            cx.emit(Event::LanguageServerLog(
8973                                                new_server_id,
8974                                                params.message,
8975                                            ));
8976                                        }).ok();
8977                                    },
8978                                );
8979                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8980                            project.copilot_log_subscription = Some(copilot_log_subscription);
8981                            cx.emit(Event::LanguageServerAdded(new_server_id));
8982                        }
8983                    }
8984                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8985                }
8986            }
8987        },
8988    )
8989}
8990
8991fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8992    let mut literal_end = 0;
8993    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8994        if part.contains(&['*', '?', '{', '}']) {
8995            break;
8996        } else {
8997            if i > 0 {
8998                // Acount for separator prior to this part
8999                literal_end += path::MAIN_SEPARATOR.len_utf8();
9000            }
9001            literal_end += part.len();
9002        }
9003    }
9004    &glob[..literal_end]
9005}
9006
9007impl WorktreeHandle {
9008    pub fn upgrade(&self) -> Option<Model<Worktree>> {
9009        match self {
9010            WorktreeHandle::Strong(handle) => Some(handle.clone()),
9011            WorktreeHandle::Weak(handle) => handle.upgrade(),
9012        }
9013    }
9014
9015    pub fn handle_id(&self) -> usize {
9016        match self {
9017            WorktreeHandle::Strong(handle) => handle.entity_id().as_u64() as usize,
9018            WorktreeHandle::Weak(handle) => handle.entity_id().as_u64() as usize,
9019        }
9020    }
9021}
9022
9023impl OpenBuffer {
9024    pub fn upgrade(&self) -> Option<Model<Buffer>> {
9025        match self {
9026            OpenBuffer::Strong(handle) => Some(handle.clone()),
9027            OpenBuffer::Weak(handle) => handle.upgrade(),
9028            OpenBuffer::Operations(_) => None,
9029        }
9030    }
9031}
9032
9033pub struct PathMatchCandidateSet {
9034    pub snapshot: Snapshot,
9035    pub include_ignored: bool,
9036    pub include_root_name: bool,
9037}
9038
9039impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
9040    type Candidates = PathMatchCandidateSetIter<'a>;
9041
9042    fn id(&self) -> usize {
9043        self.snapshot.id().to_usize()
9044    }
9045
9046    fn len(&self) -> usize {
9047        if self.include_ignored {
9048            self.snapshot.file_count()
9049        } else {
9050            self.snapshot.visible_file_count()
9051        }
9052    }
9053
9054    fn prefix(&self) -> Arc<str> {
9055        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
9056            self.snapshot.root_name().into()
9057        } else if self.include_root_name {
9058            format!("{}/", self.snapshot.root_name()).into()
9059        } else {
9060            "".into()
9061        }
9062    }
9063
9064    fn candidates(&'a self, start: usize) -> Self::Candidates {
9065        PathMatchCandidateSetIter {
9066            traversal: self.snapshot.files(self.include_ignored, start),
9067        }
9068    }
9069}
9070
9071pub struct PathMatchCandidateSetIter<'a> {
9072    traversal: Traversal<'a>,
9073}
9074
9075impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
9076    type Item = fuzzy::PathMatchCandidate<'a>;
9077
9078    fn next(&mut self) -> Option<Self::Item> {
9079        self.traversal.next().map(|entry| {
9080            if let EntryKind::File(char_bag) = entry.kind {
9081                fuzzy::PathMatchCandidate {
9082                    path: &entry.path,
9083                    char_bag,
9084                }
9085            } else {
9086                unreachable!()
9087            }
9088        })
9089    }
9090}
9091
9092impl EventEmitter<Event> for Project {}
9093
9094impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
9095    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
9096        Self {
9097            worktree_id,
9098            path: path.as_ref().into(),
9099        }
9100    }
9101}
9102
9103impl ProjectLspAdapterDelegate {
9104    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
9105        Arc::new(Self {
9106            project: cx.handle(),
9107            http_client: project.client.http_client(),
9108        })
9109    }
9110}
9111
9112impl LspAdapterDelegate for ProjectLspAdapterDelegate {
9113    fn show_notification(&self, message: &str, cx: &mut AppContext) {
9114        self.project
9115            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
9116    }
9117
9118    fn http_client(&self) -> Arc<dyn HttpClient> {
9119        self.http_client.clone()
9120    }
9121}
9122
9123fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9124    proto::Symbol {
9125        language_server_name: symbol.language_server_name.0.to_string(),
9126        source_worktree_id: symbol.source_worktree_id.to_proto(),
9127        worktree_id: symbol.path.worktree_id.to_proto(),
9128        path: symbol.path.path.to_string_lossy().to_string(),
9129        name: symbol.name.clone(),
9130        kind: unsafe { mem::transmute(symbol.kind) },
9131        start: Some(proto::PointUtf16 {
9132            row: symbol.range.start.0.row,
9133            column: symbol.range.start.0.column,
9134        }),
9135        end: Some(proto::PointUtf16 {
9136            row: symbol.range.end.0.row,
9137            column: symbol.range.end.0.column,
9138        }),
9139        signature: symbol.signature.to_vec(),
9140    }
9141}
9142
9143fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9144    let mut path_components = path.components();
9145    let mut base_components = base.components();
9146    let mut components: Vec<Component> = Vec::new();
9147    loop {
9148        match (path_components.next(), base_components.next()) {
9149            (None, None) => break,
9150            (Some(a), None) => {
9151                components.push(a);
9152                components.extend(path_components.by_ref());
9153                break;
9154            }
9155            (None, _) => components.push(Component::ParentDir),
9156            (Some(a), Some(b)) if components.is_empty() && a == b => (),
9157            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
9158            (Some(a), Some(_)) => {
9159                components.push(Component::ParentDir);
9160                for _ in base_components {
9161                    components.push(Component::ParentDir);
9162                }
9163                components.push(a);
9164                components.extend(path_components.by_ref());
9165                break;
9166            }
9167        }
9168    }
9169    components.iter().map(|c| c.as_os_str()).collect()
9170}
9171
9172impl Item for Buffer {
9173    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9174        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9175    }
9176
9177    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9178        File::from_dyn(self.file()).map(|file| ProjectPath {
9179            worktree_id: file.worktree_id(cx),
9180            path: file.path().clone(),
9181        })
9182    }
9183}
9184
9185async fn wait_for_loading_buffer(
9186    mut receiver: postage::watch::Receiver<Option<Result<Model<Buffer>, Arc<anyhow::Error>>>>,
9187) -> Result<Model<Buffer>, Arc<anyhow::Error>> {
9188    loop {
9189        if let Some(result) = receiver.borrow().as_ref() {
9190            match result {
9191                Ok(buffer) => return Ok(buffer.to_owned()),
9192                Err(e) => return Err(e.to_owned()),
9193            }
9194        }
9195        receiver.next().await;
9196    }
9197}
9198
9199fn include_text(server: &lsp::LanguageServer) -> bool {
9200    server
9201        .capabilities()
9202        .text_document_sync
9203        .as_ref()
9204        .and_then(|sync| match sync {
9205            lsp::TextDocumentSyncCapability::Kind(_) => None,
9206            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9207        })
9208        .and_then(|save_options| match save_options {
9209            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9210            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9211        })
9212        .unwrap_or(false)
9213}