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