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