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