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