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<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(languages.clone(), 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(languages.clone(), 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
1572        let buffer = cx.add_model(|cx| {
1573            Buffer::new(self.replica_id(), text, cx)
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    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(
2476        languages: Arc<LanguageRegistry>,
2477        cx: &mut ModelContext<Project>,
2478    ) -> Task<()> {
2479        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2480        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2481
2482        let settings_observation = cx.observe_global::<SettingsStore, _>(move |_, _| {
2483            *settings_changed_tx.borrow_mut() = ();
2484        });
2485        cx.spawn_weak(|this, mut cx| async move {
2486            while let Some(_) = settings_changed_rx.next().await {
2487                let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2488                if let Some(this) = this.upgrade(&cx) {
2489                    this.read_with(&cx, |this, _| {
2490                        for server_state in this.language_servers.values() {
2491                            if let LanguageServerState::Running { server, .. } = server_state {
2492                                server
2493                                    .notify::<lsp::notification::DidChangeConfiguration>(
2494                                        lsp::DidChangeConfigurationParams {
2495                                            settings: workspace_config.clone(),
2496                                        },
2497                                    )
2498                                    .ok();
2499                            }
2500                        }
2501                    })
2502                } else {
2503                    break;
2504                }
2505            }
2506
2507            drop(settings_observation);
2508        })
2509    }
2510
2511    fn detect_language_for_buffer(
2512        &mut self,
2513        buffer_handle: &ModelHandle<Buffer>,
2514        cx: &mut ModelContext<Self>,
2515    ) -> Option<()> {
2516        // If the buffer has a language, set it and start the language server if we haven't already.
2517        let buffer = buffer_handle.read(cx);
2518        let full_path = buffer.file()?.full_path(cx);
2519        let content = buffer.as_rope();
2520        let new_language = self
2521            .languages
2522            .language_for_file(&full_path, Some(content))
2523            .now_or_never()?
2524            .ok()?;
2525        self.set_language_for_buffer(buffer_handle, new_language, cx);
2526        None
2527    }
2528
2529    pub fn set_language_for_buffer(
2530        &mut self,
2531        buffer: &ModelHandle<Buffer>,
2532        new_language: Arc<Language>,
2533        cx: &mut ModelContext<Self>,
2534    ) {
2535        buffer.update(cx, |buffer, cx| {
2536            if buffer.language().map_or(true, |old_language| {
2537                !Arc::ptr_eq(old_language, &new_language)
2538            }) {
2539                buffer.set_language(Some(new_language.clone()), cx);
2540            }
2541        });
2542
2543        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
2544            let worktree = file.worktree.clone();
2545            if let Some(tree) = worktree.read(cx).as_local() {
2546                self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2547            }
2548        }
2549    }
2550
2551    fn start_language_servers(
2552        &mut self,
2553        worktree: &ModelHandle<Worktree>,
2554        worktree_path: Arc<Path>,
2555        language: Arc<Language>,
2556        cx: &mut ModelContext<Self>,
2557    ) {
2558        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2559        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2560        if !settings.enable_language_server {
2561            return;
2562        }
2563
2564        let worktree_id = worktree.read(cx).id();
2565        for adapter in language.lsp_adapters() {
2566            self.start_language_server(
2567                worktree_id,
2568                worktree_path.clone(),
2569                adapter.clone(),
2570                language.clone(),
2571                cx,
2572            );
2573        }
2574    }
2575
2576    fn start_language_server(
2577        &mut self,
2578        worktree_id: WorktreeId,
2579        worktree_path: Arc<Path>,
2580        adapter: Arc<CachedLspAdapter>,
2581        language: Arc<Language>,
2582        cx: &mut ModelContext<Self>,
2583    ) {
2584        let key = (worktree_id, adapter.name.clone());
2585        if self.language_server_ids.contains_key(&key) {
2586            return;
2587        }
2588
2589        let pending_server = match self.languages.create_pending_language_server(
2590            language.clone(),
2591            adapter.clone(),
2592            worktree_path,
2593            ProjectLspAdapterDelegate::new(self, cx),
2594            cx,
2595        ) {
2596            Some(pending_server) => pending_server,
2597            None => return,
2598        };
2599
2600        let project_settings = settings::get::<ProjectSettings>(cx);
2601        let lsp = project_settings.lsp.get(&adapter.name.0);
2602        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2603
2604        let mut initialization_options = adapter.initialization_options.clone();
2605        match (&mut initialization_options, override_options) {
2606            (Some(initialization_options), Some(override_options)) => {
2607                merge_json_value_into(override_options, initialization_options);
2608            }
2609            (None, override_options) => initialization_options = override_options,
2610            _ => {}
2611        }
2612
2613        let server_id = pending_server.server_id;
2614        let container_dir = pending_server.container_dir.clone();
2615        let state = LanguageServerState::Starting({
2616            let adapter = adapter.clone();
2617            let server_name = adapter.name.0.clone();
2618            let languages = self.languages.clone();
2619            let language = language.clone();
2620            let key = key.clone();
2621
2622            cx.spawn_weak(|this, mut cx| async move {
2623                let result = Self::setup_and_insert_language_server(
2624                    this,
2625                    initialization_options,
2626                    pending_server,
2627                    adapter.clone(),
2628                    languages,
2629                    language.clone(),
2630                    server_id,
2631                    key,
2632                    &mut cx,
2633                )
2634                .await;
2635
2636                match result {
2637                    Ok(server) => server,
2638
2639                    Err(err) => {
2640                        log::error!("failed to start language server {:?}: {}", server_name, err);
2641
2642                        if let Some(this) = this.upgrade(&cx) {
2643                            if let Some(container_dir) = container_dir {
2644                                let installation_test_binary = adapter
2645                                    .installation_test_binary(container_dir.to_path_buf())
2646                                    .await;
2647
2648                                this.update(&mut cx, |_, cx| {
2649                                    Self::check_errored_server(
2650                                        language,
2651                                        adapter,
2652                                        server_id,
2653                                        installation_test_binary,
2654                                        cx,
2655                                    )
2656                                });
2657                            }
2658                        }
2659
2660                        None
2661                    }
2662                }
2663            })
2664        });
2665
2666        self.language_servers.insert(server_id, state);
2667        self.language_server_ids.insert(key, server_id);
2668    }
2669
2670    fn reinstall_language_server(
2671        &mut self,
2672        language: Arc<Language>,
2673        adapter: Arc<CachedLspAdapter>,
2674        server_id: LanguageServerId,
2675        cx: &mut ModelContext<Self>,
2676    ) -> Option<Task<()>> {
2677        log::info!("beginning to reinstall server");
2678
2679        let existing_server = match self.language_servers.remove(&server_id) {
2680            Some(LanguageServerState::Running { server, .. }) => Some(server),
2681            _ => None,
2682        };
2683
2684        for worktree in &self.worktrees {
2685            if let Some(worktree) = worktree.upgrade(cx) {
2686                let key = (worktree.read(cx).id(), adapter.name.clone());
2687                self.language_server_ids.remove(&key);
2688            }
2689        }
2690
2691        Some(cx.spawn(move |this, mut cx| async move {
2692            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2693                log::info!("shutting down existing server");
2694                task.await;
2695            }
2696
2697            // TODO: This is race-safe with regards to preventing new instances from
2698            // starting while deleting, but existing instances in other projects are going
2699            // to be very confused and messed up
2700            this.update(&mut cx, |this, cx| {
2701                this.languages.delete_server_container(adapter.clone(), cx)
2702            })
2703            .await;
2704
2705            this.update(&mut cx, |this, mut cx| {
2706                let worktrees = this.worktrees.clone();
2707                for worktree in worktrees {
2708                    let worktree = match worktree.upgrade(cx) {
2709                        Some(worktree) => worktree.read(cx),
2710                        None => continue,
2711                    };
2712                    let worktree_id = worktree.id();
2713                    let root_path = worktree.abs_path();
2714
2715                    this.start_language_server(
2716                        worktree_id,
2717                        root_path,
2718                        adapter.clone(),
2719                        language.clone(),
2720                        &mut cx,
2721                    );
2722                }
2723            })
2724        }))
2725    }
2726
2727    async fn setup_and_insert_language_server(
2728        this: WeakModelHandle<Self>,
2729        initialization_options: Option<serde_json::Value>,
2730        pending_server: PendingLanguageServer,
2731        adapter: Arc<CachedLspAdapter>,
2732        languages: Arc<LanguageRegistry>,
2733        language: Arc<Language>,
2734        server_id: LanguageServerId,
2735        key: (WorktreeId, LanguageServerName),
2736        cx: &mut AsyncAppContext,
2737    ) -> Result<Option<Arc<LanguageServer>>> {
2738        let setup = Self::setup_pending_language_server(
2739            this,
2740            initialization_options,
2741            pending_server,
2742            adapter.clone(),
2743            languages,
2744            server_id,
2745            cx,
2746        );
2747
2748        let language_server = match setup.await? {
2749            Some(language_server) => language_server,
2750            None => return Ok(None),
2751        };
2752        let this = match this.upgrade(cx) {
2753            Some(this) => this,
2754            None => return Err(anyhow!("failed to upgrade project handle")),
2755        };
2756
2757        this.update(cx, |this, cx| {
2758            this.insert_newly_running_language_server(
2759                language,
2760                adapter,
2761                language_server.clone(),
2762                server_id,
2763                key,
2764                cx,
2765            )
2766        })?;
2767
2768        Ok(Some(language_server))
2769    }
2770
2771    async fn setup_pending_language_server(
2772        this: WeakModelHandle<Self>,
2773        initialization_options: Option<serde_json::Value>,
2774        pending_server: PendingLanguageServer,
2775        adapter: Arc<CachedLspAdapter>,
2776        languages: Arc<LanguageRegistry>,
2777        server_id: LanguageServerId,
2778        cx: &mut AsyncAppContext,
2779    ) -> Result<Option<Arc<LanguageServer>>> {
2780        let workspace_config = cx.update(|cx| languages.workspace_configuration(cx)).await;
2781        let language_server = match pending_server.task.await? {
2782            Some(server) => server.initialize(initialization_options).await?,
2783            None => {
2784                return Ok(None);
2785            }
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 languages = languages.clone();
2825                move |params, mut cx| {
2826                    let languages = languages.clone();
2827                    async move {
2828                        let workspace_config =
2829                            cx.update(|cx| languages.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        language_server
2936            .notify::<lsp::notification::DidChangeConfiguration>(
2937                lsp::DidChangeConfigurationParams {
2938                    settings: workspace_config,
2939                },
2940            )
2941            .ok();
2942
2943        Ok(Some(language_server))
2944    }
2945
2946    fn insert_newly_running_language_server(
2947        &mut self,
2948        language: Arc<Language>,
2949        adapter: Arc<CachedLspAdapter>,
2950        language_server: Arc<LanguageServer>,
2951        server_id: LanguageServerId,
2952        key: (WorktreeId, LanguageServerName),
2953        cx: &mut ModelContext<Self>,
2954    ) -> Result<()> {
2955        // If the language server for this key doesn't match the server id, don't store the
2956        // server. Which will cause it to be dropped, killing the process
2957        if self
2958            .language_server_ids
2959            .get(&key)
2960            .map(|id| id != &server_id)
2961            .unwrap_or(false)
2962        {
2963            return Ok(());
2964        }
2965
2966        // Update language_servers collection with Running variant of LanguageServerState
2967        // indicating that the server is up and running and ready
2968        self.language_servers.insert(
2969            server_id,
2970            LanguageServerState::Running {
2971                adapter: adapter.clone(),
2972                language: language.clone(),
2973                watched_paths: Default::default(),
2974                server: language_server.clone(),
2975                simulate_disk_based_diagnostics_completion: None,
2976            },
2977        );
2978
2979        self.language_server_statuses.insert(
2980            server_id,
2981            LanguageServerStatus {
2982                name: language_server.name().to_string(),
2983                pending_work: Default::default(),
2984                has_pending_diagnostic_updates: false,
2985                progress_tokens: Default::default(),
2986            },
2987        );
2988
2989        cx.emit(Event::LanguageServerAdded(server_id));
2990
2991        if let Some(project_id) = self.remote_id() {
2992            self.client.send(proto::StartLanguageServer {
2993                project_id,
2994                server: Some(proto::LanguageServer {
2995                    id: server_id.0 as u64,
2996                    name: language_server.name().to_string(),
2997                }),
2998            })?;
2999        }
3000
3001        // Tell the language server about every open buffer in the worktree that matches the language.
3002        for buffer in self.opened_buffers.values() {
3003            if let Some(buffer_handle) = buffer.upgrade(cx) {
3004                let buffer = buffer_handle.read(cx);
3005                let file = match File::from_dyn(buffer.file()) {
3006                    Some(file) => file,
3007                    None => continue,
3008                };
3009                let language = match buffer.language() {
3010                    Some(language) => language,
3011                    None => continue,
3012                };
3013
3014                if file.worktree.read(cx).id() != key.0
3015                    || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3016                {
3017                    continue;
3018                }
3019
3020                let file = match file.as_local() {
3021                    Some(file) => file,
3022                    None => continue,
3023                };
3024
3025                let versions = self
3026                    .buffer_snapshots
3027                    .entry(buffer.remote_id())
3028                    .or_default()
3029                    .entry(server_id)
3030                    .or_insert_with(|| {
3031                        vec![LspBufferSnapshot {
3032                            version: 0,
3033                            snapshot: buffer.text_snapshot(),
3034                        }]
3035                    });
3036
3037                let snapshot = versions.last().unwrap();
3038                let version = snapshot.version;
3039                let initial_snapshot = &snapshot.snapshot;
3040                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3041                language_server.notify::<lsp::notification::DidOpenTextDocument>(
3042                    lsp::DidOpenTextDocumentParams {
3043                        text_document: lsp::TextDocumentItem::new(
3044                            uri,
3045                            adapter
3046                                .language_ids
3047                                .get(language.name().as_ref())
3048                                .cloned()
3049                                .unwrap_or_default(),
3050                            version,
3051                            initial_snapshot.text(),
3052                        ),
3053                    },
3054                )?;
3055
3056                buffer_handle.update(cx, |buffer, cx| {
3057                    buffer.set_completion_triggers(
3058                        language_server
3059                            .capabilities()
3060                            .completion_provider
3061                            .as_ref()
3062                            .and_then(|provider| provider.trigger_characters.clone())
3063                            .unwrap_or_default(),
3064                        cx,
3065                    )
3066                });
3067            }
3068        }
3069
3070        cx.notify();
3071        Ok(())
3072    }
3073
3074    // Returns a list of all of the worktrees which no longer have a language server and the root path
3075    // for the stopped server
3076    fn stop_language_server(
3077        &mut self,
3078        worktree_id: WorktreeId,
3079        adapter_name: LanguageServerName,
3080        cx: &mut ModelContext<Self>,
3081    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3082        let key = (worktree_id, adapter_name);
3083        if let Some(server_id) = self.language_server_ids.remove(&key) {
3084            log::info!("stopping language server {}", key.1 .0);
3085
3086            // Remove other entries for this language server as well
3087            let mut orphaned_worktrees = vec![worktree_id];
3088            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3089            for other_key in other_keys {
3090                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3091                    self.language_server_ids.remove(&other_key);
3092                    orphaned_worktrees.push(other_key.0);
3093                }
3094            }
3095
3096            for buffer in self.opened_buffers.values() {
3097                if let Some(buffer) = buffer.upgrade(cx) {
3098                    buffer.update(cx, |buffer, cx| {
3099                        buffer.update_diagnostics(server_id, Default::default(), cx);
3100                    });
3101                }
3102            }
3103            for worktree in &self.worktrees {
3104                if let Some(worktree) = worktree.upgrade(cx) {
3105                    worktree.update(cx, |worktree, cx| {
3106                        if let Some(worktree) = worktree.as_local_mut() {
3107                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3108                        }
3109                    });
3110                }
3111            }
3112
3113            self.language_server_statuses.remove(&server_id);
3114            cx.notify();
3115
3116            let server_state = self.language_servers.remove(&server_id);
3117            cx.emit(Event::LanguageServerRemoved(server_id));
3118            cx.spawn_weak(|this, mut cx| async move {
3119                let mut root_path = None;
3120
3121                let server = match server_state {
3122                    Some(LanguageServerState::Starting(task)) => task.await,
3123                    Some(LanguageServerState::Running { server, .. }) => Some(server),
3124                    None => None,
3125                };
3126
3127                if let Some(server) = server {
3128                    root_path = Some(server.root_path().clone());
3129                    if let Some(shutdown) = server.shutdown() {
3130                        shutdown.await;
3131                    }
3132                }
3133
3134                if let Some(this) = this.upgrade(&cx) {
3135                    this.update(&mut cx, |this, cx| {
3136                        this.language_server_statuses.remove(&server_id);
3137                        cx.notify();
3138                    });
3139                }
3140
3141                (root_path, orphaned_worktrees)
3142            })
3143        } else {
3144            Task::ready((None, Vec::new()))
3145        }
3146    }
3147
3148    pub fn restart_language_servers_for_buffers(
3149        &mut self,
3150        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
3151        cx: &mut ModelContext<Self>,
3152    ) -> Option<()> {
3153        let language_server_lookup_info: HashSet<(ModelHandle<Worktree>, Arc<Language>)> = buffers
3154            .into_iter()
3155            .filter_map(|buffer| {
3156                let buffer = buffer.read(cx);
3157                let file = File::from_dyn(buffer.file())?;
3158                let full_path = file.full_path(cx);
3159                let language = self
3160                    .languages
3161                    .language_for_file(&full_path, Some(buffer.as_rope()))
3162                    .now_or_never()?
3163                    .ok()?;
3164                Some((file.worktree.clone(), language))
3165            })
3166            .collect();
3167        for (worktree, language) in language_server_lookup_info {
3168            self.restart_language_servers(worktree, language, cx);
3169        }
3170
3171        None
3172    }
3173
3174    // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3175    fn restart_language_servers(
3176        &mut self,
3177        worktree: ModelHandle<Worktree>,
3178        language: Arc<Language>,
3179        cx: &mut ModelContext<Self>,
3180    ) {
3181        let worktree_id = worktree.read(cx).id();
3182        let fallback_path = worktree.read(cx).abs_path();
3183
3184        let mut stops = Vec::new();
3185        for adapter in language.lsp_adapters() {
3186            stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3187        }
3188
3189        if stops.is_empty() {
3190            return;
3191        }
3192        let mut stops = stops.into_iter();
3193
3194        cx.spawn_weak(|this, mut cx| async move {
3195            let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3196            for stop in stops {
3197                let (_, worktrees) = stop.await;
3198                orphaned_worktrees.extend_from_slice(&worktrees);
3199            }
3200
3201            let this = match this.upgrade(&cx) {
3202                Some(this) => this,
3203                None => return,
3204            };
3205
3206            this.update(&mut cx, |this, cx| {
3207                // Attempt to restart using original server path. Fallback to passed in
3208                // path if we could not retrieve the root path
3209                let root_path = original_root_path
3210                    .map(|path_buf| Arc::from(path_buf.as_path()))
3211                    .unwrap_or(fallback_path);
3212
3213                this.start_language_servers(&worktree, root_path, language.clone(), cx);
3214
3215                // Lookup new server ids and set them for each of the orphaned worktrees
3216                for adapter in language.lsp_adapters() {
3217                    if let Some(new_server_id) = this
3218                        .language_server_ids
3219                        .get(&(worktree_id, adapter.name.clone()))
3220                        .cloned()
3221                    {
3222                        for &orphaned_worktree in &orphaned_worktrees {
3223                            this.language_server_ids
3224                                .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3225                        }
3226                    }
3227                }
3228            });
3229        })
3230        .detach();
3231    }
3232
3233    fn check_errored_server(
3234        language: Arc<Language>,
3235        adapter: Arc<CachedLspAdapter>,
3236        server_id: LanguageServerId,
3237        installation_test_binary: Option<LanguageServerBinary>,
3238        cx: &mut ModelContext<Self>,
3239    ) {
3240        if !adapter.can_be_reinstalled() {
3241            log::info!(
3242                "Validation check requested for {:?} but it cannot be reinstalled",
3243                adapter.name.0
3244            );
3245            return;
3246        }
3247
3248        cx.spawn(|this, mut cx| async move {
3249            log::info!("About to spawn test binary");
3250
3251            // A lack of test binary counts as a failure
3252            let process = installation_test_binary.and_then(|binary| {
3253                smol::process::Command::new(&binary.path)
3254                    .current_dir(&binary.path)
3255                    .args(binary.arguments)
3256                    .stdin(Stdio::piped())
3257                    .stdout(Stdio::piped())
3258                    .stderr(Stdio::inherit())
3259                    .kill_on_drop(true)
3260                    .spawn()
3261                    .ok()
3262            });
3263
3264            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3265            let mut timeout = cx.background().timer(PROCESS_TIMEOUT).fuse();
3266
3267            let mut errored = false;
3268            if let Some(mut process) = process {
3269                futures::select! {
3270                    status = process.status().fuse() => match status {
3271                        Ok(status) => errored = !status.success(),
3272                        Err(_) => errored = true,
3273                    },
3274
3275                    _ = timeout => {
3276                        log::info!("test binary time-ed out, this counts as a success");
3277                        _ = process.kill();
3278                    }
3279                }
3280            } else {
3281                log::warn!("test binary failed to launch");
3282                errored = true;
3283            }
3284
3285            if errored {
3286                log::warn!("test binary check failed");
3287                let task = this.update(&mut cx, move |this, mut cx| {
3288                    this.reinstall_language_server(language, adapter, server_id, &mut cx)
3289                });
3290
3291                if let Some(task) = task {
3292                    task.await;
3293                }
3294            }
3295        })
3296        .detach();
3297    }
3298
3299    fn on_lsp_progress(
3300        &mut self,
3301        progress: lsp::ProgressParams,
3302        language_server_id: LanguageServerId,
3303        disk_based_diagnostics_progress_token: Option<String>,
3304        cx: &mut ModelContext<Self>,
3305    ) {
3306        let token = match progress.token {
3307            lsp::NumberOrString::String(token) => token,
3308            lsp::NumberOrString::Number(token) => {
3309                log::info!("skipping numeric progress token {}", token);
3310                return;
3311            }
3312        };
3313        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3314        let language_server_status =
3315            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3316                status
3317            } else {
3318                return;
3319            };
3320
3321        if !language_server_status.progress_tokens.contains(&token) {
3322            return;
3323        }
3324
3325        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3326            .as_ref()
3327            .map_or(false, |disk_based_token| {
3328                token.starts_with(disk_based_token)
3329            });
3330
3331        match progress {
3332            lsp::WorkDoneProgress::Begin(report) => {
3333                if is_disk_based_diagnostics_progress {
3334                    language_server_status.has_pending_diagnostic_updates = true;
3335                    self.disk_based_diagnostics_started(language_server_id, cx);
3336                    self.buffer_ordered_messages_tx
3337                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3338                            language_server_id,
3339                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3340                        })
3341                        .ok();
3342                } else {
3343                    self.on_lsp_work_start(
3344                        language_server_id,
3345                        token.clone(),
3346                        LanguageServerProgress {
3347                            message: report.message.clone(),
3348                            percentage: report.percentage.map(|p| p as usize),
3349                            last_update_at: Instant::now(),
3350                        },
3351                        cx,
3352                    );
3353                    self.buffer_ordered_messages_tx
3354                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3355                            language_server_id,
3356                            message: proto::update_language_server::Variant::WorkStart(
3357                                proto::LspWorkStart {
3358                                    token,
3359                                    message: report.message,
3360                                    percentage: report.percentage.map(|p| p as u32),
3361                                },
3362                            ),
3363                        })
3364                        .ok();
3365                }
3366            }
3367            lsp::WorkDoneProgress::Report(report) => {
3368                if !is_disk_based_diagnostics_progress {
3369                    self.on_lsp_work_progress(
3370                        language_server_id,
3371                        token.clone(),
3372                        LanguageServerProgress {
3373                            message: report.message.clone(),
3374                            percentage: report.percentage.map(|p| p as usize),
3375                            last_update_at: Instant::now(),
3376                        },
3377                        cx,
3378                    );
3379                    self.buffer_ordered_messages_tx
3380                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3381                            language_server_id,
3382                            message: proto::update_language_server::Variant::WorkProgress(
3383                                proto::LspWorkProgress {
3384                                    token,
3385                                    message: report.message,
3386                                    percentage: report.percentage.map(|p| p as u32),
3387                                },
3388                            ),
3389                        })
3390                        .ok();
3391                }
3392            }
3393            lsp::WorkDoneProgress::End(_) => {
3394                language_server_status.progress_tokens.remove(&token);
3395
3396                if is_disk_based_diagnostics_progress {
3397                    language_server_status.has_pending_diagnostic_updates = false;
3398                    self.disk_based_diagnostics_finished(language_server_id, cx);
3399                    self.buffer_ordered_messages_tx
3400                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3401                            language_server_id,
3402                            message:
3403                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3404                                    Default::default(),
3405                                ),
3406                        })
3407                        .ok();
3408                } else {
3409                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3410                    self.buffer_ordered_messages_tx
3411                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3412                            language_server_id,
3413                            message: proto::update_language_server::Variant::WorkEnd(
3414                                proto::LspWorkEnd { token },
3415                            ),
3416                        })
3417                        .ok();
3418                }
3419            }
3420        }
3421    }
3422
3423    fn on_lsp_work_start(
3424        &mut self,
3425        language_server_id: LanguageServerId,
3426        token: String,
3427        progress: LanguageServerProgress,
3428        cx: &mut ModelContext<Self>,
3429    ) {
3430        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3431            status.pending_work.insert(token, progress);
3432            cx.notify();
3433        }
3434    }
3435
3436    fn on_lsp_work_progress(
3437        &mut self,
3438        language_server_id: LanguageServerId,
3439        token: String,
3440        progress: LanguageServerProgress,
3441        cx: &mut ModelContext<Self>,
3442    ) {
3443        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3444            let entry = status
3445                .pending_work
3446                .entry(token)
3447                .or_insert(LanguageServerProgress {
3448                    message: Default::default(),
3449                    percentage: Default::default(),
3450                    last_update_at: progress.last_update_at,
3451                });
3452            if progress.message.is_some() {
3453                entry.message = progress.message;
3454            }
3455            if progress.percentage.is_some() {
3456                entry.percentage = progress.percentage;
3457            }
3458            entry.last_update_at = progress.last_update_at;
3459            cx.notify();
3460        }
3461    }
3462
3463    fn on_lsp_work_end(
3464        &mut self,
3465        language_server_id: LanguageServerId,
3466        token: String,
3467        cx: &mut ModelContext<Self>,
3468    ) {
3469        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3470            cx.emit(Event::RefreshInlayHints);
3471            status.pending_work.remove(&token);
3472            cx.notify();
3473        }
3474    }
3475
3476    fn on_lsp_did_change_watched_files(
3477        &mut self,
3478        language_server_id: LanguageServerId,
3479        params: DidChangeWatchedFilesRegistrationOptions,
3480        cx: &mut ModelContext<Self>,
3481    ) {
3482        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3483            self.language_servers.get_mut(&language_server_id)
3484        {
3485            let mut builders = HashMap::default();
3486            for watcher in params.watchers {
3487                for worktree in &self.worktrees {
3488                    if let Some(worktree) = worktree.upgrade(cx) {
3489                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3490                            if let Some(abs_path) = tree.abs_path().to_str() {
3491                                let relative_glob_pattern = match &watcher.glob_pattern {
3492                                    lsp::GlobPattern::String(s) => s
3493                                        .strip_prefix(abs_path)
3494                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3495                                    lsp::GlobPattern::Relative(rp) => {
3496                                        let base_uri = match &rp.base_uri {
3497                                            lsp::OneOf::Left(workspace_folder) => {
3498                                                &workspace_folder.uri
3499                                            }
3500                                            lsp::OneOf::Right(base_uri) => base_uri,
3501                                        };
3502                                        base_uri.to_file_path().ok().and_then(|file_path| {
3503                                            (file_path.to_str() == Some(abs_path))
3504                                                .then_some(rp.pattern.as_str())
3505                                        })
3506                                    }
3507                                };
3508                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3509                                    let literal_prefix =
3510                                        glob_literal_prefix(&relative_glob_pattern);
3511                                    tree.as_local_mut()
3512                                        .unwrap()
3513                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3514                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3515                                        builders
3516                                            .entry(tree.id())
3517                                            .or_insert_with(|| GlobSetBuilder::new())
3518                                            .add(glob);
3519                                    }
3520                                    return true;
3521                                }
3522                            }
3523                            false
3524                        });
3525                        if glob_is_inside_worktree {
3526                            break;
3527                        }
3528                    }
3529                }
3530            }
3531
3532            watched_paths.clear();
3533            for (worktree_id, builder) in builders {
3534                if let Ok(globset) = builder.build() {
3535                    watched_paths.insert(worktree_id, globset);
3536                }
3537            }
3538
3539            cx.notify();
3540        }
3541    }
3542
3543    async fn on_lsp_workspace_edit(
3544        this: WeakModelHandle<Self>,
3545        params: lsp::ApplyWorkspaceEditParams,
3546        server_id: LanguageServerId,
3547        adapter: Arc<CachedLspAdapter>,
3548        mut cx: AsyncAppContext,
3549    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3550        let this = this
3551            .upgrade(&cx)
3552            .ok_or_else(|| anyhow!("project project closed"))?;
3553        let language_server = this
3554            .read_with(&cx, |this, _| this.language_server_for_id(server_id))
3555            .ok_or_else(|| anyhow!("language server not found"))?;
3556        let transaction = Self::deserialize_workspace_edit(
3557            this.clone(),
3558            params.edit,
3559            true,
3560            adapter.clone(),
3561            language_server.clone(),
3562            &mut cx,
3563        )
3564        .await
3565        .log_err();
3566        this.update(&mut cx, |this, _| {
3567            if let Some(transaction) = transaction {
3568                this.last_workspace_edits_by_language_server
3569                    .insert(server_id, transaction);
3570            }
3571        });
3572        Ok(lsp::ApplyWorkspaceEditResponse {
3573            applied: true,
3574            failed_change: None,
3575            failure_reason: None,
3576        })
3577    }
3578
3579    pub fn language_server_statuses(
3580        &self,
3581    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3582        self.language_server_statuses.values()
3583    }
3584
3585    pub fn update_diagnostics(
3586        &mut self,
3587        language_server_id: LanguageServerId,
3588        mut params: lsp::PublishDiagnosticsParams,
3589        disk_based_sources: &[String],
3590        cx: &mut ModelContext<Self>,
3591    ) -> Result<()> {
3592        let abs_path = params
3593            .uri
3594            .to_file_path()
3595            .map_err(|_| anyhow!("URI is not a file"))?;
3596        let mut diagnostics = Vec::default();
3597        let mut primary_diagnostic_group_ids = HashMap::default();
3598        let mut sources_by_group_id = HashMap::default();
3599        let mut supporting_diagnostics = HashMap::default();
3600
3601        // Ensure that primary diagnostics are always the most severe
3602        params.diagnostics.sort_by_key(|item| item.severity);
3603
3604        for diagnostic in &params.diagnostics {
3605            let source = diagnostic.source.as_ref();
3606            let code = diagnostic.code.as_ref().map(|code| match code {
3607                lsp::NumberOrString::Number(code) => code.to_string(),
3608                lsp::NumberOrString::String(code) => code.clone(),
3609            });
3610            let range = range_from_lsp(diagnostic.range);
3611            let is_supporting = diagnostic
3612                .related_information
3613                .as_ref()
3614                .map_or(false, |infos| {
3615                    infos.iter().any(|info| {
3616                        primary_diagnostic_group_ids.contains_key(&(
3617                            source,
3618                            code.clone(),
3619                            range_from_lsp(info.location.range),
3620                        ))
3621                    })
3622                });
3623
3624            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3625                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3626            });
3627
3628            if is_supporting {
3629                supporting_diagnostics.insert(
3630                    (source, code.clone(), range),
3631                    (diagnostic.severity, is_unnecessary),
3632                );
3633            } else {
3634                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3635                let is_disk_based =
3636                    source.map_or(false, |source| disk_based_sources.contains(source));
3637
3638                sources_by_group_id.insert(group_id, source);
3639                primary_diagnostic_group_ids
3640                    .insert((source, code.clone(), range.clone()), group_id);
3641
3642                diagnostics.push(DiagnosticEntry {
3643                    range,
3644                    diagnostic: Diagnostic {
3645                        source: diagnostic.source.clone(),
3646                        code: code.clone(),
3647                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3648                        message: diagnostic.message.clone(),
3649                        group_id,
3650                        is_primary: true,
3651                        is_valid: true,
3652                        is_disk_based,
3653                        is_unnecessary,
3654                    },
3655                });
3656                if let Some(infos) = &diagnostic.related_information {
3657                    for info in infos {
3658                        if info.location.uri == params.uri && !info.message.is_empty() {
3659                            let range = range_from_lsp(info.location.range);
3660                            diagnostics.push(DiagnosticEntry {
3661                                range,
3662                                diagnostic: Diagnostic {
3663                                    source: diagnostic.source.clone(),
3664                                    code: code.clone(),
3665                                    severity: DiagnosticSeverity::INFORMATION,
3666                                    message: info.message.clone(),
3667                                    group_id,
3668                                    is_primary: false,
3669                                    is_valid: true,
3670                                    is_disk_based,
3671                                    is_unnecessary: false,
3672                                },
3673                            });
3674                        }
3675                    }
3676                }
3677            }
3678        }
3679
3680        for entry in &mut diagnostics {
3681            let diagnostic = &mut entry.diagnostic;
3682            if !diagnostic.is_primary {
3683                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3684                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3685                    source,
3686                    diagnostic.code.clone(),
3687                    entry.range.clone(),
3688                )) {
3689                    if let Some(severity) = severity {
3690                        diagnostic.severity = severity;
3691                    }
3692                    diagnostic.is_unnecessary = is_unnecessary;
3693                }
3694            }
3695        }
3696
3697        self.update_diagnostic_entries(
3698            language_server_id,
3699            abs_path,
3700            params.version,
3701            diagnostics,
3702            cx,
3703        )?;
3704        Ok(())
3705    }
3706
3707    pub fn update_diagnostic_entries(
3708        &mut self,
3709        server_id: LanguageServerId,
3710        abs_path: PathBuf,
3711        version: Option<i32>,
3712        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3713        cx: &mut ModelContext<Project>,
3714    ) -> Result<(), anyhow::Error> {
3715        let (worktree, relative_path) = self
3716            .find_local_worktree(&abs_path, cx)
3717            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3718
3719        let project_path = ProjectPath {
3720            worktree_id: worktree.read(cx).id(),
3721            path: relative_path.into(),
3722        };
3723
3724        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3725            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3726        }
3727
3728        let updated = worktree.update(cx, |worktree, cx| {
3729            worktree
3730                .as_local_mut()
3731                .ok_or_else(|| anyhow!("not a local worktree"))?
3732                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3733        })?;
3734        if updated {
3735            cx.emit(Event::DiagnosticsUpdated {
3736                language_server_id: server_id,
3737                path: project_path,
3738            });
3739        }
3740        Ok(())
3741    }
3742
3743    fn update_buffer_diagnostics(
3744        &mut self,
3745        buffer: &ModelHandle<Buffer>,
3746        server_id: LanguageServerId,
3747        version: Option<i32>,
3748        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3749        cx: &mut ModelContext<Self>,
3750    ) -> Result<()> {
3751        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3752            Ordering::Equal
3753                .then_with(|| b.is_primary.cmp(&a.is_primary))
3754                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3755                .then_with(|| a.severity.cmp(&b.severity))
3756                .then_with(|| a.message.cmp(&b.message))
3757        }
3758
3759        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3760
3761        diagnostics.sort_unstable_by(|a, b| {
3762            Ordering::Equal
3763                .then_with(|| a.range.start.cmp(&b.range.start))
3764                .then_with(|| b.range.end.cmp(&a.range.end))
3765                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3766        });
3767
3768        let mut sanitized_diagnostics = Vec::new();
3769        let edits_since_save = Patch::new(
3770            snapshot
3771                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3772                .collect(),
3773        );
3774        for entry in diagnostics {
3775            let start;
3776            let end;
3777            if entry.diagnostic.is_disk_based {
3778                // Some diagnostics are based on files on disk instead of buffers'
3779                // current contents. Adjust these diagnostics' ranges to reflect
3780                // any unsaved edits.
3781                start = edits_since_save.old_to_new(entry.range.start);
3782                end = edits_since_save.old_to_new(entry.range.end);
3783            } else {
3784                start = entry.range.start;
3785                end = entry.range.end;
3786            }
3787
3788            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3789                ..snapshot.clip_point_utf16(end, Bias::Right);
3790
3791            // Expand empty ranges by one codepoint
3792            if range.start == range.end {
3793                // This will be go to the next boundary when being clipped
3794                range.end.column += 1;
3795                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3796                if range.start == range.end && range.end.column > 0 {
3797                    range.start.column -= 1;
3798                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3799                }
3800            }
3801
3802            sanitized_diagnostics.push(DiagnosticEntry {
3803                range,
3804                diagnostic: entry.diagnostic,
3805            });
3806        }
3807        drop(edits_since_save);
3808
3809        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3810        buffer.update(cx, |buffer, cx| {
3811            buffer.update_diagnostics(server_id, set, cx)
3812        });
3813        Ok(())
3814    }
3815
3816    pub fn reload_buffers(
3817        &self,
3818        buffers: HashSet<ModelHandle<Buffer>>,
3819        push_to_history: bool,
3820        cx: &mut ModelContext<Self>,
3821    ) -> Task<Result<ProjectTransaction>> {
3822        let mut local_buffers = Vec::new();
3823        let mut remote_buffers = None;
3824        for buffer_handle in buffers {
3825            let buffer = buffer_handle.read(cx);
3826            if buffer.is_dirty() {
3827                if let Some(file) = File::from_dyn(buffer.file()) {
3828                    if file.is_local() {
3829                        local_buffers.push(buffer_handle);
3830                    } else {
3831                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3832                    }
3833                }
3834            }
3835        }
3836
3837        let remote_buffers = self.remote_id().zip(remote_buffers);
3838        let client = self.client.clone();
3839
3840        cx.spawn(|this, mut cx| async move {
3841            let mut project_transaction = ProjectTransaction::default();
3842
3843            if let Some((project_id, remote_buffers)) = remote_buffers {
3844                let response = client
3845                    .request(proto::ReloadBuffers {
3846                        project_id,
3847                        buffer_ids: remote_buffers
3848                            .iter()
3849                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3850                            .collect(),
3851                    })
3852                    .await?
3853                    .transaction
3854                    .ok_or_else(|| anyhow!("missing transaction"))?;
3855                project_transaction = this
3856                    .update(&mut cx, |this, cx| {
3857                        this.deserialize_project_transaction(response, push_to_history, cx)
3858                    })
3859                    .await?;
3860            }
3861
3862            for buffer in local_buffers {
3863                let transaction = buffer
3864                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
3865                    .await?;
3866                buffer.update(&mut cx, |buffer, cx| {
3867                    if let Some(transaction) = transaction {
3868                        if !push_to_history {
3869                            buffer.forget_transaction(transaction.id);
3870                        }
3871                        project_transaction.0.insert(cx.handle(), transaction);
3872                    }
3873                });
3874            }
3875
3876            Ok(project_transaction)
3877        })
3878    }
3879
3880    pub fn format(
3881        &self,
3882        buffers: HashSet<ModelHandle<Buffer>>,
3883        push_to_history: bool,
3884        trigger: FormatTrigger,
3885        cx: &mut ModelContext<Project>,
3886    ) -> Task<Result<ProjectTransaction>> {
3887        if self.is_local() {
3888            let mut buffers_with_paths_and_servers = buffers
3889                .into_iter()
3890                .filter_map(|buffer_handle| {
3891                    let buffer = buffer_handle.read(cx);
3892                    let file = File::from_dyn(buffer.file())?;
3893                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3894                    let server = self
3895                        .primary_language_servers_for_buffer(buffer, cx)
3896                        .map(|s| s.1.clone());
3897                    Some((buffer_handle, buffer_abs_path, server))
3898                })
3899                .collect::<Vec<_>>();
3900
3901            cx.spawn(|this, mut cx| async move {
3902                // Do not allow multiple concurrent formatting requests for the
3903                // same buffer.
3904                this.update(&mut cx, |this, cx| {
3905                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
3906                        this.buffers_being_formatted
3907                            .insert(buffer.read(cx).remote_id())
3908                    });
3909                });
3910
3911                let _cleanup = defer({
3912                    let this = this.clone();
3913                    let mut cx = cx.clone();
3914                    let buffers = &buffers_with_paths_and_servers;
3915                    move || {
3916                        this.update(&mut cx, |this, cx| {
3917                            for (buffer, _, _) in buffers {
3918                                this.buffers_being_formatted
3919                                    .remove(&buffer.read(cx).remote_id());
3920                            }
3921                        });
3922                    }
3923                });
3924
3925                let mut project_transaction = ProjectTransaction::default();
3926                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
3927                    let settings = buffer.read_with(&cx, |buffer, cx| {
3928                        language_settings(buffer.language(), buffer.file(), cx).clone()
3929                    });
3930
3931                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
3932                    let ensure_final_newline = settings.ensure_final_newline_on_save;
3933                    let format_on_save = settings.format_on_save.clone();
3934                    let formatter = settings.formatter.clone();
3935                    let tab_size = settings.tab_size;
3936
3937                    // First, format buffer's whitespace according to the settings.
3938                    let trailing_whitespace_diff = if remove_trailing_whitespace {
3939                        Some(
3940                            buffer
3941                                .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
3942                                .await,
3943                        )
3944                    } else {
3945                        None
3946                    };
3947                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
3948                        buffer.finalize_last_transaction();
3949                        buffer.start_transaction();
3950                        if let Some(diff) = trailing_whitespace_diff {
3951                            buffer.apply_diff(diff, cx);
3952                        }
3953                        if ensure_final_newline {
3954                            buffer.ensure_final_newline(cx);
3955                        }
3956                        buffer.end_transaction(cx)
3957                    });
3958
3959                    // Currently, formatting operations are represented differently depending on
3960                    // whether they come from a language server or an external command.
3961                    enum FormatOperation {
3962                        Lsp(Vec<(Range<Anchor>, String)>),
3963                        External(Diff),
3964                    }
3965
3966                    // Apply language-specific formatting using either a language server
3967                    // or external command.
3968                    let mut format_operation = None;
3969                    match (formatter, format_on_save) {
3970                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
3971
3972                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
3973                        | (_, FormatOnSave::LanguageServer) => {
3974                            if let Some((language_server, buffer_abs_path)) =
3975                                language_server.as_ref().zip(buffer_abs_path.as_ref())
3976                            {
3977                                format_operation = Some(FormatOperation::Lsp(
3978                                    Self::format_via_lsp(
3979                                        &this,
3980                                        &buffer,
3981                                        buffer_abs_path,
3982                                        &language_server,
3983                                        tab_size,
3984                                        &mut cx,
3985                                    )
3986                                    .await
3987                                    .context("failed to format via language server")?,
3988                                ));
3989                            }
3990                        }
3991
3992                        (
3993                            Formatter::External { command, arguments },
3994                            FormatOnSave::On | FormatOnSave::Off,
3995                        )
3996                        | (_, FormatOnSave::External { command, arguments }) => {
3997                            if let Some(buffer_abs_path) = buffer_abs_path {
3998                                format_operation = Self::format_via_external_command(
3999                                    &buffer,
4000                                    &buffer_abs_path,
4001                                    &command,
4002                                    &arguments,
4003                                    &mut cx,
4004                                )
4005                                .await
4006                                .context(format!(
4007                                    "failed to format via external command {:?}",
4008                                    command
4009                                ))?
4010                                .map(FormatOperation::External);
4011                            }
4012                        }
4013                    };
4014
4015                    buffer.update(&mut cx, |b, cx| {
4016                        // If the buffer had its whitespace formatted and was edited while the language-specific
4017                        // formatting was being computed, avoid applying the language-specific formatting, because
4018                        // it can't be grouped with the whitespace formatting in the undo history.
4019                        if let Some(transaction_id) = whitespace_transaction_id {
4020                            if b.peek_undo_stack()
4021                                .map_or(true, |e| e.transaction_id() != transaction_id)
4022                            {
4023                                format_operation.take();
4024                            }
4025                        }
4026
4027                        // Apply any language-specific formatting, and group the two formatting operations
4028                        // in the buffer's undo history.
4029                        if let Some(operation) = format_operation {
4030                            match operation {
4031                                FormatOperation::Lsp(edits) => {
4032                                    b.edit(edits, None, cx);
4033                                }
4034                                FormatOperation::External(diff) => {
4035                                    b.apply_diff(diff, cx);
4036                                }
4037                            }
4038
4039                            if let Some(transaction_id) = whitespace_transaction_id {
4040                                b.group_until_transaction(transaction_id);
4041                            }
4042                        }
4043
4044                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4045                            if !push_to_history {
4046                                b.forget_transaction(transaction.id);
4047                            }
4048                            project_transaction.0.insert(buffer.clone(), transaction);
4049                        }
4050                    });
4051                }
4052
4053                Ok(project_transaction)
4054            })
4055        } else {
4056            let remote_id = self.remote_id();
4057            let client = self.client.clone();
4058            cx.spawn(|this, mut cx| async move {
4059                let mut project_transaction = ProjectTransaction::default();
4060                if let Some(project_id) = remote_id {
4061                    let response = client
4062                        .request(proto::FormatBuffers {
4063                            project_id,
4064                            trigger: trigger as i32,
4065                            buffer_ids: buffers
4066                                .iter()
4067                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
4068                                .collect(),
4069                        })
4070                        .await?
4071                        .transaction
4072                        .ok_or_else(|| anyhow!("missing transaction"))?;
4073                    project_transaction = this
4074                        .update(&mut cx, |this, cx| {
4075                            this.deserialize_project_transaction(response, push_to_history, cx)
4076                        })
4077                        .await?;
4078                }
4079                Ok(project_transaction)
4080            })
4081        }
4082    }
4083
4084    async fn format_via_lsp(
4085        this: &ModelHandle<Self>,
4086        buffer: &ModelHandle<Buffer>,
4087        abs_path: &Path,
4088        language_server: &Arc<LanguageServer>,
4089        tab_size: NonZeroU32,
4090        cx: &mut AsyncAppContext,
4091    ) -> Result<Vec<(Range<Anchor>, String)>> {
4092        let uri = lsp::Url::from_file_path(abs_path)
4093            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4094        let text_document = lsp::TextDocumentIdentifier::new(uri);
4095        let capabilities = &language_server.capabilities();
4096
4097        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4098        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4099
4100        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4101            language_server
4102                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4103                    text_document,
4104                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4105                    work_done_progress_params: Default::default(),
4106                })
4107                .await?
4108        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4109            let buffer_start = lsp::Position::new(0, 0);
4110            let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
4111
4112            language_server
4113                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4114                    text_document,
4115                    range: lsp::Range::new(buffer_start, buffer_end),
4116                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4117                    work_done_progress_params: Default::default(),
4118                })
4119                .await?
4120        } else {
4121            None
4122        };
4123
4124        if let Some(lsp_edits) = lsp_edits {
4125            this.update(cx, |this, cx| {
4126                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4127            })
4128            .await
4129        } else {
4130            Ok(Vec::new())
4131        }
4132    }
4133
4134    async fn format_via_external_command(
4135        buffer: &ModelHandle<Buffer>,
4136        buffer_abs_path: &Path,
4137        command: &str,
4138        arguments: &[String],
4139        cx: &mut AsyncAppContext,
4140    ) -> Result<Option<Diff>> {
4141        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
4142            let file = File::from_dyn(buffer.file())?;
4143            let worktree = file.worktree.read(cx).as_local()?;
4144            let mut worktree_path = worktree.abs_path().to_path_buf();
4145            if worktree.root_entry()?.is_file() {
4146                worktree_path.pop();
4147            }
4148            Some(worktree_path)
4149        });
4150
4151        if let Some(working_dir_path) = working_dir_path {
4152            let mut child =
4153                smol::process::Command::new(command)
4154                    .args(arguments.iter().map(|arg| {
4155                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4156                    }))
4157                    .current_dir(&working_dir_path)
4158                    .stdin(smol::process::Stdio::piped())
4159                    .stdout(smol::process::Stdio::piped())
4160                    .stderr(smol::process::Stdio::piped())
4161                    .spawn()?;
4162            let stdin = child
4163                .stdin
4164                .as_mut()
4165                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4166            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
4167            for chunk in text.chunks() {
4168                stdin.write_all(chunk.as_bytes()).await?;
4169            }
4170            stdin.flush().await?;
4171
4172            let output = child.output().await?;
4173            if !output.status.success() {
4174                return Err(anyhow!(
4175                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4176                    output.status.code(),
4177                    String::from_utf8_lossy(&output.stdout),
4178                    String::from_utf8_lossy(&output.stderr),
4179                ));
4180            }
4181
4182            let stdout = String::from_utf8(output.stdout)?;
4183            Ok(Some(
4184                buffer
4185                    .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4186                    .await,
4187            ))
4188        } else {
4189            Ok(None)
4190        }
4191    }
4192
4193    pub fn definition<T: ToPointUtf16>(
4194        &self,
4195        buffer: &ModelHandle<Buffer>,
4196        position: T,
4197        cx: &mut ModelContext<Self>,
4198    ) -> Task<Result<Vec<LocationLink>>> {
4199        let position = position.to_point_utf16(buffer.read(cx));
4200        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
4201    }
4202
4203    pub fn type_definition<T: ToPointUtf16>(
4204        &self,
4205        buffer: &ModelHandle<Buffer>,
4206        position: T,
4207        cx: &mut ModelContext<Self>,
4208    ) -> Task<Result<Vec<LocationLink>>> {
4209        let position = position.to_point_utf16(buffer.read(cx));
4210        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
4211    }
4212
4213    pub fn references<T: ToPointUtf16>(
4214        &self,
4215        buffer: &ModelHandle<Buffer>,
4216        position: T,
4217        cx: &mut ModelContext<Self>,
4218    ) -> Task<Result<Vec<Location>>> {
4219        let position = position.to_point_utf16(buffer.read(cx));
4220        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
4221    }
4222
4223    pub fn document_highlights<T: ToPointUtf16>(
4224        &self,
4225        buffer: &ModelHandle<Buffer>,
4226        position: T,
4227        cx: &mut ModelContext<Self>,
4228    ) -> Task<Result<Vec<DocumentHighlight>>> {
4229        let position = position.to_point_utf16(buffer.read(cx));
4230        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
4231    }
4232
4233    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4234        if self.is_local() {
4235            let mut requests = Vec::new();
4236            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4237                let worktree_id = *worktree_id;
4238                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4239                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4240                    Some(worktree) => worktree,
4241                    None => continue,
4242                };
4243                let worktree_abs_path = worktree.abs_path().clone();
4244
4245                let (adapter, language, server) = match self.language_servers.get(server_id) {
4246                    Some(LanguageServerState::Running {
4247                        adapter,
4248                        language,
4249                        server,
4250                        ..
4251                    }) => (adapter.clone(), language.clone(), server),
4252
4253                    _ => continue,
4254                };
4255
4256                requests.push(
4257                    server
4258                        .request::<lsp::request::WorkspaceSymbolRequest>(
4259                            lsp::WorkspaceSymbolParams {
4260                                query: query.to_string(),
4261                                ..Default::default()
4262                            },
4263                        )
4264                        .log_err()
4265                        .map(move |response| {
4266                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4267                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4268                                    flat_responses.into_iter().map(|lsp_symbol| {
4269                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4270                                    }).collect::<Vec<_>>()
4271                                }
4272                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4273                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4274                                        let location = match lsp_symbol.location {
4275                                            OneOf::Left(location) => location,
4276                                            OneOf::Right(_) => {
4277                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4278                                                return None
4279                                            }
4280                                        };
4281                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4282                                    }).collect::<Vec<_>>()
4283                                }
4284                            }).unwrap_or_default();
4285
4286                            (
4287                                adapter,
4288                                language,
4289                                worktree_id,
4290                                worktree_abs_path,
4291                                lsp_symbols,
4292                            )
4293                        }),
4294                );
4295            }
4296
4297            cx.spawn_weak(|this, cx| async move {
4298                let responses = futures::future::join_all(requests).await;
4299                let this = match this.upgrade(&cx) {
4300                    Some(this) => this,
4301                    None => return Ok(Vec::new()),
4302                };
4303
4304                let symbols = this.read_with(&cx, |this, cx| {
4305                    let mut symbols = Vec::new();
4306                    for (
4307                        adapter,
4308                        adapter_language,
4309                        source_worktree_id,
4310                        worktree_abs_path,
4311                        lsp_symbols,
4312                    ) in responses
4313                    {
4314                        symbols.extend(lsp_symbols.into_iter().filter_map(
4315                            |(symbol_name, symbol_kind, symbol_location)| {
4316                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4317                                let mut worktree_id = source_worktree_id;
4318                                let path;
4319                                if let Some((worktree, rel_path)) =
4320                                    this.find_local_worktree(&abs_path, cx)
4321                                {
4322                                    worktree_id = worktree.read(cx).id();
4323                                    path = rel_path;
4324                                } else {
4325                                    path = relativize_path(&worktree_abs_path, &abs_path);
4326                                }
4327
4328                                let project_path = ProjectPath {
4329                                    worktree_id,
4330                                    path: path.into(),
4331                                };
4332                                let signature = this.symbol_signature(&project_path);
4333                                let adapter_language = adapter_language.clone();
4334                                let language = this
4335                                    .languages
4336                                    .language_for_file(&project_path.path, None)
4337                                    .unwrap_or_else(move |_| adapter_language);
4338                                let language_server_name = adapter.name.clone();
4339                                Some(async move {
4340                                    let language = language.await;
4341                                    let label =
4342                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4343
4344                                    Symbol {
4345                                        language_server_name,
4346                                        source_worktree_id,
4347                                        path: project_path,
4348                                        label: label.unwrap_or_else(|| {
4349                                            CodeLabel::plain(symbol_name.clone(), None)
4350                                        }),
4351                                        kind: symbol_kind,
4352                                        name: symbol_name,
4353                                        range: range_from_lsp(symbol_location.range),
4354                                        signature,
4355                                    }
4356                                })
4357                            },
4358                        ));
4359                    }
4360
4361                    symbols
4362                });
4363
4364                Ok(futures::future::join_all(symbols).await)
4365            })
4366        } else if let Some(project_id) = self.remote_id() {
4367            let request = self.client.request(proto::GetProjectSymbols {
4368                project_id,
4369                query: query.to_string(),
4370            });
4371            cx.spawn_weak(|this, cx| async move {
4372                let response = request.await?;
4373                let mut symbols = Vec::new();
4374                if let Some(this) = this.upgrade(&cx) {
4375                    let new_symbols = this.read_with(&cx, |this, _| {
4376                        response
4377                            .symbols
4378                            .into_iter()
4379                            .map(|symbol| this.deserialize_symbol(symbol))
4380                            .collect::<Vec<_>>()
4381                    });
4382                    symbols = futures::future::join_all(new_symbols)
4383                        .await
4384                        .into_iter()
4385                        .filter_map(|symbol| symbol.log_err())
4386                        .collect::<Vec<_>>();
4387                }
4388                Ok(symbols)
4389            })
4390        } else {
4391            Task::ready(Ok(Default::default()))
4392        }
4393    }
4394
4395    pub fn open_buffer_for_symbol(
4396        &mut self,
4397        symbol: &Symbol,
4398        cx: &mut ModelContext<Self>,
4399    ) -> Task<Result<ModelHandle<Buffer>>> {
4400        if self.is_local() {
4401            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4402                symbol.source_worktree_id,
4403                symbol.language_server_name.clone(),
4404            )) {
4405                *id
4406            } else {
4407                return Task::ready(Err(anyhow!(
4408                    "language server for worktree and language not found"
4409                )));
4410            };
4411
4412            let worktree_abs_path = if let Some(worktree_abs_path) = self
4413                .worktree_for_id(symbol.path.worktree_id, cx)
4414                .and_then(|worktree| worktree.read(cx).as_local())
4415                .map(|local_worktree| local_worktree.abs_path())
4416            {
4417                worktree_abs_path
4418            } else {
4419                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4420            };
4421            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4422            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4423                uri
4424            } else {
4425                return Task::ready(Err(anyhow!("invalid symbol path")));
4426            };
4427
4428            self.open_local_buffer_via_lsp(
4429                symbol_uri,
4430                language_server_id,
4431                symbol.language_server_name.clone(),
4432                cx,
4433            )
4434        } else if let Some(project_id) = self.remote_id() {
4435            let request = self.client.request(proto::OpenBufferForSymbol {
4436                project_id,
4437                symbol: Some(serialize_symbol(symbol)),
4438            });
4439            cx.spawn(|this, mut cx| async move {
4440                let response = request.await?;
4441                this.update(&mut cx, |this, cx| {
4442                    this.wait_for_remote_buffer(response.buffer_id, cx)
4443                })
4444                .await
4445            })
4446        } else {
4447            Task::ready(Err(anyhow!("project does not have a remote id")))
4448        }
4449    }
4450
4451    pub fn hover<T: ToPointUtf16>(
4452        &self,
4453        buffer: &ModelHandle<Buffer>,
4454        position: T,
4455        cx: &mut ModelContext<Self>,
4456    ) -> Task<Result<Option<Hover>>> {
4457        let position = position.to_point_utf16(buffer.read(cx));
4458        self.request_lsp(buffer.clone(), GetHover { position }, cx)
4459    }
4460
4461    pub fn completions<T: ToPointUtf16>(
4462        &self,
4463        buffer: &ModelHandle<Buffer>,
4464        position: T,
4465        cx: &mut ModelContext<Self>,
4466    ) -> Task<Result<Vec<Completion>>> {
4467        let position = position.to_point_utf16(buffer.read(cx));
4468        self.request_lsp(buffer.clone(), GetCompletions { position }, cx)
4469    }
4470
4471    pub fn apply_additional_edits_for_completion(
4472        &self,
4473        buffer_handle: ModelHandle<Buffer>,
4474        completion: Completion,
4475        push_to_history: bool,
4476        cx: &mut ModelContext<Self>,
4477    ) -> Task<Result<Option<Transaction>>> {
4478        let buffer = buffer_handle.read(cx);
4479        let buffer_id = buffer.remote_id();
4480
4481        if self.is_local() {
4482            let lang_server = match self.primary_language_servers_for_buffer(buffer, cx) {
4483                Some((_, server)) => server.clone(),
4484                _ => return Task::ready(Ok(Default::default())),
4485            };
4486
4487            cx.spawn(|this, mut cx| async move {
4488                let can_resolve = lang_server
4489                    .capabilities()
4490                    .completion_provider
4491                    .as_ref()
4492                    .and_then(|options| options.resolve_provider)
4493                    .unwrap_or(false);
4494                let additional_text_edits = if can_resolve {
4495                    lang_server
4496                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4497                        .await?
4498                        .additional_text_edits
4499                } else {
4500                    completion.lsp_completion.additional_text_edits
4501                };
4502                if let Some(edits) = additional_text_edits {
4503                    let edits = this
4504                        .update(&mut cx, |this, cx| {
4505                            this.edits_from_lsp(
4506                                &buffer_handle,
4507                                edits,
4508                                lang_server.server_id(),
4509                                None,
4510                                cx,
4511                            )
4512                        })
4513                        .await?;
4514
4515                    buffer_handle.update(&mut cx, |buffer, cx| {
4516                        buffer.finalize_last_transaction();
4517                        buffer.start_transaction();
4518
4519                        for (range, text) in edits {
4520                            let primary = &completion.old_range;
4521                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4522                                && primary.end.cmp(&range.start, buffer).is_ge();
4523                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4524                                && range.end.cmp(&primary.end, buffer).is_ge();
4525
4526                            //Skip additional edits which overlap with the primary completion edit
4527                            //https://github.com/zed-industries/zed/pull/1871
4528                            if !start_within && !end_within {
4529                                buffer.edit([(range, text)], None, cx);
4530                            }
4531                        }
4532
4533                        let transaction = if buffer.end_transaction(cx).is_some() {
4534                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4535                            if !push_to_history {
4536                                buffer.forget_transaction(transaction.id);
4537                            }
4538                            Some(transaction)
4539                        } else {
4540                            None
4541                        };
4542                        Ok(transaction)
4543                    })
4544                } else {
4545                    Ok(None)
4546                }
4547            })
4548        } else if let Some(project_id) = self.remote_id() {
4549            let client = self.client.clone();
4550            cx.spawn(|_, mut cx| async move {
4551                let response = client
4552                    .request(proto::ApplyCompletionAdditionalEdits {
4553                        project_id,
4554                        buffer_id,
4555                        completion: Some(language::proto::serialize_completion(&completion)),
4556                    })
4557                    .await?;
4558
4559                if let Some(transaction) = response.transaction {
4560                    let transaction = language::proto::deserialize_transaction(transaction)?;
4561                    buffer_handle
4562                        .update(&mut cx, |buffer, _| {
4563                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4564                        })
4565                        .await?;
4566                    if push_to_history {
4567                        buffer_handle.update(&mut cx, |buffer, _| {
4568                            buffer.push_transaction(transaction.clone(), Instant::now());
4569                        });
4570                    }
4571                    Ok(Some(transaction))
4572                } else {
4573                    Ok(None)
4574                }
4575            })
4576        } else {
4577            Task::ready(Err(anyhow!("project does not have a remote id")))
4578        }
4579    }
4580
4581    pub fn code_actions<T: Clone + ToOffset>(
4582        &self,
4583        buffer_handle: &ModelHandle<Buffer>,
4584        range: Range<T>,
4585        cx: &mut ModelContext<Self>,
4586    ) -> Task<Result<Vec<CodeAction>>> {
4587        let buffer = buffer_handle.read(cx);
4588        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4589        self.request_lsp(buffer_handle.clone(), GetCodeActions { range }, cx)
4590    }
4591
4592    pub fn apply_code_action(
4593        &self,
4594        buffer_handle: ModelHandle<Buffer>,
4595        mut action: CodeAction,
4596        push_to_history: bool,
4597        cx: &mut ModelContext<Self>,
4598    ) -> Task<Result<ProjectTransaction>> {
4599        if self.is_local() {
4600            let buffer = buffer_handle.read(cx);
4601            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4602                self.language_server_for_buffer(buffer, action.server_id, cx)
4603            {
4604                (adapter.clone(), server.clone())
4605            } else {
4606                return Task::ready(Ok(Default::default()));
4607            };
4608            let range = action.range.to_point_utf16(buffer);
4609
4610            cx.spawn(|this, mut cx| async move {
4611                if let Some(lsp_range) = action
4612                    .lsp_action
4613                    .data
4614                    .as_mut()
4615                    .and_then(|d| d.get_mut("codeActionParams"))
4616                    .and_then(|d| d.get_mut("range"))
4617                {
4618                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4619                    action.lsp_action = lang_server
4620                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4621                        .await?;
4622                } else {
4623                    let actions = this
4624                        .update(&mut cx, |this, cx| {
4625                            this.code_actions(&buffer_handle, action.range, cx)
4626                        })
4627                        .await?;
4628                    action.lsp_action = actions
4629                        .into_iter()
4630                        .find(|a| a.lsp_action.title == action.lsp_action.title)
4631                        .ok_or_else(|| anyhow!("code action is outdated"))?
4632                        .lsp_action;
4633                }
4634
4635                if let Some(edit) = action.lsp_action.edit {
4636                    if edit.changes.is_some() || edit.document_changes.is_some() {
4637                        return Self::deserialize_workspace_edit(
4638                            this,
4639                            edit,
4640                            push_to_history,
4641                            lsp_adapter.clone(),
4642                            lang_server.clone(),
4643                            &mut cx,
4644                        )
4645                        .await;
4646                    }
4647                }
4648
4649                if let Some(command) = action.lsp_action.command {
4650                    this.update(&mut cx, |this, _| {
4651                        this.last_workspace_edits_by_language_server
4652                            .remove(&lang_server.server_id());
4653                    });
4654
4655                    let result = lang_server
4656                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4657                            command: command.command,
4658                            arguments: command.arguments.unwrap_or_default(),
4659                            ..Default::default()
4660                        })
4661                        .await;
4662
4663                    if let Err(err) = result {
4664                        // TODO: LSP ERROR
4665                        return Err(err);
4666                    }
4667
4668                    return Ok(this.update(&mut cx, |this, _| {
4669                        this.last_workspace_edits_by_language_server
4670                            .remove(&lang_server.server_id())
4671                            .unwrap_or_default()
4672                    }));
4673                }
4674
4675                Ok(ProjectTransaction::default())
4676            })
4677        } else if let Some(project_id) = self.remote_id() {
4678            let client = self.client.clone();
4679            let request = proto::ApplyCodeAction {
4680                project_id,
4681                buffer_id: buffer_handle.read(cx).remote_id(),
4682                action: Some(language::proto::serialize_code_action(&action)),
4683            };
4684            cx.spawn(|this, mut cx| async move {
4685                let response = client
4686                    .request(request)
4687                    .await?
4688                    .transaction
4689                    .ok_or_else(|| anyhow!("missing transaction"))?;
4690                this.update(&mut cx, |this, cx| {
4691                    this.deserialize_project_transaction(response, push_to_history, cx)
4692                })
4693                .await
4694            })
4695        } else {
4696            Task::ready(Err(anyhow!("project does not have a remote id")))
4697        }
4698    }
4699
4700    fn apply_on_type_formatting(
4701        &self,
4702        buffer: ModelHandle<Buffer>,
4703        position: Anchor,
4704        trigger: String,
4705        cx: &mut ModelContext<Self>,
4706    ) -> Task<Result<Option<Transaction>>> {
4707        if self.is_local() {
4708            cx.spawn(|this, mut cx| async move {
4709                // Do not allow multiple concurrent formatting requests for the
4710                // same buffer.
4711                this.update(&mut cx, |this, cx| {
4712                    this.buffers_being_formatted
4713                        .insert(buffer.read(cx).remote_id())
4714                });
4715
4716                let _cleanup = defer({
4717                    let this = this.clone();
4718                    let mut cx = cx.clone();
4719                    let closure_buffer = buffer.clone();
4720                    move || {
4721                        this.update(&mut cx, |this, cx| {
4722                            this.buffers_being_formatted
4723                                .remove(&closure_buffer.read(cx).remote_id());
4724                        });
4725                    }
4726                });
4727
4728                buffer
4729                    .update(&mut cx, |buffer, _| {
4730                        buffer.wait_for_edits(Some(position.timestamp))
4731                    })
4732                    .await?;
4733                this.update(&mut cx, |this, cx| {
4734                    let position = position.to_point_utf16(buffer.read(cx));
4735                    this.on_type_format(buffer, position, trigger, false, cx)
4736                })
4737                .await
4738            })
4739        } else if let Some(project_id) = self.remote_id() {
4740            let client = self.client.clone();
4741            let request = proto::OnTypeFormatting {
4742                project_id,
4743                buffer_id: buffer.read(cx).remote_id(),
4744                position: Some(serialize_anchor(&position)),
4745                trigger,
4746                version: serialize_version(&buffer.read(cx).version()),
4747            };
4748            cx.spawn(|_, _| async move {
4749                client
4750                    .request(request)
4751                    .await?
4752                    .transaction
4753                    .map(language::proto::deserialize_transaction)
4754                    .transpose()
4755            })
4756        } else {
4757            Task::ready(Err(anyhow!("project does not have a remote id")))
4758        }
4759    }
4760
4761    async fn deserialize_edits(
4762        this: ModelHandle<Self>,
4763        buffer_to_edit: ModelHandle<Buffer>,
4764        edits: Vec<lsp::TextEdit>,
4765        push_to_history: bool,
4766        _: Arc<CachedLspAdapter>,
4767        language_server: Arc<LanguageServer>,
4768        cx: &mut AsyncAppContext,
4769    ) -> Result<Option<Transaction>> {
4770        let edits = this
4771            .update(cx, |this, cx| {
4772                this.edits_from_lsp(
4773                    &buffer_to_edit,
4774                    edits,
4775                    language_server.server_id(),
4776                    None,
4777                    cx,
4778                )
4779            })
4780            .await?;
4781
4782        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4783            buffer.finalize_last_transaction();
4784            buffer.start_transaction();
4785            for (range, text) in edits {
4786                buffer.edit([(range, text)], None, cx);
4787            }
4788
4789            if buffer.end_transaction(cx).is_some() {
4790                let transaction = buffer.finalize_last_transaction().unwrap().clone();
4791                if !push_to_history {
4792                    buffer.forget_transaction(transaction.id);
4793                }
4794                Some(transaction)
4795            } else {
4796                None
4797            }
4798        });
4799
4800        Ok(transaction)
4801    }
4802
4803    async fn deserialize_workspace_edit(
4804        this: ModelHandle<Self>,
4805        edit: lsp::WorkspaceEdit,
4806        push_to_history: bool,
4807        lsp_adapter: Arc<CachedLspAdapter>,
4808        language_server: Arc<LanguageServer>,
4809        cx: &mut AsyncAppContext,
4810    ) -> Result<ProjectTransaction> {
4811        let fs = this.read_with(cx, |this, _| this.fs.clone());
4812        let mut operations = Vec::new();
4813        if let Some(document_changes) = edit.document_changes {
4814            match document_changes {
4815                lsp::DocumentChanges::Edits(edits) => {
4816                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
4817                }
4818                lsp::DocumentChanges::Operations(ops) => operations = ops,
4819            }
4820        } else if let Some(changes) = edit.changes {
4821            operations.extend(changes.into_iter().map(|(uri, edits)| {
4822                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
4823                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
4824                        uri,
4825                        version: None,
4826                    },
4827                    edits: edits.into_iter().map(OneOf::Left).collect(),
4828                })
4829            }));
4830        }
4831
4832        let mut project_transaction = ProjectTransaction::default();
4833        for operation in operations {
4834            match operation {
4835                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
4836                    let abs_path = op
4837                        .uri
4838                        .to_file_path()
4839                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4840
4841                    if let Some(parent_path) = abs_path.parent() {
4842                        fs.create_dir(parent_path).await?;
4843                    }
4844                    if abs_path.ends_with("/") {
4845                        fs.create_dir(&abs_path).await?;
4846                    } else {
4847                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
4848                            .await?;
4849                    }
4850                }
4851
4852                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
4853                    let source_abs_path = op
4854                        .old_uri
4855                        .to_file_path()
4856                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4857                    let target_abs_path = op
4858                        .new_uri
4859                        .to_file_path()
4860                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4861                    fs.rename(
4862                        &source_abs_path,
4863                        &target_abs_path,
4864                        op.options.map(Into::into).unwrap_or_default(),
4865                    )
4866                    .await?;
4867                }
4868
4869                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
4870                    let abs_path = op
4871                        .uri
4872                        .to_file_path()
4873                        .map_err(|_| anyhow!("can't convert URI to path"))?;
4874                    let options = op.options.map(Into::into).unwrap_or_default();
4875                    if abs_path.ends_with("/") {
4876                        fs.remove_dir(&abs_path, options).await?;
4877                    } else {
4878                        fs.remove_file(&abs_path, options).await?;
4879                    }
4880                }
4881
4882                lsp::DocumentChangeOperation::Edit(op) => {
4883                    let buffer_to_edit = this
4884                        .update(cx, |this, cx| {
4885                            this.open_local_buffer_via_lsp(
4886                                op.text_document.uri,
4887                                language_server.server_id(),
4888                                lsp_adapter.name.clone(),
4889                                cx,
4890                            )
4891                        })
4892                        .await?;
4893
4894                    let edits = this
4895                        .update(cx, |this, cx| {
4896                            let edits = op.edits.into_iter().map(|edit| match edit {
4897                                OneOf::Left(edit) => edit,
4898                                OneOf::Right(edit) => edit.text_edit,
4899                            });
4900                            this.edits_from_lsp(
4901                                &buffer_to_edit,
4902                                edits,
4903                                language_server.server_id(),
4904                                op.text_document.version,
4905                                cx,
4906                            )
4907                        })
4908                        .await?;
4909
4910                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
4911                        buffer.finalize_last_transaction();
4912                        buffer.start_transaction();
4913                        for (range, text) in edits {
4914                            buffer.edit([(range, text)], None, cx);
4915                        }
4916                        let transaction = if buffer.end_transaction(cx).is_some() {
4917                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4918                            if !push_to_history {
4919                                buffer.forget_transaction(transaction.id);
4920                            }
4921                            Some(transaction)
4922                        } else {
4923                            None
4924                        };
4925
4926                        transaction
4927                    });
4928                    if let Some(transaction) = transaction {
4929                        project_transaction.0.insert(buffer_to_edit, transaction);
4930                    }
4931                }
4932            }
4933        }
4934
4935        Ok(project_transaction)
4936    }
4937
4938    pub fn prepare_rename<T: ToPointUtf16>(
4939        &self,
4940        buffer: ModelHandle<Buffer>,
4941        position: T,
4942        cx: &mut ModelContext<Self>,
4943    ) -> Task<Result<Option<Range<Anchor>>>> {
4944        let position = position.to_point_utf16(buffer.read(cx));
4945        self.request_lsp(buffer, PrepareRename { position }, cx)
4946    }
4947
4948    pub fn perform_rename<T: ToPointUtf16>(
4949        &self,
4950        buffer: ModelHandle<Buffer>,
4951        position: T,
4952        new_name: String,
4953        push_to_history: bool,
4954        cx: &mut ModelContext<Self>,
4955    ) -> Task<Result<ProjectTransaction>> {
4956        let position = position.to_point_utf16(buffer.read(cx));
4957        self.request_lsp(
4958            buffer,
4959            PerformRename {
4960                position,
4961                new_name,
4962                push_to_history,
4963            },
4964            cx,
4965        )
4966    }
4967
4968    pub fn on_type_format<T: ToPointUtf16>(
4969        &self,
4970        buffer: ModelHandle<Buffer>,
4971        position: T,
4972        trigger: String,
4973        push_to_history: bool,
4974        cx: &mut ModelContext<Self>,
4975    ) -> Task<Result<Option<Transaction>>> {
4976        let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
4977            let position = position.to_point_utf16(buffer);
4978            (
4979                position,
4980                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
4981                    .tab_size,
4982            )
4983        });
4984        self.request_lsp(
4985            buffer.clone(),
4986            OnTypeFormatting {
4987                position,
4988                trigger,
4989                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
4990                push_to_history,
4991            },
4992            cx,
4993        )
4994    }
4995
4996    pub fn inlay_hints<T: ToOffset>(
4997        &self,
4998        buffer_handle: ModelHandle<Buffer>,
4999        range: Range<T>,
5000        cx: &mut ModelContext<Self>,
5001    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5002        let buffer = buffer_handle.read(cx);
5003        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5004        let range_start = range.start;
5005        let range_end = range.end;
5006        let buffer_id = buffer.remote_id();
5007        let buffer_version = buffer.version().clone();
5008        let lsp_request = InlayHints { range };
5009
5010        if self.is_local() {
5011            let lsp_request_task = self.request_lsp(buffer_handle.clone(), lsp_request, cx);
5012            cx.spawn(|_, mut cx| async move {
5013                buffer_handle
5014                    .update(&mut cx, |buffer, _| {
5015                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5016                    })
5017                    .await
5018                    .context("waiting for inlay hint request range edits")?;
5019                lsp_request_task.await.context("inlay hints LSP request")
5020            })
5021        } else if let Some(project_id) = self.remote_id() {
5022            let client = self.client.clone();
5023            let request = proto::InlayHints {
5024                project_id,
5025                buffer_id,
5026                start: Some(serialize_anchor(&range_start)),
5027                end: Some(serialize_anchor(&range_end)),
5028                version: serialize_version(&buffer_version),
5029            };
5030            cx.spawn(|project, cx| async move {
5031                let response = client
5032                    .request(request)
5033                    .await
5034                    .context("inlay hints proto request")?;
5035                let hints_request_result = LspCommand::response_from_proto(
5036                    lsp_request,
5037                    response,
5038                    project,
5039                    buffer_handle.clone(),
5040                    cx,
5041                )
5042                .await;
5043
5044                hints_request_result.context("inlay hints proto response conversion")
5045            })
5046        } else {
5047            Task::ready(Err(anyhow!("project does not have a remote id")))
5048        }
5049    }
5050
5051    pub fn resolve_inlay_hint(
5052        &self,
5053        hint: InlayHint,
5054        buffer_handle: ModelHandle<Buffer>,
5055        server_id: LanguageServerId,
5056        cx: &mut ModelContext<Self>,
5057    ) -> Task<anyhow::Result<InlayHint>> {
5058        if self.is_local() {
5059            let buffer = buffer_handle.read(cx);
5060            let (_, lang_server) = if let Some((adapter, server)) =
5061                self.language_server_for_buffer(buffer, server_id, cx)
5062            {
5063                (adapter.clone(), server.clone())
5064            } else {
5065                return Task::ready(Ok(hint));
5066            };
5067            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5068                return Task::ready(Ok(hint));
5069            }
5070
5071            let buffer_snapshot = buffer.snapshot();
5072            cx.spawn(|project, mut cx| async move {
5073                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5074                    InlayHints::project_to_lsp_hint(hint, &project, &buffer_snapshot, &cx),
5075                );
5076                let resolved_hint = resolve_task
5077                    .await
5078                    .context("inlay hint resolve LSP request")?;
5079                let resolved_hint = InlayHints::lsp_to_project_hint(
5080                    resolved_hint,
5081                    &project,
5082                    &buffer_handle,
5083                    server_id,
5084                    ResolveState::Resolved,
5085                    false,
5086                    &mut cx,
5087                )
5088                .await?;
5089                Ok(resolved_hint)
5090            })
5091        } else if let Some(project_id) = self.remote_id() {
5092            let client = self.client.clone();
5093            let request = proto::ResolveInlayHint {
5094                project_id,
5095                buffer_id: buffer_handle.read(cx).remote_id(),
5096                language_server_id: server_id.0 as u64,
5097                hint: Some(InlayHints::project_to_proto_hint(hint.clone(), cx)),
5098            };
5099            cx.spawn(|project, mut cx| async move {
5100                let response = client
5101                    .request(request)
5102                    .await
5103                    .context("inlay hints proto request")?;
5104                match response.hint {
5105                    Some(resolved_hint) => {
5106                        InlayHints::proto_to_project_hint(resolved_hint, &project, &mut cx)
5107                            .await
5108                            .context("inlay hints proto resolve response conversion")
5109                    }
5110                    None => Ok(hint),
5111                }
5112            })
5113        } else {
5114            Task::ready(Err(anyhow!("project does not have a remote id")))
5115        }
5116    }
5117
5118    #[allow(clippy::type_complexity)]
5119    pub fn search(
5120        &self,
5121        query: SearchQuery,
5122        cx: &mut ModelContext<Self>,
5123    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5124        if self.is_local() {
5125            self.search_local(query, cx)
5126        } else if let Some(project_id) = self.remote_id() {
5127            let (tx, rx) = smol::channel::unbounded();
5128            let request = self.client.request(query.to_proto(project_id));
5129            cx.spawn(|this, mut cx| async move {
5130                let response = request.await?;
5131                let mut result = HashMap::default();
5132                for location in response.locations {
5133                    let target_buffer = this
5134                        .update(&mut cx, |this, cx| {
5135                            this.wait_for_remote_buffer(location.buffer_id, cx)
5136                        })
5137                        .await?;
5138                    let start = location
5139                        .start
5140                        .and_then(deserialize_anchor)
5141                        .ok_or_else(|| anyhow!("missing target start"))?;
5142                    let end = location
5143                        .end
5144                        .and_then(deserialize_anchor)
5145                        .ok_or_else(|| anyhow!("missing target end"))?;
5146                    result
5147                        .entry(target_buffer)
5148                        .or_insert(Vec::new())
5149                        .push(start..end)
5150                }
5151                for (buffer, ranges) in result {
5152                    let _ = tx.send((buffer, ranges)).await;
5153                }
5154                Result::<(), anyhow::Error>::Ok(())
5155            })
5156            .detach_and_log_err(cx);
5157            rx
5158        } else {
5159            unimplemented!();
5160        }
5161    }
5162
5163    pub fn search_local(
5164        &self,
5165        query: SearchQuery,
5166        cx: &mut ModelContext<Self>,
5167    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5168        // Local search is split into several phases.
5169        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5170        // and the second phase that finds positions of all the matches found in the candidate files.
5171        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5172        //
5173        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5174        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5175        //
5176        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5177        //    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
5178        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5179        // 2. At this point, we have a list of all potentially matching buffers/files.
5180        //    We sort that list by buffer path - this list is retained for later use.
5181        //    We ensure that all buffers are now opened and available in project.
5182        // 3. We run a scan over all the candidate buffers on multiple background threads.
5183        //    We cannot assume that there will even be a match - while at least one match
5184        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5185        //    There is also an auxilliary background thread responsible for result gathering.
5186        //    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),
5187        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5188        //    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
5189        //    entry - which might already be available thanks to out-of-order processing.
5190        //
5191        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5192        // 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.
5193        // 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
5194        // in face of constantly updating list of sorted matches.
5195        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5196        let snapshots = self
5197            .visible_worktrees(cx)
5198            .filter_map(|tree| {
5199                let tree = tree.read(cx).as_local()?;
5200                Some(tree.snapshot())
5201            })
5202            .collect::<Vec<_>>();
5203
5204        let background = cx.background().clone();
5205        let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5206        if path_count == 0 {
5207            let (_, rx) = smol::channel::bounded(1024);
5208            return rx;
5209        }
5210        let workers = background.num_cpus().min(path_count);
5211        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5212        let mut unnamed_files = vec![];
5213        let opened_buffers = self
5214            .opened_buffers
5215            .iter()
5216            .filter_map(|(_, b)| {
5217                let buffer = b.upgrade(cx)?;
5218                let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
5219                if let Some(path) = snapshot.file().map(|file| file.path()) {
5220                    Some((path.clone(), (buffer, snapshot)))
5221                } else {
5222                    unnamed_files.push(buffer);
5223                    None
5224                }
5225            })
5226            .collect();
5227        cx.background()
5228            .spawn(Self::background_search(
5229                unnamed_files,
5230                opened_buffers,
5231                cx.background().clone(),
5232                self.fs.clone(),
5233                workers,
5234                query.clone(),
5235                path_count,
5236                snapshots,
5237                matching_paths_tx,
5238            ))
5239            .detach();
5240
5241        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5242        let background = cx.background().clone();
5243        let (result_tx, result_rx) = smol::channel::bounded(1024);
5244        cx.background()
5245            .spawn(async move {
5246                let Ok(buffers) = buffers.await else {
5247                    return;
5248                };
5249
5250                let buffers_len = buffers.len();
5251                if buffers_len == 0 {
5252                    return;
5253                }
5254                let query = &query;
5255                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5256                background
5257                    .scoped(|scope| {
5258                        #[derive(Clone)]
5259                        struct FinishedStatus {
5260                            entry: Option<(ModelHandle<Buffer>, Vec<Range<Anchor>>)>,
5261                            buffer_index: SearchMatchCandidateIndex,
5262                        }
5263
5264                        for _ in 0..workers {
5265                            let finished_tx = finished_tx.clone();
5266                            let mut buffers_rx = buffers_rx.clone();
5267                            scope.spawn(async move {
5268                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5269                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5270                                    {
5271                                        if query.file_matches(
5272                                            snapshot.file().map(|file| file.path().as_ref()),
5273                                        ) {
5274                                            query
5275                                                .search(&snapshot, None)
5276                                                .await
5277                                                .iter()
5278                                                .map(|range| {
5279                                                    snapshot.anchor_before(range.start)
5280                                                        ..snapshot.anchor_after(range.end)
5281                                                })
5282                                                .collect()
5283                                        } else {
5284                                            Vec::new()
5285                                        }
5286                                    } else {
5287                                        Vec::new()
5288                                    };
5289
5290                                    let status = if !buffer_matches.is_empty() {
5291                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5292                                            Some((buffer.clone(), buffer_matches))
5293                                        } else {
5294                                            None
5295                                        };
5296                                        FinishedStatus {
5297                                            entry,
5298                                            buffer_index,
5299                                        }
5300                                    } else {
5301                                        FinishedStatus {
5302                                            entry: None,
5303                                            buffer_index,
5304                                        }
5305                                    };
5306                                    if finished_tx.send(status).await.is_err() {
5307                                        break;
5308                                    }
5309                                }
5310                            });
5311                        }
5312                        // Report sorted matches
5313                        scope.spawn(async move {
5314                            let mut current_index = 0;
5315                            let mut scratch = vec![None; buffers_len];
5316                            while let Some(status) = finished_rx.next().await {
5317                                debug_assert!(
5318                                    scratch[status.buffer_index].is_none(),
5319                                    "Got match status of position {} twice",
5320                                    status.buffer_index
5321                                );
5322                                let index = status.buffer_index;
5323                                scratch[index] = Some(status);
5324                                while current_index < buffers_len {
5325                                    let Some(current_entry) = scratch[current_index].take() else {
5326                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5327                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5328                                        // this time.
5329                                        break;
5330                                    };
5331                                    if let Some(entry) = current_entry.entry {
5332                                        result_tx.send(entry).await.log_err();
5333                                    }
5334                                    current_index += 1;
5335                                }
5336                                if current_index == buffers_len {
5337                                    break;
5338                                }
5339                            }
5340                        });
5341                    })
5342                    .await;
5343            })
5344            .detach();
5345        result_rx
5346    }
5347    /// Pick paths that might potentially contain a match of a given search query.
5348    async fn background_search(
5349        unnamed_buffers: Vec<ModelHandle<Buffer>>,
5350        opened_buffers: HashMap<Arc<Path>, (ModelHandle<Buffer>, BufferSnapshot)>,
5351        background: Arc<Background>,
5352        fs: Arc<dyn Fs>,
5353        workers: usize,
5354        query: SearchQuery,
5355        path_count: usize,
5356        snapshots: Vec<LocalSnapshot>,
5357        matching_paths_tx: Sender<SearchMatchCandidate>,
5358    ) {
5359        let fs = &fs;
5360        let query = &query;
5361        let matching_paths_tx = &matching_paths_tx;
5362        let snapshots = &snapshots;
5363        let paths_per_worker = (path_count + workers - 1) / workers;
5364        for buffer in unnamed_buffers {
5365            matching_paths_tx
5366                .send(SearchMatchCandidate::OpenBuffer {
5367                    buffer: buffer.clone(),
5368                    path: None,
5369                })
5370                .await
5371                .log_err();
5372        }
5373        for (path, (buffer, _)) in opened_buffers.iter() {
5374            matching_paths_tx
5375                .send(SearchMatchCandidate::OpenBuffer {
5376                    buffer: buffer.clone(),
5377                    path: Some(path.clone()),
5378                })
5379                .await
5380                .log_err();
5381        }
5382        background
5383            .scoped(|scope| {
5384                for worker_ix in 0..workers {
5385                    let worker_start_ix = worker_ix * paths_per_worker;
5386                    let worker_end_ix = worker_start_ix + paths_per_worker;
5387                    let unnamed_buffers = opened_buffers.clone();
5388                    scope.spawn(async move {
5389                        let mut snapshot_start_ix = 0;
5390                        let mut abs_path = PathBuf::new();
5391                        for snapshot in snapshots {
5392                            let snapshot_end_ix = snapshot_start_ix + snapshot.visible_file_count();
5393                            if worker_end_ix <= snapshot_start_ix {
5394                                break;
5395                            } else if worker_start_ix > snapshot_end_ix {
5396                                snapshot_start_ix = snapshot_end_ix;
5397                                continue;
5398                            } else {
5399                                let start_in_snapshot =
5400                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5401                                let end_in_snapshot =
5402                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5403
5404                                for entry in snapshot
5405                                    .files(false, start_in_snapshot)
5406                                    .take(end_in_snapshot - start_in_snapshot)
5407                                {
5408                                    if matching_paths_tx.is_closed() {
5409                                        break;
5410                                    }
5411                                    if unnamed_buffers.contains_key(&entry.path) {
5412                                        continue;
5413                                    }
5414                                    let matches = if query.file_matches(Some(&entry.path)) {
5415                                        abs_path.clear();
5416                                        abs_path.push(&snapshot.abs_path());
5417                                        abs_path.push(&entry.path);
5418                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5419                                        {
5420                                            query.detect(file).unwrap_or(false)
5421                                        } else {
5422                                            false
5423                                        }
5424                                    } else {
5425                                        false
5426                                    };
5427
5428                                    if matches {
5429                                        let project_path = SearchMatchCandidate::Path {
5430                                            worktree_id: snapshot.id(),
5431                                            path: entry.path.clone(),
5432                                        };
5433                                        if matching_paths_tx.send(project_path).await.is_err() {
5434                                            break;
5435                                        }
5436                                    }
5437                                }
5438
5439                                snapshot_start_ix = snapshot_end_ix;
5440                            }
5441                        }
5442                    });
5443                }
5444            })
5445            .await;
5446    }
5447
5448    // TODO: Wire this up to allow selecting a server?
5449    fn request_lsp<R: LspCommand>(
5450        &self,
5451        buffer_handle: ModelHandle<Buffer>,
5452        request: R,
5453        cx: &mut ModelContext<Self>,
5454    ) -> Task<Result<R::Response>>
5455    where
5456        <R::LspRequest as lsp::request::Request>::Result: Send,
5457    {
5458        let buffer = buffer_handle.read(cx);
5459        if self.is_local() {
5460            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5461            if let Some((file, language_server)) = file.zip(
5462                self.primary_language_servers_for_buffer(buffer, cx)
5463                    .map(|(_, server)| server.clone()),
5464            ) {
5465                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5466                return cx.spawn(|this, cx| async move {
5467                    if !request.check_capabilities(language_server.capabilities()) {
5468                        return Ok(Default::default());
5469                    }
5470
5471                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5472                    let response = match result {
5473                        Ok(response) => response,
5474
5475                        Err(err) => {
5476                            log::warn!(
5477                                "Generic lsp request to {} failed: {}",
5478                                language_server.name(),
5479                                err
5480                            );
5481                            return Err(err);
5482                        }
5483                    };
5484
5485                    request
5486                        .response_from_lsp(
5487                            response,
5488                            this,
5489                            buffer_handle,
5490                            language_server.server_id(),
5491                            cx,
5492                        )
5493                        .await
5494                });
5495            }
5496        } else if let Some(project_id) = self.remote_id() {
5497            let rpc = self.client.clone();
5498            let message = request.to_proto(project_id, buffer);
5499            return cx.spawn_weak(|this, cx| async move {
5500                // Ensure the project is still alive by the time the task
5501                // is scheduled.
5502                this.upgrade(&cx)
5503                    .ok_or_else(|| anyhow!("project dropped"))?;
5504
5505                let response = rpc.request(message).await?;
5506
5507                let this = this
5508                    .upgrade(&cx)
5509                    .ok_or_else(|| anyhow!("project dropped"))?;
5510                if this.read_with(&cx, |this, _| this.is_read_only()) {
5511                    Err(anyhow!("disconnected before completing request"))
5512                } else {
5513                    request
5514                        .response_from_proto(response, this, buffer_handle, cx)
5515                        .await
5516                }
5517            });
5518        }
5519        Task::ready(Ok(Default::default()))
5520    }
5521
5522    fn sort_candidates_and_open_buffers(
5523        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
5524        cx: &mut ModelContext<Self>,
5525    ) -> (
5526        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
5527        Receiver<(
5528            Option<(ModelHandle<Buffer>, BufferSnapshot)>,
5529            SearchMatchCandidateIndex,
5530        )>,
5531    ) {
5532        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5533        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
5534        cx.spawn(|this, cx| async move {
5535            let mut buffers = vec![];
5536            while let Some(entry) = matching_paths_rx.next().await {
5537                buffers.push(entry);
5538            }
5539            buffers.sort_by_key(|candidate| candidate.path());
5540            let matching_paths = buffers.clone();
5541            let _ = sorted_buffers_tx.send(buffers);
5542            for (index, candidate) in matching_paths.into_iter().enumerate() {
5543                if buffers_tx.is_closed() {
5544                    break;
5545                }
5546                let this = this.clone();
5547                let buffers_tx = buffers_tx.clone();
5548                cx.spawn(|mut cx| async move {
5549                    let buffer = match candidate {
5550                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
5551                        SearchMatchCandidate::Path { worktree_id, path } => this
5552                            .update(&mut cx, |this, cx| {
5553                                this.open_buffer((worktree_id, path), cx)
5554                            })
5555                            .await
5556                            .log_err(),
5557                    };
5558                    if let Some(buffer) = buffer {
5559                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5560                        buffers_tx
5561                            .send((Some((buffer, snapshot)), index))
5562                            .await
5563                            .log_err();
5564                    } else {
5565                        buffers_tx.send((None, index)).await.log_err();
5566                    }
5567
5568                    Ok::<_, anyhow::Error>(())
5569                })
5570                .detach();
5571            }
5572        })
5573        .detach();
5574        (sorted_buffers_rx, buffers_rx)
5575    }
5576
5577    pub fn find_or_create_local_worktree(
5578        &mut self,
5579        abs_path: impl AsRef<Path>,
5580        visible: bool,
5581        cx: &mut ModelContext<Self>,
5582    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5583        let abs_path = abs_path.as_ref();
5584        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5585            Task::ready(Ok((tree, relative_path)))
5586        } else {
5587            let worktree = self.create_local_worktree(abs_path, visible, cx);
5588            cx.foreground()
5589                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5590        }
5591    }
5592
5593    pub fn find_local_worktree(
5594        &self,
5595        abs_path: &Path,
5596        cx: &AppContext,
5597    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5598        for tree in &self.worktrees {
5599            if let Some(tree) = tree.upgrade(cx) {
5600                if let Some(relative_path) = tree
5601                    .read(cx)
5602                    .as_local()
5603                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5604                {
5605                    return Some((tree.clone(), relative_path.into()));
5606                }
5607            }
5608        }
5609        None
5610    }
5611
5612    pub fn is_shared(&self) -> bool {
5613        match &self.client_state {
5614            Some(ProjectClientState::Local { .. }) => true,
5615            _ => false,
5616        }
5617    }
5618
5619    fn create_local_worktree(
5620        &mut self,
5621        abs_path: impl AsRef<Path>,
5622        visible: bool,
5623        cx: &mut ModelContext<Self>,
5624    ) -> Task<Result<ModelHandle<Worktree>>> {
5625        let fs = self.fs.clone();
5626        let client = self.client.clone();
5627        let next_entry_id = self.next_entry_id.clone();
5628        let path: Arc<Path> = abs_path.as_ref().into();
5629        let task = self
5630            .loading_local_worktrees
5631            .entry(path.clone())
5632            .or_insert_with(|| {
5633                cx.spawn(|project, mut cx| {
5634                    async move {
5635                        let worktree = Worktree::local(
5636                            client.clone(),
5637                            path.clone(),
5638                            visible,
5639                            fs,
5640                            next_entry_id,
5641                            &mut cx,
5642                        )
5643                        .await;
5644
5645                        project.update(&mut cx, |project, _| {
5646                            project.loading_local_worktrees.remove(&path);
5647                        });
5648
5649                        let worktree = worktree?;
5650                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
5651                        Ok(worktree)
5652                    }
5653                    .map_err(Arc::new)
5654                })
5655                .shared()
5656            })
5657            .clone();
5658        cx.foreground().spawn(async move {
5659            match task.await {
5660                Ok(worktree) => Ok(worktree),
5661                Err(err) => Err(anyhow!("{}", err)),
5662            }
5663        })
5664    }
5665
5666    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
5667        self.worktrees.retain(|worktree| {
5668            if let Some(worktree) = worktree.upgrade(cx) {
5669                let id = worktree.read(cx).id();
5670                if id == id_to_remove {
5671                    cx.emit(Event::WorktreeRemoved(id));
5672                    false
5673                } else {
5674                    true
5675                }
5676            } else {
5677                false
5678            }
5679        });
5680        self.metadata_changed(cx);
5681    }
5682
5683    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
5684        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
5685        if worktree.read(cx).is_local() {
5686            cx.subscribe(worktree, |this, worktree, event, cx| match event {
5687                worktree::Event::UpdatedEntries(changes) => {
5688                    this.update_local_worktree_buffers(&worktree, changes, cx);
5689                    this.update_local_worktree_language_servers(&worktree, changes, cx);
5690                    this.update_local_worktree_settings(&worktree, changes, cx);
5691                    cx.emit(Event::WorktreeUpdatedEntries(
5692                        worktree.read(cx).id(),
5693                        changes.clone(),
5694                    ));
5695                }
5696                worktree::Event::UpdatedGitRepositories(updated_repos) => {
5697                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
5698                }
5699            })
5700            .detach();
5701        }
5702
5703        let push_strong_handle = {
5704            let worktree = worktree.read(cx);
5705            self.is_shared() || worktree.is_visible() || worktree.is_remote()
5706        };
5707        if push_strong_handle {
5708            self.worktrees
5709                .push(WorktreeHandle::Strong(worktree.clone()));
5710        } else {
5711            self.worktrees
5712                .push(WorktreeHandle::Weak(worktree.downgrade()));
5713        }
5714
5715        let handle_id = worktree.id();
5716        cx.observe_release(worktree, move |this, worktree, cx| {
5717            let _ = this.remove_worktree(worktree.id(), cx);
5718            cx.update_global::<SettingsStore, _, _>(|store, cx| {
5719                store.clear_local_settings(handle_id, cx).log_err()
5720            });
5721        })
5722        .detach();
5723
5724        cx.emit(Event::WorktreeAdded);
5725        self.metadata_changed(cx);
5726    }
5727
5728    fn update_local_worktree_buffers(
5729        &mut self,
5730        worktree_handle: &ModelHandle<Worktree>,
5731        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5732        cx: &mut ModelContext<Self>,
5733    ) {
5734        let snapshot = worktree_handle.read(cx).snapshot();
5735
5736        let mut renamed_buffers = Vec::new();
5737        for (path, entry_id, _) in changes {
5738            let worktree_id = worktree_handle.read(cx).id();
5739            let project_path = ProjectPath {
5740                worktree_id,
5741                path: path.clone(),
5742            };
5743
5744            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
5745                Some(&buffer_id) => buffer_id,
5746                None => match self.local_buffer_ids_by_path.get(&project_path) {
5747                    Some(&buffer_id) => buffer_id,
5748                    None => continue,
5749                },
5750            };
5751
5752            let open_buffer = self.opened_buffers.get(&buffer_id);
5753            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
5754                buffer
5755            } else {
5756                self.opened_buffers.remove(&buffer_id);
5757                self.local_buffer_ids_by_path.remove(&project_path);
5758                self.local_buffer_ids_by_entry_id.remove(entry_id);
5759                continue;
5760            };
5761
5762            buffer.update(cx, |buffer, cx| {
5763                if let Some(old_file) = File::from_dyn(buffer.file()) {
5764                    if old_file.worktree != *worktree_handle {
5765                        return;
5766                    }
5767
5768                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
5769                        File {
5770                            is_local: true,
5771                            entry_id: entry.id,
5772                            mtime: entry.mtime,
5773                            path: entry.path.clone(),
5774                            worktree: worktree_handle.clone(),
5775                            is_deleted: false,
5776                        }
5777                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
5778                        File {
5779                            is_local: true,
5780                            entry_id: entry.id,
5781                            mtime: entry.mtime,
5782                            path: entry.path.clone(),
5783                            worktree: worktree_handle.clone(),
5784                            is_deleted: false,
5785                        }
5786                    } else {
5787                        File {
5788                            is_local: true,
5789                            entry_id: old_file.entry_id,
5790                            path: old_file.path().clone(),
5791                            mtime: old_file.mtime(),
5792                            worktree: worktree_handle.clone(),
5793                            is_deleted: true,
5794                        }
5795                    };
5796
5797                    let old_path = old_file.abs_path(cx);
5798                    if new_file.abs_path(cx) != old_path {
5799                        renamed_buffers.push((cx.handle(), old_file.clone()));
5800                        self.local_buffer_ids_by_path.remove(&project_path);
5801                        self.local_buffer_ids_by_path.insert(
5802                            ProjectPath {
5803                                worktree_id,
5804                                path: path.clone(),
5805                            },
5806                            buffer_id,
5807                        );
5808                    }
5809
5810                    if new_file.entry_id != *entry_id {
5811                        self.local_buffer_ids_by_entry_id.remove(entry_id);
5812                        self.local_buffer_ids_by_entry_id
5813                            .insert(new_file.entry_id, buffer_id);
5814                    }
5815
5816                    if new_file != *old_file {
5817                        if let Some(project_id) = self.remote_id() {
5818                            self.client
5819                                .send(proto::UpdateBufferFile {
5820                                    project_id,
5821                                    buffer_id: buffer_id as u64,
5822                                    file: Some(new_file.to_proto()),
5823                                })
5824                                .log_err();
5825                        }
5826
5827                        buffer.file_updated(Arc::new(new_file), cx).detach();
5828                    }
5829                }
5830            });
5831        }
5832
5833        for (buffer, old_file) in renamed_buffers {
5834            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
5835            self.detect_language_for_buffer(&buffer, cx);
5836            self.register_buffer_with_language_servers(&buffer, cx);
5837        }
5838    }
5839
5840    fn update_local_worktree_language_servers(
5841        &mut self,
5842        worktree_handle: &ModelHandle<Worktree>,
5843        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
5844        cx: &mut ModelContext<Self>,
5845    ) {
5846        if changes.is_empty() {
5847            return;
5848        }
5849
5850        let worktree_id = worktree_handle.read(cx).id();
5851        let mut language_server_ids = self
5852            .language_server_ids
5853            .iter()
5854            .filter_map(|((server_worktree_id, _), server_id)| {
5855                (*server_worktree_id == worktree_id).then_some(*server_id)
5856            })
5857            .collect::<Vec<_>>();
5858        language_server_ids.sort();
5859        language_server_ids.dedup();
5860
5861        let abs_path = worktree_handle.read(cx).abs_path();
5862        for server_id in &language_server_ids {
5863            if let Some(LanguageServerState::Running {
5864                server,
5865                watched_paths,
5866                ..
5867            }) = self.language_servers.get(server_id)
5868            {
5869                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
5870                    let params = lsp::DidChangeWatchedFilesParams {
5871                        changes: changes
5872                            .iter()
5873                            .filter_map(|(path, _, change)| {
5874                                if !watched_paths.is_match(&path) {
5875                                    return None;
5876                                }
5877                                let typ = match change {
5878                                    PathChange::Loaded => return None,
5879                                    PathChange::Added => lsp::FileChangeType::CREATED,
5880                                    PathChange::Removed => lsp::FileChangeType::DELETED,
5881                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
5882                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
5883                                };
5884                                Some(lsp::FileEvent {
5885                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
5886                                    typ,
5887                                })
5888                            })
5889                            .collect(),
5890                    };
5891
5892                    if !params.changes.is_empty() {
5893                        server
5894                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
5895                            .log_err();
5896                    }
5897                }
5898            }
5899        }
5900    }
5901
5902    fn update_local_worktree_buffers_git_repos(
5903        &mut self,
5904        worktree_handle: ModelHandle<Worktree>,
5905        changed_repos: &UpdatedGitRepositoriesSet,
5906        cx: &mut ModelContext<Self>,
5907    ) {
5908        debug_assert!(worktree_handle.read(cx).is_local());
5909
5910        // Identify the loading buffers whose containing repository that has changed.
5911        let future_buffers = self
5912            .loading_buffers_by_path
5913            .iter()
5914            .filter_map(|(project_path, receiver)| {
5915                if project_path.worktree_id != worktree_handle.read(cx).id() {
5916                    return None;
5917                }
5918                let path = &project_path.path;
5919                changed_repos
5920                    .iter()
5921                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
5922                let receiver = receiver.clone();
5923                let path = path.clone();
5924                Some(async move {
5925                    wait_for_loading_buffer(receiver)
5926                        .await
5927                        .ok()
5928                        .map(|buffer| (buffer, path))
5929                })
5930            })
5931            .collect::<FuturesUnordered<_>>();
5932
5933        // Identify the current buffers whose containing repository has changed.
5934        let current_buffers = self
5935            .opened_buffers
5936            .values()
5937            .filter_map(|buffer| {
5938                let buffer = buffer.upgrade(cx)?;
5939                let file = File::from_dyn(buffer.read(cx).file())?;
5940                if file.worktree != worktree_handle {
5941                    return None;
5942                }
5943                let path = file.path();
5944                changed_repos
5945                    .iter()
5946                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
5947                Some((buffer, path.clone()))
5948            })
5949            .collect::<Vec<_>>();
5950
5951        if future_buffers.len() + current_buffers.len() == 0 {
5952            return;
5953        }
5954
5955        let remote_id = self.remote_id();
5956        let client = self.client.clone();
5957        cx.spawn_weak(move |_, mut cx| async move {
5958            // Wait for all of the buffers to load.
5959            let future_buffers = future_buffers.collect::<Vec<_>>().await;
5960
5961            // Reload the diff base for every buffer whose containing git repository has changed.
5962            let snapshot =
5963                worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
5964            let diff_bases_by_buffer = cx
5965                .background()
5966                .spawn(async move {
5967                    future_buffers
5968                        .into_iter()
5969                        .filter_map(|e| e)
5970                        .chain(current_buffers)
5971                        .filter_map(|(buffer, path)| {
5972                            let (work_directory, repo) =
5973                                snapshot.repository_and_work_directory_for_path(&path)?;
5974                            let repo = snapshot.get_local_repo(&repo)?;
5975                            let relative_path = path.strip_prefix(&work_directory).ok()?;
5976                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
5977                            Some((buffer, base_text))
5978                        })
5979                        .collect::<Vec<_>>()
5980                })
5981                .await;
5982
5983            // Assign the new diff bases on all of the buffers.
5984            for (buffer, diff_base) in diff_bases_by_buffer {
5985                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
5986                    buffer.set_diff_base(diff_base.clone(), cx);
5987                    buffer.remote_id()
5988                });
5989                if let Some(project_id) = remote_id {
5990                    client
5991                        .send(proto::UpdateDiffBase {
5992                            project_id,
5993                            buffer_id,
5994                            diff_base,
5995                        })
5996                        .log_err();
5997                }
5998            }
5999        })
6000        .detach();
6001    }
6002
6003    fn update_local_worktree_settings(
6004        &mut self,
6005        worktree: &ModelHandle<Worktree>,
6006        changes: &UpdatedEntriesSet,
6007        cx: &mut ModelContext<Self>,
6008    ) {
6009        let project_id = self.remote_id();
6010        let worktree_id = worktree.id();
6011        let worktree = worktree.read(cx).as_local().unwrap();
6012        let remote_worktree_id = worktree.id();
6013
6014        let mut settings_contents = Vec::new();
6015        for (path, _, change) in changes.iter() {
6016            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6017                let settings_dir = Arc::from(
6018                    path.ancestors()
6019                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6020                        .unwrap(),
6021                );
6022                let fs = self.fs.clone();
6023                let removed = *change == PathChange::Removed;
6024                let abs_path = worktree.absolutize(path);
6025                settings_contents.push(async move {
6026                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6027                });
6028            }
6029        }
6030
6031        if settings_contents.is_empty() {
6032            return;
6033        }
6034
6035        let client = self.client.clone();
6036        cx.spawn_weak(move |_, mut cx| async move {
6037            let settings_contents: Vec<(Arc<Path>, _)> =
6038                futures::future::join_all(settings_contents).await;
6039            cx.update(|cx| {
6040                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6041                    for (directory, file_content) in settings_contents {
6042                        let file_content = file_content.and_then(|content| content.log_err());
6043                        store
6044                            .set_local_settings(
6045                                worktree_id,
6046                                directory.clone(),
6047                                file_content.as_ref().map(String::as_str),
6048                                cx,
6049                            )
6050                            .log_err();
6051                        if let Some(remote_id) = project_id {
6052                            client
6053                                .send(proto::UpdateWorktreeSettings {
6054                                    project_id: remote_id,
6055                                    worktree_id: remote_worktree_id.to_proto(),
6056                                    path: directory.to_string_lossy().into_owned(),
6057                                    content: file_content,
6058                                })
6059                                .log_err();
6060                        }
6061                    }
6062                });
6063            });
6064        })
6065        .detach();
6066    }
6067
6068    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6069        let new_active_entry = entry.and_then(|project_path| {
6070            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6071            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6072            Some(entry.id)
6073        });
6074        if new_active_entry != self.active_entry {
6075            self.active_entry = new_active_entry;
6076            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6077        }
6078    }
6079
6080    pub fn language_servers_running_disk_based_diagnostics(
6081        &self,
6082    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6083        self.language_server_statuses
6084            .iter()
6085            .filter_map(|(id, status)| {
6086                if status.has_pending_diagnostic_updates {
6087                    Some(*id)
6088                } else {
6089                    None
6090                }
6091            })
6092    }
6093
6094    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
6095        let mut summary = DiagnosticSummary::default();
6096        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
6097            summary.error_count += path_summary.error_count;
6098            summary.warning_count += path_summary.warning_count;
6099        }
6100        summary
6101    }
6102
6103    pub fn diagnostic_summaries<'a>(
6104        &'a self,
6105        cx: &'a AppContext,
6106    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6107        self.visible_worktrees(cx).flat_map(move |worktree| {
6108            let worktree = worktree.read(cx);
6109            let worktree_id = worktree.id();
6110            worktree
6111                .diagnostic_summaries()
6112                .map(move |(path, server_id, summary)| {
6113                    (ProjectPath { worktree_id, path }, server_id, summary)
6114                })
6115        })
6116    }
6117
6118    pub fn disk_based_diagnostics_started(
6119        &mut self,
6120        language_server_id: LanguageServerId,
6121        cx: &mut ModelContext<Self>,
6122    ) {
6123        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6124    }
6125
6126    pub fn disk_based_diagnostics_finished(
6127        &mut self,
6128        language_server_id: LanguageServerId,
6129        cx: &mut ModelContext<Self>,
6130    ) {
6131        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6132    }
6133
6134    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6135        self.active_entry
6136    }
6137
6138    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6139        self.worktree_for_id(path.worktree_id, cx)?
6140            .read(cx)
6141            .entry_for_path(&path.path)
6142            .cloned()
6143    }
6144
6145    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6146        let worktree = self.worktree_for_entry(entry_id, cx)?;
6147        let worktree = worktree.read(cx);
6148        let worktree_id = worktree.id();
6149        let path = worktree.entry_for_id(entry_id)?.path.clone();
6150        Some(ProjectPath { worktree_id, path })
6151    }
6152
6153    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6154        let workspace_root = self
6155            .worktree_for_id(project_path.worktree_id, cx)?
6156            .read(cx)
6157            .abs_path();
6158        let project_path = project_path.path.as_ref();
6159
6160        Some(if project_path == Path::new("") {
6161            workspace_root.to_path_buf()
6162        } else {
6163            workspace_root.join(project_path)
6164        })
6165    }
6166
6167    // RPC message handlers
6168
6169    async fn handle_unshare_project(
6170        this: ModelHandle<Self>,
6171        _: TypedEnvelope<proto::UnshareProject>,
6172        _: Arc<Client>,
6173        mut cx: AsyncAppContext,
6174    ) -> Result<()> {
6175        this.update(&mut cx, |this, cx| {
6176            if this.is_local() {
6177                this.unshare(cx)?;
6178            } else {
6179                this.disconnected_from_host(cx);
6180            }
6181            Ok(())
6182        })
6183    }
6184
6185    async fn handle_add_collaborator(
6186        this: ModelHandle<Self>,
6187        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6188        _: Arc<Client>,
6189        mut cx: AsyncAppContext,
6190    ) -> Result<()> {
6191        let collaborator = envelope
6192            .payload
6193            .collaborator
6194            .take()
6195            .ok_or_else(|| anyhow!("empty collaborator"))?;
6196
6197        let collaborator = Collaborator::from_proto(collaborator)?;
6198        this.update(&mut cx, |this, cx| {
6199            this.shared_buffers.remove(&collaborator.peer_id);
6200            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6201            this.collaborators
6202                .insert(collaborator.peer_id, collaborator);
6203            cx.notify();
6204        });
6205
6206        Ok(())
6207    }
6208
6209    async fn handle_update_project_collaborator(
6210        this: ModelHandle<Self>,
6211        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6212        _: Arc<Client>,
6213        mut cx: AsyncAppContext,
6214    ) -> Result<()> {
6215        let old_peer_id = envelope
6216            .payload
6217            .old_peer_id
6218            .ok_or_else(|| anyhow!("missing old peer id"))?;
6219        let new_peer_id = envelope
6220            .payload
6221            .new_peer_id
6222            .ok_or_else(|| anyhow!("missing new peer id"))?;
6223        this.update(&mut cx, |this, cx| {
6224            let collaborator = this
6225                .collaborators
6226                .remove(&old_peer_id)
6227                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6228            let is_host = collaborator.replica_id == 0;
6229            this.collaborators.insert(new_peer_id, collaborator);
6230
6231            let buffers = this.shared_buffers.remove(&old_peer_id);
6232            log::info!(
6233                "peer {} became {}. moving buffers {:?}",
6234                old_peer_id,
6235                new_peer_id,
6236                &buffers
6237            );
6238            if let Some(buffers) = buffers {
6239                this.shared_buffers.insert(new_peer_id, buffers);
6240            }
6241
6242            if is_host {
6243                this.opened_buffers
6244                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6245                this.buffer_ordered_messages_tx
6246                    .unbounded_send(BufferOrderedMessage::Resync)
6247                    .unwrap();
6248            }
6249
6250            cx.emit(Event::CollaboratorUpdated {
6251                old_peer_id,
6252                new_peer_id,
6253            });
6254            cx.notify();
6255            Ok(())
6256        })
6257    }
6258
6259    async fn handle_remove_collaborator(
6260        this: ModelHandle<Self>,
6261        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6262        _: Arc<Client>,
6263        mut cx: AsyncAppContext,
6264    ) -> Result<()> {
6265        this.update(&mut cx, |this, cx| {
6266            let peer_id = envelope
6267                .payload
6268                .peer_id
6269                .ok_or_else(|| anyhow!("invalid peer id"))?;
6270            let replica_id = this
6271                .collaborators
6272                .remove(&peer_id)
6273                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6274                .replica_id;
6275            for buffer in this.opened_buffers.values() {
6276                if let Some(buffer) = buffer.upgrade(cx) {
6277                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6278                }
6279            }
6280            this.shared_buffers.remove(&peer_id);
6281
6282            cx.emit(Event::CollaboratorLeft(peer_id));
6283            cx.notify();
6284            Ok(())
6285        })
6286    }
6287
6288    async fn handle_update_project(
6289        this: ModelHandle<Self>,
6290        envelope: TypedEnvelope<proto::UpdateProject>,
6291        _: Arc<Client>,
6292        mut cx: AsyncAppContext,
6293    ) -> Result<()> {
6294        this.update(&mut cx, |this, cx| {
6295            // Don't handle messages that were sent before the response to us joining the project
6296            if envelope.message_id > this.join_project_response_message_id {
6297                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6298            }
6299            Ok(())
6300        })
6301    }
6302
6303    async fn handle_update_worktree(
6304        this: ModelHandle<Self>,
6305        envelope: TypedEnvelope<proto::UpdateWorktree>,
6306        _: Arc<Client>,
6307        mut cx: AsyncAppContext,
6308    ) -> Result<()> {
6309        this.update(&mut cx, |this, cx| {
6310            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6311            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6312                worktree.update(cx, |worktree, _| {
6313                    let worktree = worktree.as_remote_mut().unwrap();
6314                    worktree.update_from_remote(envelope.payload);
6315                });
6316            }
6317            Ok(())
6318        })
6319    }
6320
6321    async fn handle_update_worktree_settings(
6322        this: ModelHandle<Self>,
6323        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6324        _: Arc<Client>,
6325        mut cx: AsyncAppContext,
6326    ) -> Result<()> {
6327        this.update(&mut cx, |this, cx| {
6328            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6329            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6330                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6331                    store
6332                        .set_local_settings(
6333                            worktree.id(),
6334                            PathBuf::from(&envelope.payload.path).into(),
6335                            envelope.payload.content.as_ref().map(String::as_str),
6336                            cx,
6337                        )
6338                        .log_err();
6339                });
6340            }
6341            Ok(())
6342        })
6343    }
6344
6345    async fn handle_create_project_entry(
6346        this: ModelHandle<Self>,
6347        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6348        _: Arc<Client>,
6349        mut cx: AsyncAppContext,
6350    ) -> Result<proto::ProjectEntryResponse> {
6351        let worktree = this.update(&mut cx, |this, cx| {
6352            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6353            this.worktree_for_id(worktree_id, cx)
6354                .ok_or_else(|| anyhow!("worktree not found"))
6355        })?;
6356        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6357        let entry = worktree
6358            .update(&mut cx, |worktree, cx| {
6359                let worktree = worktree.as_local_mut().unwrap();
6360                let path = PathBuf::from(envelope.payload.path);
6361                worktree.create_entry(path, envelope.payload.is_directory, cx)
6362            })
6363            .await?;
6364        Ok(proto::ProjectEntryResponse {
6365            entry: Some((&entry).into()),
6366            worktree_scan_id: worktree_scan_id as u64,
6367        })
6368    }
6369
6370    async fn handle_rename_project_entry(
6371        this: ModelHandle<Self>,
6372        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6373        _: Arc<Client>,
6374        mut cx: AsyncAppContext,
6375    ) -> Result<proto::ProjectEntryResponse> {
6376        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6377        let worktree = this.read_with(&cx, |this, cx| {
6378            this.worktree_for_entry(entry_id, cx)
6379                .ok_or_else(|| anyhow!("worktree not found"))
6380        })?;
6381        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6382        let entry = worktree
6383            .update(&mut cx, |worktree, cx| {
6384                let new_path = PathBuf::from(envelope.payload.new_path);
6385                worktree
6386                    .as_local_mut()
6387                    .unwrap()
6388                    .rename_entry(entry_id, new_path, cx)
6389                    .ok_or_else(|| anyhow!("invalid entry"))
6390            })?
6391            .await?;
6392        Ok(proto::ProjectEntryResponse {
6393            entry: Some((&entry).into()),
6394            worktree_scan_id: worktree_scan_id as u64,
6395        })
6396    }
6397
6398    async fn handle_copy_project_entry(
6399        this: ModelHandle<Self>,
6400        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6401        _: Arc<Client>,
6402        mut cx: AsyncAppContext,
6403    ) -> Result<proto::ProjectEntryResponse> {
6404        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6405        let worktree = this.read_with(&cx, |this, cx| {
6406            this.worktree_for_entry(entry_id, cx)
6407                .ok_or_else(|| anyhow!("worktree not found"))
6408        })?;
6409        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6410        let entry = worktree
6411            .update(&mut cx, |worktree, cx| {
6412                let new_path = PathBuf::from(envelope.payload.new_path);
6413                worktree
6414                    .as_local_mut()
6415                    .unwrap()
6416                    .copy_entry(entry_id, new_path, cx)
6417                    .ok_or_else(|| anyhow!("invalid entry"))
6418            })?
6419            .await?;
6420        Ok(proto::ProjectEntryResponse {
6421            entry: Some((&entry).into()),
6422            worktree_scan_id: worktree_scan_id as u64,
6423        })
6424    }
6425
6426    async fn handle_delete_project_entry(
6427        this: ModelHandle<Self>,
6428        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6429        _: Arc<Client>,
6430        mut cx: AsyncAppContext,
6431    ) -> Result<proto::ProjectEntryResponse> {
6432        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6433
6434        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6435
6436        let worktree = this.read_with(&cx, |this, cx| {
6437            this.worktree_for_entry(entry_id, cx)
6438                .ok_or_else(|| anyhow!("worktree not found"))
6439        })?;
6440        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6441        worktree
6442            .update(&mut cx, |worktree, cx| {
6443                worktree
6444                    .as_local_mut()
6445                    .unwrap()
6446                    .delete_entry(entry_id, cx)
6447                    .ok_or_else(|| anyhow!("invalid entry"))
6448            })?
6449            .await?;
6450        Ok(proto::ProjectEntryResponse {
6451            entry: None,
6452            worktree_scan_id: worktree_scan_id as u64,
6453        })
6454    }
6455
6456    async fn handle_expand_project_entry(
6457        this: ModelHandle<Self>,
6458        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6459        _: Arc<Client>,
6460        mut cx: AsyncAppContext,
6461    ) -> Result<proto::ExpandProjectEntryResponse> {
6462        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6463        let worktree = this
6464            .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6465            .ok_or_else(|| anyhow!("invalid request"))?;
6466        worktree
6467            .update(&mut cx, |worktree, cx| {
6468                worktree
6469                    .as_local_mut()
6470                    .unwrap()
6471                    .expand_entry(entry_id, cx)
6472                    .ok_or_else(|| anyhow!("invalid entry"))
6473            })?
6474            .await?;
6475        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6476        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6477    }
6478
6479    async fn handle_update_diagnostic_summary(
6480        this: ModelHandle<Self>,
6481        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6482        _: Arc<Client>,
6483        mut cx: AsyncAppContext,
6484    ) -> Result<()> {
6485        this.update(&mut cx, |this, cx| {
6486            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6487            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6488                if let Some(summary) = envelope.payload.summary {
6489                    let project_path = ProjectPath {
6490                        worktree_id,
6491                        path: Path::new(&summary.path).into(),
6492                    };
6493                    worktree.update(cx, |worktree, _| {
6494                        worktree
6495                            .as_remote_mut()
6496                            .unwrap()
6497                            .update_diagnostic_summary(project_path.path.clone(), &summary);
6498                    });
6499                    cx.emit(Event::DiagnosticsUpdated {
6500                        language_server_id: LanguageServerId(summary.language_server_id as usize),
6501                        path: project_path,
6502                    });
6503                }
6504            }
6505            Ok(())
6506        })
6507    }
6508
6509    async fn handle_start_language_server(
6510        this: ModelHandle<Self>,
6511        envelope: TypedEnvelope<proto::StartLanguageServer>,
6512        _: Arc<Client>,
6513        mut cx: AsyncAppContext,
6514    ) -> Result<()> {
6515        let server = envelope
6516            .payload
6517            .server
6518            .ok_or_else(|| anyhow!("invalid server"))?;
6519        this.update(&mut cx, |this, cx| {
6520            this.language_server_statuses.insert(
6521                LanguageServerId(server.id as usize),
6522                LanguageServerStatus {
6523                    name: server.name,
6524                    pending_work: Default::default(),
6525                    has_pending_diagnostic_updates: false,
6526                    progress_tokens: Default::default(),
6527                },
6528            );
6529            cx.notify();
6530        });
6531        Ok(())
6532    }
6533
6534    async fn handle_update_language_server(
6535        this: ModelHandle<Self>,
6536        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6537        _: Arc<Client>,
6538        mut cx: AsyncAppContext,
6539    ) -> Result<()> {
6540        this.update(&mut cx, |this, cx| {
6541            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6542
6543            match envelope
6544                .payload
6545                .variant
6546                .ok_or_else(|| anyhow!("invalid variant"))?
6547            {
6548                proto::update_language_server::Variant::WorkStart(payload) => {
6549                    this.on_lsp_work_start(
6550                        language_server_id,
6551                        payload.token,
6552                        LanguageServerProgress {
6553                            message: payload.message,
6554                            percentage: payload.percentage.map(|p| p as usize),
6555                            last_update_at: Instant::now(),
6556                        },
6557                        cx,
6558                    );
6559                }
6560
6561                proto::update_language_server::Variant::WorkProgress(payload) => {
6562                    this.on_lsp_work_progress(
6563                        language_server_id,
6564                        payload.token,
6565                        LanguageServerProgress {
6566                            message: payload.message,
6567                            percentage: payload.percentage.map(|p| p as usize),
6568                            last_update_at: Instant::now(),
6569                        },
6570                        cx,
6571                    );
6572                }
6573
6574                proto::update_language_server::Variant::WorkEnd(payload) => {
6575                    this.on_lsp_work_end(language_server_id, payload.token, cx);
6576                }
6577
6578                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
6579                    this.disk_based_diagnostics_started(language_server_id, cx);
6580                }
6581
6582                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
6583                    this.disk_based_diagnostics_finished(language_server_id, cx)
6584                }
6585            }
6586
6587            Ok(())
6588        })
6589    }
6590
6591    async fn handle_update_buffer(
6592        this: ModelHandle<Self>,
6593        envelope: TypedEnvelope<proto::UpdateBuffer>,
6594        _: Arc<Client>,
6595        mut cx: AsyncAppContext,
6596    ) -> Result<proto::Ack> {
6597        this.update(&mut cx, |this, cx| {
6598            let payload = envelope.payload.clone();
6599            let buffer_id = payload.buffer_id;
6600            let ops = payload
6601                .operations
6602                .into_iter()
6603                .map(language::proto::deserialize_operation)
6604                .collect::<Result<Vec<_>, _>>()?;
6605            let is_remote = this.is_remote();
6606            match this.opened_buffers.entry(buffer_id) {
6607                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
6608                    OpenBuffer::Strong(buffer) => {
6609                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
6610                    }
6611                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
6612                    OpenBuffer::Weak(_) => {}
6613                },
6614                hash_map::Entry::Vacant(e) => {
6615                    assert!(
6616                        is_remote,
6617                        "received buffer update from {:?}",
6618                        envelope.original_sender_id
6619                    );
6620                    e.insert(OpenBuffer::Operations(ops));
6621                }
6622            }
6623            Ok(proto::Ack {})
6624        })
6625    }
6626
6627    async fn handle_create_buffer_for_peer(
6628        this: ModelHandle<Self>,
6629        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
6630        _: Arc<Client>,
6631        mut cx: AsyncAppContext,
6632    ) -> Result<()> {
6633        this.update(&mut cx, |this, cx| {
6634            match envelope
6635                .payload
6636                .variant
6637                .ok_or_else(|| anyhow!("missing variant"))?
6638            {
6639                proto::create_buffer_for_peer::Variant::State(mut state) => {
6640                    let mut buffer_file = None;
6641                    if let Some(file) = state.file.take() {
6642                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
6643                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
6644                            anyhow!("no worktree found for id {}", file.worktree_id)
6645                        })?;
6646                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
6647                            as Arc<dyn language::File>);
6648                    }
6649
6650                    let buffer_id = state.id;
6651                    let buffer = cx.add_model(|_| {
6652                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
6653                    });
6654                    this.incomplete_remote_buffers
6655                        .insert(buffer_id, Some(buffer));
6656                }
6657                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
6658                    let buffer = this
6659                        .incomplete_remote_buffers
6660                        .get(&chunk.buffer_id)
6661                        .cloned()
6662                        .flatten()
6663                        .ok_or_else(|| {
6664                            anyhow!(
6665                                "received chunk for buffer {} without initial state",
6666                                chunk.buffer_id
6667                            )
6668                        })?;
6669                    let operations = chunk
6670                        .operations
6671                        .into_iter()
6672                        .map(language::proto::deserialize_operation)
6673                        .collect::<Result<Vec<_>>>()?;
6674                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
6675
6676                    if chunk.is_last {
6677                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
6678                        this.register_buffer(&buffer, cx)?;
6679                    }
6680                }
6681            }
6682
6683            Ok(())
6684        })
6685    }
6686
6687    async fn handle_update_diff_base(
6688        this: ModelHandle<Self>,
6689        envelope: TypedEnvelope<proto::UpdateDiffBase>,
6690        _: Arc<Client>,
6691        mut cx: AsyncAppContext,
6692    ) -> Result<()> {
6693        this.update(&mut cx, |this, cx| {
6694            let buffer_id = envelope.payload.buffer_id;
6695            let diff_base = envelope.payload.diff_base;
6696            if let Some(buffer) = this
6697                .opened_buffers
6698                .get_mut(&buffer_id)
6699                .and_then(|b| b.upgrade(cx))
6700                .or_else(|| {
6701                    this.incomplete_remote_buffers
6702                        .get(&buffer_id)
6703                        .cloned()
6704                        .flatten()
6705                })
6706            {
6707                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
6708            }
6709            Ok(())
6710        })
6711    }
6712
6713    async fn handle_update_buffer_file(
6714        this: ModelHandle<Self>,
6715        envelope: TypedEnvelope<proto::UpdateBufferFile>,
6716        _: Arc<Client>,
6717        mut cx: AsyncAppContext,
6718    ) -> Result<()> {
6719        let buffer_id = envelope.payload.buffer_id;
6720
6721        this.update(&mut cx, |this, cx| {
6722            let payload = envelope.payload.clone();
6723            if let Some(buffer) = this
6724                .opened_buffers
6725                .get(&buffer_id)
6726                .and_then(|b| b.upgrade(cx))
6727                .or_else(|| {
6728                    this.incomplete_remote_buffers
6729                        .get(&buffer_id)
6730                        .cloned()
6731                        .flatten()
6732                })
6733            {
6734                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
6735                let worktree = this
6736                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
6737                    .ok_or_else(|| anyhow!("no such worktree"))?;
6738                let file = File::from_proto(file, worktree, cx)?;
6739                buffer.update(cx, |buffer, cx| {
6740                    buffer.file_updated(Arc::new(file), cx).detach();
6741                });
6742                this.detect_language_for_buffer(&buffer, cx);
6743            }
6744            Ok(())
6745        })
6746    }
6747
6748    async fn handle_save_buffer(
6749        this: ModelHandle<Self>,
6750        envelope: TypedEnvelope<proto::SaveBuffer>,
6751        _: Arc<Client>,
6752        mut cx: AsyncAppContext,
6753    ) -> Result<proto::BufferSaved> {
6754        let buffer_id = envelope.payload.buffer_id;
6755        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
6756            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
6757            let buffer = this
6758                .opened_buffers
6759                .get(&buffer_id)
6760                .and_then(|buffer| buffer.upgrade(cx))
6761                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
6762            anyhow::Ok((project_id, buffer))
6763        })?;
6764        buffer
6765            .update(&mut cx, |buffer, _| {
6766                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
6767            })
6768            .await?;
6769        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
6770
6771        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
6772            .await?;
6773        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
6774            project_id,
6775            buffer_id,
6776            version: serialize_version(buffer.saved_version()),
6777            mtime: Some(buffer.saved_mtime().into()),
6778            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
6779        }))
6780    }
6781
6782    async fn handle_reload_buffers(
6783        this: ModelHandle<Self>,
6784        envelope: TypedEnvelope<proto::ReloadBuffers>,
6785        _: Arc<Client>,
6786        mut cx: AsyncAppContext,
6787    ) -> Result<proto::ReloadBuffersResponse> {
6788        let sender_id = envelope.original_sender_id()?;
6789        let reload = this.update(&mut cx, |this, cx| {
6790            let mut buffers = HashSet::default();
6791            for buffer_id in &envelope.payload.buffer_ids {
6792                buffers.insert(
6793                    this.opened_buffers
6794                        .get(buffer_id)
6795                        .and_then(|buffer| buffer.upgrade(cx))
6796                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6797                );
6798            }
6799            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
6800        })?;
6801
6802        let project_transaction = reload.await?;
6803        let project_transaction = this.update(&mut cx, |this, cx| {
6804            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6805        });
6806        Ok(proto::ReloadBuffersResponse {
6807            transaction: Some(project_transaction),
6808        })
6809    }
6810
6811    async fn handle_synchronize_buffers(
6812        this: ModelHandle<Self>,
6813        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
6814        _: Arc<Client>,
6815        mut cx: AsyncAppContext,
6816    ) -> Result<proto::SynchronizeBuffersResponse> {
6817        let project_id = envelope.payload.project_id;
6818        let mut response = proto::SynchronizeBuffersResponse {
6819            buffers: Default::default(),
6820        };
6821
6822        this.update(&mut cx, |this, cx| {
6823            let Some(guest_id) = envelope.original_sender_id else {
6824                error!("missing original_sender_id on SynchronizeBuffers request");
6825                return;
6826            };
6827
6828            this.shared_buffers.entry(guest_id).or_default().clear();
6829            for buffer in envelope.payload.buffers {
6830                let buffer_id = buffer.id;
6831                let remote_version = language::proto::deserialize_version(&buffer.version);
6832                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6833                    this.shared_buffers
6834                        .entry(guest_id)
6835                        .or_default()
6836                        .insert(buffer_id);
6837
6838                    let buffer = buffer.read(cx);
6839                    response.buffers.push(proto::BufferVersion {
6840                        id: buffer_id,
6841                        version: language::proto::serialize_version(&buffer.version),
6842                    });
6843
6844                    let operations = buffer.serialize_ops(Some(remote_version), cx);
6845                    let client = this.client.clone();
6846                    if let Some(file) = buffer.file() {
6847                        client
6848                            .send(proto::UpdateBufferFile {
6849                                project_id,
6850                                buffer_id: buffer_id as u64,
6851                                file: Some(file.to_proto()),
6852                            })
6853                            .log_err();
6854                    }
6855
6856                    client
6857                        .send(proto::UpdateDiffBase {
6858                            project_id,
6859                            buffer_id: buffer_id as u64,
6860                            diff_base: buffer.diff_base().map(Into::into),
6861                        })
6862                        .log_err();
6863
6864                    client
6865                        .send(proto::BufferReloaded {
6866                            project_id,
6867                            buffer_id,
6868                            version: language::proto::serialize_version(buffer.saved_version()),
6869                            mtime: Some(buffer.saved_mtime().into()),
6870                            fingerprint: language::proto::serialize_fingerprint(
6871                                buffer.saved_version_fingerprint(),
6872                            ),
6873                            line_ending: language::proto::serialize_line_ending(
6874                                buffer.line_ending(),
6875                            ) as i32,
6876                        })
6877                        .log_err();
6878
6879                    cx.background()
6880                        .spawn(
6881                            async move {
6882                                let operations = operations.await;
6883                                for chunk in split_operations(operations) {
6884                                    client
6885                                        .request(proto::UpdateBuffer {
6886                                            project_id,
6887                                            buffer_id,
6888                                            operations: chunk,
6889                                        })
6890                                        .await?;
6891                                }
6892                                anyhow::Ok(())
6893                            }
6894                            .log_err(),
6895                        )
6896                        .detach();
6897                }
6898            }
6899        });
6900
6901        Ok(response)
6902    }
6903
6904    async fn handle_format_buffers(
6905        this: ModelHandle<Self>,
6906        envelope: TypedEnvelope<proto::FormatBuffers>,
6907        _: Arc<Client>,
6908        mut cx: AsyncAppContext,
6909    ) -> Result<proto::FormatBuffersResponse> {
6910        let sender_id = envelope.original_sender_id()?;
6911        let format = this.update(&mut cx, |this, cx| {
6912            let mut buffers = HashSet::default();
6913            for buffer_id in &envelope.payload.buffer_ids {
6914                buffers.insert(
6915                    this.opened_buffers
6916                        .get(buffer_id)
6917                        .and_then(|buffer| buffer.upgrade(cx))
6918                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
6919                );
6920            }
6921            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
6922            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
6923        })?;
6924
6925        let project_transaction = format.await?;
6926        let project_transaction = this.update(&mut cx, |this, cx| {
6927            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6928        });
6929        Ok(proto::FormatBuffersResponse {
6930            transaction: Some(project_transaction),
6931        })
6932    }
6933
6934    async fn handle_apply_additional_edits_for_completion(
6935        this: ModelHandle<Self>,
6936        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
6937        _: Arc<Client>,
6938        mut cx: AsyncAppContext,
6939    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
6940        let (buffer, completion) = this.update(&mut cx, |this, cx| {
6941            let buffer = this
6942                .opened_buffers
6943                .get(&envelope.payload.buffer_id)
6944                .and_then(|buffer| buffer.upgrade(cx))
6945                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6946            let language = buffer.read(cx).language();
6947            let completion = language::proto::deserialize_completion(
6948                envelope
6949                    .payload
6950                    .completion
6951                    .ok_or_else(|| anyhow!("invalid completion"))?,
6952                language.cloned(),
6953            );
6954            Ok::<_, anyhow::Error>((buffer, completion))
6955        })?;
6956
6957        let completion = completion.await?;
6958
6959        let apply_additional_edits = this.update(&mut cx, |this, cx| {
6960            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
6961        });
6962
6963        Ok(proto::ApplyCompletionAdditionalEditsResponse {
6964            transaction: apply_additional_edits
6965                .await?
6966                .as_ref()
6967                .map(language::proto::serialize_transaction),
6968        })
6969    }
6970
6971    async fn handle_apply_code_action(
6972        this: ModelHandle<Self>,
6973        envelope: TypedEnvelope<proto::ApplyCodeAction>,
6974        _: Arc<Client>,
6975        mut cx: AsyncAppContext,
6976    ) -> Result<proto::ApplyCodeActionResponse> {
6977        let sender_id = envelope.original_sender_id()?;
6978        let action = language::proto::deserialize_code_action(
6979            envelope
6980                .payload
6981                .action
6982                .ok_or_else(|| anyhow!("invalid action"))?,
6983        )?;
6984        let apply_code_action = this.update(&mut cx, |this, cx| {
6985            let buffer = this
6986                .opened_buffers
6987                .get(&envelope.payload.buffer_id)
6988                .and_then(|buffer| buffer.upgrade(cx))
6989                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
6990            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
6991        })?;
6992
6993        let project_transaction = apply_code_action.await?;
6994        let project_transaction = this.update(&mut cx, |this, cx| {
6995            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
6996        });
6997        Ok(proto::ApplyCodeActionResponse {
6998            transaction: Some(project_transaction),
6999        })
7000    }
7001
7002    async fn handle_on_type_formatting(
7003        this: ModelHandle<Self>,
7004        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7005        _: Arc<Client>,
7006        mut cx: AsyncAppContext,
7007    ) -> Result<proto::OnTypeFormattingResponse> {
7008        let on_type_formatting = this.update(&mut cx, |this, cx| {
7009            let buffer = this
7010                .opened_buffers
7011                .get(&envelope.payload.buffer_id)
7012                .and_then(|buffer| buffer.upgrade(cx))
7013                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7014            let position = envelope
7015                .payload
7016                .position
7017                .and_then(deserialize_anchor)
7018                .ok_or_else(|| anyhow!("invalid position"))?;
7019            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7020                buffer,
7021                position,
7022                envelope.payload.trigger.clone(),
7023                cx,
7024            ))
7025        })?;
7026
7027        let transaction = on_type_formatting
7028            .await?
7029            .as_ref()
7030            .map(language::proto::serialize_transaction);
7031        Ok(proto::OnTypeFormattingResponse { transaction })
7032    }
7033
7034    async fn handle_inlay_hints(
7035        this: ModelHandle<Self>,
7036        envelope: TypedEnvelope<proto::InlayHints>,
7037        _: Arc<Client>,
7038        mut cx: AsyncAppContext,
7039    ) -> Result<proto::InlayHintsResponse> {
7040        let sender_id = envelope.original_sender_id()?;
7041        let buffer = this.update(&mut cx, |this, cx| {
7042            this.opened_buffers
7043                .get(&envelope.payload.buffer_id)
7044                .and_then(|buffer| buffer.upgrade(cx))
7045                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7046        })?;
7047        let buffer_version = deserialize_version(&envelope.payload.version);
7048
7049        buffer
7050            .update(&mut cx, |buffer, _| {
7051                buffer.wait_for_version(buffer_version.clone())
7052            })
7053            .await
7054            .with_context(|| {
7055                format!(
7056                    "waiting for version {:?} for buffer {}",
7057                    buffer_version,
7058                    buffer.id()
7059                )
7060            })?;
7061
7062        let start = envelope
7063            .payload
7064            .start
7065            .and_then(deserialize_anchor)
7066            .context("missing range start")?;
7067        let end = envelope
7068            .payload
7069            .end
7070            .and_then(deserialize_anchor)
7071            .context("missing range end")?;
7072        let buffer_hints = this
7073            .update(&mut cx, |project, cx| {
7074                project.inlay_hints(buffer, start..end, cx)
7075            })
7076            .await
7077            .context("inlay hints fetch")?;
7078
7079        Ok(this.update(&mut cx, |project, cx| {
7080            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7081        }))
7082    }
7083
7084    async fn handle_resolve_inlay_hint(
7085        this: ModelHandle<Self>,
7086        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7087        _: Arc<Client>,
7088        mut cx: AsyncAppContext,
7089    ) -> Result<proto::ResolveInlayHintResponse> {
7090        let proto_hint = envelope
7091            .payload
7092            .hint
7093            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7094        let hint = InlayHints::proto_to_project_hint(proto_hint, &this, &mut cx)
7095            .await
7096            .context("resolved proto inlay hint conversion")?;
7097        let buffer = this.update(&mut cx, |this, cx| {
7098            this.opened_buffers
7099                .get(&envelope.payload.buffer_id)
7100                .and_then(|buffer| buffer.upgrade(cx))
7101                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7102        })?;
7103        let response_hint = this
7104            .update(&mut cx, |project, cx| {
7105                project.resolve_inlay_hint(
7106                    hint,
7107                    buffer,
7108                    LanguageServerId(envelope.payload.language_server_id as usize),
7109                    cx,
7110                )
7111            })
7112            .await
7113            .context("inlay hints fetch")?;
7114        let resolved_hint = cx.read(|cx| InlayHints::project_to_proto_hint(response_hint, cx));
7115
7116        Ok(proto::ResolveInlayHintResponse {
7117            hint: Some(resolved_hint),
7118        })
7119    }
7120
7121    async fn handle_refresh_inlay_hints(
7122        this: ModelHandle<Self>,
7123        _: TypedEnvelope<proto::RefreshInlayHints>,
7124        _: Arc<Client>,
7125        mut cx: AsyncAppContext,
7126    ) -> Result<proto::Ack> {
7127        this.update(&mut cx, |_, cx| {
7128            cx.emit(Event::RefreshInlayHints);
7129        });
7130        Ok(proto::Ack {})
7131    }
7132
7133    async fn handle_lsp_command<T: LspCommand>(
7134        this: ModelHandle<Self>,
7135        envelope: TypedEnvelope<T::ProtoRequest>,
7136        _: Arc<Client>,
7137        mut cx: AsyncAppContext,
7138    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7139    where
7140        <T::LspRequest as lsp::request::Request>::Result: Send,
7141    {
7142        let sender_id = envelope.original_sender_id()?;
7143        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7144        let buffer_handle = this.read_with(&cx, |this, _| {
7145            this.opened_buffers
7146                .get(&buffer_id)
7147                .and_then(|buffer| buffer.upgrade(&cx))
7148                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7149        })?;
7150        let request = T::from_proto(
7151            envelope.payload,
7152            this.clone(),
7153            buffer_handle.clone(),
7154            cx.clone(),
7155        )
7156        .await?;
7157        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
7158        let response = this
7159            .update(&mut cx, |this, cx| {
7160                this.request_lsp(buffer_handle, request, cx)
7161            })
7162            .await?;
7163        this.update(&mut cx, |this, cx| {
7164            Ok(T::response_to_proto(
7165                response,
7166                this,
7167                sender_id,
7168                &buffer_version,
7169                cx,
7170            ))
7171        })
7172    }
7173
7174    async fn handle_get_project_symbols(
7175        this: ModelHandle<Self>,
7176        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7177        _: Arc<Client>,
7178        mut cx: AsyncAppContext,
7179    ) -> Result<proto::GetProjectSymbolsResponse> {
7180        let symbols = this
7181            .update(&mut cx, |this, cx| {
7182                this.symbols(&envelope.payload.query, cx)
7183            })
7184            .await?;
7185
7186        Ok(proto::GetProjectSymbolsResponse {
7187            symbols: symbols.iter().map(serialize_symbol).collect(),
7188        })
7189    }
7190
7191    async fn handle_search_project(
7192        this: ModelHandle<Self>,
7193        envelope: TypedEnvelope<proto::SearchProject>,
7194        _: Arc<Client>,
7195        mut cx: AsyncAppContext,
7196    ) -> Result<proto::SearchProjectResponse> {
7197        let peer_id = envelope.original_sender_id()?;
7198        let query = SearchQuery::from_proto(envelope.payload)?;
7199        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx));
7200
7201        cx.spawn(|mut cx| async move {
7202            let mut locations = Vec::new();
7203            while let Some((buffer, ranges)) = result.next().await {
7204                for range in ranges {
7205                    let start = serialize_anchor(&range.start);
7206                    let end = serialize_anchor(&range.end);
7207                    let buffer_id = this.update(&mut cx, |this, cx| {
7208                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7209                    });
7210                    locations.push(proto::Location {
7211                        buffer_id,
7212                        start: Some(start),
7213                        end: Some(end),
7214                    });
7215                }
7216            }
7217            Ok(proto::SearchProjectResponse { locations })
7218        })
7219        .await
7220    }
7221
7222    async fn handle_open_buffer_for_symbol(
7223        this: ModelHandle<Self>,
7224        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7225        _: Arc<Client>,
7226        mut cx: AsyncAppContext,
7227    ) -> Result<proto::OpenBufferForSymbolResponse> {
7228        let peer_id = envelope.original_sender_id()?;
7229        let symbol = envelope
7230            .payload
7231            .symbol
7232            .ok_or_else(|| anyhow!("invalid symbol"))?;
7233        let symbol = this
7234            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
7235            .await?;
7236        let symbol = this.read_with(&cx, |this, _| {
7237            let signature = this.symbol_signature(&symbol.path);
7238            if signature == symbol.signature {
7239                Ok(symbol)
7240            } else {
7241                Err(anyhow!("invalid symbol signature"))
7242            }
7243        })?;
7244        let buffer = this
7245            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
7246            .await?;
7247
7248        Ok(proto::OpenBufferForSymbolResponse {
7249            buffer_id: this.update(&mut cx, |this, cx| {
7250                this.create_buffer_for_peer(&buffer, peer_id, cx)
7251            }),
7252        })
7253    }
7254
7255    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7256        let mut hasher = Sha256::new();
7257        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7258        hasher.update(project_path.path.to_string_lossy().as_bytes());
7259        hasher.update(self.nonce.to_be_bytes());
7260        hasher.finalize().as_slice().try_into().unwrap()
7261    }
7262
7263    async fn handle_open_buffer_by_id(
7264        this: ModelHandle<Self>,
7265        envelope: TypedEnvelope<proto::OpenBufferById>,
7266        _: Arc<Client>,
7267        mut cx: AsyncAppContext,
7268    ) -> Result<proto::OpenBufferResponse> {
7269        let peer_id = envelope.original_sender_id()?;
7270        let buffer = this
7271            .update(&mut cx, |this, cx| {
7272                this.open_buffer_by_id(envelope.payload.id, cx)
7273            })
7274            .await?;
7275        this.update(&mut cx, |this, cx| {
7276            Ok(proto::OpenBufferResponse {
7277                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7278            })
7279        })
7280    }
7281
7282    async fn handle_open_buffer_by_path(
7283        this: ModelHandle<Self>,
7284        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7285        _: Arc<Client>,
7286        mut cx: AsyncAppContext,
7287    ) -> Result<proto::OpenBufferResponse> {
7288        let peer_id = envelope.original_sender_id()?;
7289        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7290        let open_buffer = this.update(&mut cx, |this, cx| {
7291            this.open_buffer(
7292                ProjectPath {
7293                    worktree_id,
7294                    path: PathBuf::from(envelope.payload.path).into(),
7295                },
7296                cx,
7297            )
7298        });
7299
7300        let buffer = open_buffer.await?;
7301        this.update(&mut cx, |this, cx| {
7302            Ok(proto::OpenBufferResponse {
7303                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7304            })
7305        })
7306    }
7307
7308    fn serialize_project_transaction_for_peer(
7309        &mut self,
7310        project_transaction: ProjectTransaction,
7311        peer_id: proto::PeerId,
7312        cx: &mut AppContext,
7313    ) -> proto::ProjectTransaction {
7314        let mut serialized_transaction = proto::ProjectTransaction {
7315            buffer_ids: Default::default(),
7316            transactions: Default::default(),
7317        };
7318        for (buffer, transaction) in project_transaction.0 {
7319            serialized_transaction
7320                .buffer_ids
7321                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7322            serialized_transaction
7323                .transactions
7324                .push(language::proto::serialize_transaction(&transaction));
7325        }
7326        serialized_transaction
7327    }
7328
7329    fn deserialize_project_transaction(
7330        &mut self,
7331        message: proto::ProjectTransaction,
7332        push_to_history: bool,
7333        cx: &mut ModelContext<Self>,
7334    ) -> Task<Result<ProjectTransaction>> {
7335        cx.spawn(|this, mut cx| async move {
7336            let mut project_transaction = ProjectTransaction::default();
7337            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7338            {
7339                let buffer = this
7340                    .update(&mut cx, |this, cx| {
7341                        this.wait_for_remote_buffer(buffer_id, cx)
7342                    })
7343                    .await?;
7344                let transaction = language::proto::deserialize_transaction(transaction)?;
7345                project_transaction.0.insert(buffer, transaction);
7346            }
7347
7348            for (buffer, transaction) in &project_transaction.0 {
7349                buffer
7350                    .update(&mut cx, |buffer, _| {
7351                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7352                    })
7353                    .await?;
7354
7355                if push_to_history {
7356                    buffer.update(&mut cx, |buffer, _| {
7357                        buffer.push_transaction(transaction.clone(), Instant::now());
7358                    });
7359                }
7360            }
7361
7362            Ok(project_transaction)
7363        })
7364    }
7365
7366    fn create_buffer_for_peer(
7367        &mut self,
7368        buffer: &ModelHandle<Buffer>,
7369        peer_id: proto::PeerId,
7370        cx: &mut AppContext,
7371    ) -> u64 {
7372        let buffer_id = buffer.read(cx).remote_id();
7373        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7374            updates_tx
7375                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7376                .ok();
7377        }
7378        buffer_id
7379    }
7380
7381    fn wait_for_remote_buffer(
7382        &mut self,
7383        id: u64,
7384        cx: &mut ModelContext<Self>,
7385    ) -> Task<Result<ModelHandle<Buffer>>> {
7386        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7387
7388        cx.spawn_weak(|this, mut cx| async move {
7389            let buffer = loop {
7390                let Some(this) = this.upgrade(&cx) else {
7391                    return Err(anyhow!("project dropped"));
7392                };
7393
7394                let buffer = this.read_with(&cx, |this, cx| {
7395                    this.opened_buffers
7396                        .get(&id)
7397                        .and_then(|buffer| buffer.upgrade(cx))
7398                });
7399
7400                if let Some(buffer) = buffer {
7401                    break buffer;
7402                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7403                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7404                }
7405
7406                this.update(&mut cx, |this, _| {
7407                    this.incomplete_remote_buffers.entry(id).or_default();
7408                });
7409                drop(this);
7410
7411                opened_buffer_rx
7412                    .next()
7413                    .await
7414                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7415            };
7416
7417            Ok(buffer)
7418        })
7419    }
7420
7421    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7422        let project_id = match self.client_state.as_ref() {
7423            Some(ProjectClientState::Remote {
7424                sharing_has_stopped,
7425                remote_id,
7426                ..
7427            }) => {
7428                if *sharing_has_stopped {
7429                    return Task::ready(Err(anyhow!(
7430                        "can't synchronize remote buffers on a readonly project"
7431                    )));
7432                } else {
7433                    *remote_id
7434                }
7435            }
7436            Some(ProjectClientState::Local { .. }) | None => {
7437                return Task::ready(Err(anyhow!(
7438                    "can't synchronize remote buffers on a local project"
7439                )))
7440            }
7441        };
7442
7443        let client = self.client.clone();
7444        cx.spawn(|this, cx| async move {
7445            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7446                let buffers = this
7447                    .opened_buffers
7448                    .iter()
7449                    .filter_map(|(id, buffer)| {
7450                        let buffer = buffer.upgrade(cx)?;
7451                        Some(proto::BufferVersion {
7452                            id: *id,
7453                            version: language::proto::serialize_version(&buffer.read(cx).version),
7454                        })
7455                    })
7456                    .collect();
7457                let incomplete_buffer_ids = this
7458                    .incomplete_remote_buffers
7459                    .keys()
7460                    .copied()
7461                    .collect::<Vec<_>>();
7462
7463                (buffers, incomplete_buffer_ids)
7464            });
7465            let response = client
7466                .request(proto::SynchronizeBuffers {
7467                    project_id,
7468                    buffers,
7469                })
7470                .await?;
7471
7472            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7473                let client = client.clone();
7474                let buffer_id = buffer.id;
7475                let remote_version = language::proto::deserialize_version(&buffer.version);
7476                this.read_with(&cx, |this, cx| {
7477                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7478                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7479                        cx.background().spawn(async move {
7480                            let operations = operations.await;
7481                            for chunk in split_operations(operations) {
7482                                client
7483                                    .request(proto::UpdateBuffer {
7484                                        project_id,
7485                                        buffer_id,
7486                                        operations: chunk,
7487                                    })
7488                                    .await?;
7489                            }
7490                            anyhow::Ok(())
7491                        })
7492                    } else {
7493                        Task::ready(Ok(()))
7494                    }
7495                })
7496            });
7497
7498            // Any incomplete buffers have open requests waiting. Request that the host sends
7499            // creates these buffers for us again to unblock any waiting futures.
7500            for id in incomplete_buffer_ids {
7501                cx.background()
7502                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
7503                    .detach();
7504            }
7505
7506            futures::future::join_all(send_updates_for_buffers)
7507                .await
7508                .into_iter()
7509                .collect()
7510        })
7511    }
7512
7513    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7514        self.worktrees(cx)
7515            .map(|worktree| {
7516                let worktree = worktree.read(cx);
7517                proto::WorktreeMetadata {
7518                    id: worktree.id().to_proto(),
7519                    root_name: worktree.root_name().into(),
7520                    visible: worktree.is_visible(),
7521                    abs_path: worktree.abs_path().to_string_lossy().into(),
7522                }
7523            })
7524            .collect()
7525    }
7526
7527    fn set_worktrees_from_proto(
7528        &mut self,
7529        worktrees: Vec<proto::WorktreeMetadata>,
7530        cx: &mut ModelContext<Project>,
7531    ) -> Result<()> {
7532        let replica_id = self.replica_id();
7533        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
7534
7535        let mut old_worktrees_by_id = self
7536            .worktrees
7537            .drain(..)
7538            .filter_map(|worktree| {
7539                let worktree = worktree.upgrade(cx)?;
7540                Some((worktree.read(cx).id(), worktree))
7541            })
7542            .collect::<HashMap<_, _>>();
7543
7544        for worktree in worktrees {
7545            if let Some(old_worktree) =
7546                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
7547            {
7548                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
7549            } else {
7550                let worktree =
7551                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
7552                let _ = self.add_worktree(&worktree, cx);
7553            }
7554        }
7555
7556        self.metadata_changed(cx);
7557        for id in old_worktrees_by_id.keys() {
7558            cx.emit(Event::WorktreeRemoved(*id));
7559        }
7560
7561        Ok(())
7562    }
7563
7564    fn set_collaborators_from_proto(
7565        &mut self,
7566        messages: Vec<proto::Collaborator>,
7567        cx: &mut ModelContext<Self>,
7568    ) -> Result<()> {
7569        let mut collaborators = HashMap::default();
7570        for message in messages {
7571            let collaborator = Collaborator::from_proto(message)?;
7572            collaborators.insert(collaborator.peer_id, collaborator);
7573        }
7574        for old_peer_id in self.collaborators.keys() {
7575            if !collaborators.contains_key(old_peer_id) {
7576                cx.emit(Event::CollaboratorLeft(*old_peer_id));
7577            }
7578        }
7579        self.collaborators = collaborators;
7580        Ok(())
7581    }
7582
7583    fn deserialize_symbol(
7584        &self,
7585        serialized_symbol: proto::Symbol,
7586    ) -> impl Future<Output = Result<Symbol>> {
7587        let languages = self.languages.clone();
7588        async move {
7589            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
7590            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
7591            let start = serialized_symbol
7592                .start
7593                .ok_or_else(|| anyhow!("invalid start"))?;
7594            let end = serialized_symbol
7595                .end
7596                .ok_or_else(|| anyhow!("invalid end"))?;
7597            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
7598            let path = ProjectPath {
7599                worktree_id,
7600                path: PathBuf::from(serialized_symbol.path).into(),
7601            };
7602            let language = languages
7603                .language_for_file(&path.path, None)
7604                .await
7605                .log_err();
7606            Ok(Symbol {
7607                language_server_name: LanguageServerName(
7608                    serialized_symbol.language_server_name.into(),
7609                ),
7610                source_worktree_id,
7611                path,
7612                label: {
7613                    match language {
7614                        Some(language) => {
7615                            language
7616                                .label_for_symbol(&serialized_symbol.name, kind)
7617                                .await
7618                        }
7619                        None => None,
7620                    }
7621                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
7622                },
7623
7624                name: serialized_symbol.name,
7625                range: Unclipped(PointUtf16::new(start.row, start.column))
7626                    ..Unclipped(PointUtf16::new(end.row, end.column)),
7627                kind,
7628                signature: serialized_symbol
7629                    .signature
7630                    .try_into()
7631                    .map_err(|_| anyhow!("invalid signature"))?,
7632            })
7633        }
7634    }
7635
7636    async fn handle_buffer_saved(
7637        this: ModelHandle<Self>,
7638        envelope: TypedEnvelope<proto::BufferSaved>,
7639        _: Arc<Client>,
7640        mut cx: AsyncAppContext,
7641    ) -> Result<()> {
7642        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
7643        let version = deserialize_version(&envelope.payload.version);
7644        let mtime = envelope
7645            .payload
7646            .mtime
7647            .ok_or_else(|| anyhow!("missing mtime"))?
7648            .into();
7649
7650        this.update(&mut cx, |this, cx| {
7651            let buffer = this
7652                .opened_buffers
7653                .get(&envelope.payload.buffer_id)
7654                .and_then(|buffer| buffer.upgrade(cx))
7655                .or_else(|| {
7656                    this.incomplete_remote_buffers
7657                        .get(&envelope.payload.buffer_id)
7658                        .and_then(|b| b.clone())
7659                });
7660            if let Some(buffer) = buffer {
7661                buffer.update(cx, |buffer, cx| {
7662                    buffer.did_save(version, fingerprint, mtime, cx);
7663                });
7664            }
7665            Ok(())
7666        })
7667    }
7668
7669    async fn handle_buffer_reloaded(
7670        this: ModelHandle<Self>,
7671        envelope: TypedEnvelope<proto::BufferReloaded>,
7672        _: Arc<Client>,
7673        mut cx: AsyncAppContext,
7674    ) -> Result<()> {
7675        let payload = envelope.payload;
7676        let version = deserialize_version(&payload.version);
7677        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
7678        let line_ending = deserialize_line_ending(
7679            proto::LineEnding::from_i32(payload.line_ending)
7680                .ok_or_else(|| anyhow!("missing line ending"))?,
7681        );
7682        let mtime = payload
7683            .mtime
7684            .ok_or_else(|| anyhow!("missing mtime"))?
7685            .into();
7686        this.update(&mut cx, |this, cx| {
7687            let buffer = this
7688                .opened_buffers
7689                .get(&payload.buffer_id)
7690                .and_then(|buffer| buffer.upgrade(cx))
7691                .or_else(|| {
7692                    this.incomplete_remote_buffers
7693                        .get(&payload.buffer_id)
7694                        .cloned()
7695                        .flatten()
7696                });
7697            if let Some(buffer) = buffer {
7698                buffer.update(cx, |buffer, cx| {
7699                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
7700                });
7701            }
7702            Ok(())
7703        })
7704    }
7705
7706    #[allow(clippy::type_complexity)]
7707    fn edits_from_lsp(
7708        &mut self,
7709        buffer: &ModelHandle<Buffer>,
7710        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
7711        server_id: LanguageServerId,
7712        version: Option<i32>,
7713        cx: &mut ModelContext<Self>,
7714    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
7715        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
7716        cx.background().spawn(async move {
7717            let snapshot = snapshot?;
7718            let mut lsp_edits = lsp_edits
7719                .into_iter()
7720                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
7721                .collect::<Vec<_>>();
7722            lsp_edits.sort_by_key(|(range, _)| range.start);
7723
7724            let mut lsp_edits = lsp_edits.into_iter().peekable();
7725            let mut edits = Vec::new();
7726            while let Some((range, mut new_text)) = lsp_edits.next() {
7727                // Clip invalid ranges provided by the language server.
7728                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
7729                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
7730
7731                // Combine any LSP edits that are adjacent.
7732                //
7733                // Also, combine LSP edits that are separated from each other by only
7734                // a newline. This is important because for some code actions,
7735                // Rust-analyzer rewrites the entire buffer via a series of edits that
7736                // are separated by unchanged newline characters.
7737                //
7738                // In order for the diffing logic below to work properly, any edits that
7739                // cancel each other out must be combined into one.
7740                while let Some((next_range, next_text)) = lsp_edits.peek() {
7741                    if next_range.start.0 > range.end {
7742                        if next_range.start.0.row > range.end.row + 1
7743                            || next_range.start.0.column > 0
7744                            || snapshot.clip_point_utf16(
7745                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
7746                                Bias::Left,
7747                            ) > range.end
7748                        {
7749                            break;
7750                        }
7751                        new_text.push('\n');
7752                    }
7753                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
7754                    new_text.push_str(next_text);
7755                    lsp_edits.next();
7756                }
7757
7758                // For multiline edits, perform a diff of the old and new text so that
7759                // we can identify the changes more precisely, preserving the locations
7760                // of any anchors positioned in the unchanged regions.
7761                if range.end.row > range.start.row {
7762                    let mut offset = range.start.to_offset(&snapshot);
7763                    let old_text = snapshot.text_for_range(range).collect::<String>();
7764
7765                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
7766                    let mut moved_since_edit = true;
7767                    for change in diff.iter_all_changes() {
7768                        let tag = change.tag();
7769                        let value = change.value();
7770                        match tag {
7771                            ChangeTag::Equal => {
7772                                offset += value.len();
7773                                moved_since_edit = true;
7774                            }
7775                            ChangeTag::Delete => {
7776                                let start = snapshot.anchor_after(offset);
7777                                let end = snapshot.anchor_before(offset + value.len());
7778                                if moved_since_edit {
7779                                    edits.push((start..end, String::new()));
7780                                } else {
7781                                    edits.last_mut().unwrap().0.end = end;
7782                                }
7783                                offset += value.len();
7784                                moved_since_edit = false;
7785                            }
7786                            ChangeTag::Insert => {
7787                                if moved_since_edit {
7788                                    let anchor = snapshot.anchor_after(offset);
7789                                    edits.push((anchor..anchor, value.to_string()));
7790                                } else {
7791                                    edits.last_mut().unwrap().1.push_str(value);
7792                                }
7793                                moved_since_edit = false;
7794                            }
7795                        }
7796                    }
7797                } else if range.end == range.start {
7798                    let anchor = snapshot.anchor_after(range.start);
7799                    edits.push((anchor..anchor, new_text));
7800                } else {
7801                    let edit_start = snapshot.anchor_after(range.start);
7802                    let edit_end = snapshot.anchor_before(range.end);
7803                    edits.push((edit_start..edit_end, new_text));
7804                }
7805            }
7806
7807            Ok(edits)
7808        })
7809    }
7810
7811    fn buffer_snapshot_for_lsp_version(
7812        &mut self,
7813        buffer: &ModelHandle<Buffer>,
7814        server_id: LanguageServerId,
7815        version: Option<i32>,
7816        cx: &AppContext,
7817    ) -> Result<TextBufferSnapshot> {
7818        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
7819
7820        if let Some(version) = version {
7821            let buffer_id = buffer.read(cx).remote_id();
7822            let snapshots = self
7823                .buffer_snapshots
7824                .get_mut(&buffer_id)
7825                .and_then(|m| m.get_mut(&server_id))
7826                .ok_or_else(|| {
7827                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
7828                })?;
7829
7830            let found_snapshot = snapshots
7831                .binary_search_by_key(&version, |e| e.version)
7832                .map(|ix| snapshots[ix].snapshot.clone())
7833                .map_err(|_| {
7834                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
7835                })?;
7836
7837            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
7838            Ok(found_snapshot)
7839        } else {
7840            Ok((buffer.read(cx)).text_snapshot())
7841        }
7842    }
7843
7844    pub fn language_servers(
7845        &self,
7846    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
7847        self.language_server_ids
7848            .iter()
7849            .map(|((worktree_id, server_name), server_id)| {
7850                (*server_id, server_name.clone(), *worktree_id)
7851            })
7852    }
7853
7854    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
7855        if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
7856            Some(server.clone())
7857        } else {
7858            None
7859        }
7860    }
7861
7862    pub fn language_servers_for_buffer(
7863        &self,
7864        buffer: &Buffer,
7865        cx: &AppContext,
7866    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7867        self.language_server_ids_for_buffer(buffer, cx)
7868            .into_iter()
7869            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
7870                LanguageServerState::Running {
7871                    adapter, server, ..
7872                } => Some((adapter, server)),
7873                _ => None,
7874            })
7875    }
7876
7877    fn primary_language_servers_for_buffer(
7878        &self,
7879        buffer: &Buffer,
7880        cx: &AppContext,
7881    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7882        self.language_servers_for_buffer(buffer, cx).next()
7883    }
7884
7885    fn language_server_for_buffer(
7886        &self,
7887        buffer: &Buffer,
7888        server_id: LanguageServerId,
7889        cx: &AppContext,
7890    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
7891        self.language_servers_for_buffer(buffer, cx)
7892            .find(|(_, s)| s.server_id() == server_id)
7893    }
7894
7895    fn language_server_ids_for_buffer(
7896        &self,
7897        buffer: &Buffer,
7898        cx: &AppContext,
7899    ) -> Vec<LanguageServerId> {
7900        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
7901            let worktree_id = file.worktree_id(cx);
7902            language
7903                .lsp_adapters()
7904                .iter()
7905                .flat_map(|adapter| {
7906                    let key = (worktree_id, adapter.name.clone());
7907                    self.language_server_ids.get(&key).copied()
7908                })
7909                .collect()
7910        } else {
7911            Vec::new()
7912        }
7913    }
7914}
7915
7916fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
7917    let mut literal_end = 0;
7918    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
7919        if part.contains(&['*', '?', '{', '}']) {
7920            break;
7921        } else {
7922            if i > 0 {
7923                // Acount for separator prior to this part
7924                literal_end += path::MAIN_SEPARATOR.len_utf8();
7925            }
7926            literal_end += part.len();
7927        }
7928    }
7929    &glob[..literal_end]
7930}
7931
7932impl WorktreeHandle {
7933    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
7934        match self {
7935            WorktreeHandle::Strong(handle) => Some(handle.clone()),
7936            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
7937        }
7938    }
7939
7940    pub fn handle_id(&self) -> usize {
7941        match self {
7942            WorktreeHandle::Strong(handle) => handle.id(),
7943            WorktreeHandle::Weak(handle) => handle.id(),
7944        }
7945    }
7946}
7947
7948impl OpenBuffer {
7949    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
7950        match self {
7951            OpenBuffer::Strong(handle) => Some(handle.clone()),
7952            OpenBuffer::Weak(handle) => handle.upgrade(cx),
7953            OpenBuffer::Operations(_) => None,
7954        }
7955    }
7956}
7957
7958pub struct PathMatchCandidateSet {
7959    pub snapshot: Snapshot,
7960    pub include_ignored: bool,
7961    pub include_root_name: bool,
7962}
7963
7964impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
7965    type Candidates = PathMatchCandidateSetIter<'a>;
7966
7967    fn id(&self) -> usize {
7968        self.snapshot.id().to_usize()
7969    }
7970
7971    fn len(&self) -> usize {
7972        if self.include_ignored {
7973            self.snapshot.file_count()
7974        } else {
7975            self.snapshot.visible_file_count()
7976        }
7977    }
7978
7979    fn prefix(&self) -> Arc<str> {
7980        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
7981            self.snapshot.root_name().into()
7982        } else if self.include_root_name {
7983            format!("{}/", self.snapshot.root_name()).into()
7984        } else {
7985            "".into()
7986        }
7987    }
7988
7989    fn candidates(&'a self, start: usize) -> Self::Candidates {
7990        PathMatchCandidateSetIter {
7991            traversal: self.snapshot.files(self.include_ignored, start),
7992        }
7993    }
7994}
7995
7996pub struct PathMatchCandidateSetIter<'a> {
7997    traversal: Traversal<'a>,
7998}
7999
8000impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8001    type Item = fuzzy::PathMatchCandidate<'a>;
8002
8003    fn next(&mut self) -> Option<Self::Item> {
8004        self.traversal.next().map(|entry| {
8005            if let EntryKind::File(char_bag) = entry.kind {
8006                fuzzy::PathMatchCandidate {
8007                    path: &entry.path,
8008                    char_bag,
8009                }
8010            } else {
8011                unreachable!()
8012            }
8013        })
8014    }
8015}
8016
8017impl Entity for Project {
8018    type Event = Event;
8019
8020    fn release(&mut self, cx: &mut gpui::AppContext) {
8021        match &self.client_state {
8022            Some(ProjectClientState::Local { .. }) => {
8023                let _ = self.unshare_internal(cx);
8024            }
8025            Some(ProjectClientState::Remote { remote_id, .. }) => {
8026                let _ = self.client.send(proto::LeaveProject {
8027                    project_id: *remote_id,
8028                });
8029                self.disconnected_from_host_internal(cx);
8030            }
8031            _ => {}
8032        }
8033    }
8034
8035    fn app_will_quit(
8036        &mut self,
8037        _: &mut AppContext,
8038    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
8039        let shutdown_futures = self
8040            .language_servers
8041            .drain()
8042            .map(|(_, server_state)| async {
8043                use LanguageServerState::*;
8044                match server_state {
8045                    Running { server, .. } => server.shutdown()?.await,
8046                    Starting(task) => task.await?.shutdown()?.await,
8047                }
8048            })
8049            .collect::<Vec<_>>();
8050
8051        Some(
8052            async move {
8053                futures::future::join_all(shutdown_futures).await;
8054            }
8055            .boxed(),
8056        )
8057    }
8058}
8059
8060impl Collaborator {
8061    fn from_proto(message: proto::Collaborator) -> Result<Self> {
8062        Ok(Self {
8063            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
8064            replica_id: message.replica_id as ReplicaId,
8065            user_id: message.user_id as UserId,
8066        })
8067    }
8068}
8069
8070impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8071    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8072        Self {
8073            worktree_id,
8074            path: path.as_ref().into(),
8075        }
8076    }
8077}
8078
8079impl ProjectLspAdapterDelegate {
8080    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8081        Arc::new(Self {
8082            project: cx.handle(),
8083            http_client: project.client.http_client(),
8084        })
8085    }
8086}
8087
8088impl LspAdapterDelegate for ProjectLspAdapterDelegate {
8089    fn show_notification(&self, message: &str, cx: &mut AppContext) {
8090        self.project
8091            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
8092    }
8093
8094    fn http_client(&self) -> Arc<dyn HttpClient> {
8095        self.http_client.clone()
8096    }
8097}
8098
8099fn split_operations(
8100    mut operations: Vec<proto::Operation>,
8101) -> impl Iterator<Item = Vec<proto::Operation>> {
8102    #[cfg(any(test, feature = "test-support"))]
8103    const CHUNK_SIZE: usize = 5;
8104
8105    #[cfg(not(any(test, feature = "test-support")))]
8106    const CHUNK_SIZE: usize = 100;
8107
8108    let mut done = false;
8109    std::iter::from_fn(move || {
8110        if done {
8111            return None;
8112        }
8113
8114        let operations = operations
8115            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
8116            .collect::<Vec<_>>();
8117        if operations.is_empty() {
8118            done = true;
8119        }
8120        Some(operations)
8121    })
8122}
8123
8124fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
8125    proto::Symbol {
8126        language_server_name: symbol.language_server_name.0.to_string(),
8127        source_worktree_id: symbol.source_worktree_id.to_proto(),
8128        worktree_id: symbol.path.worktree_id.to_proto(),
8129        path: symbol.path.path.to_string_lossy().to_string(),
8130        name: symbol.name.clone(),
8131        kind: unsafe { mem::transmute(symbol.kind) },
8132        start: Some(proto::PointUtf16 {
8133            row: symbol.range.start.0.row,
8134            column: symbol.range.start.0.column,
8135        }),
8136        end: Some(proto::PointUtf16 {
8137            row: symbol.range.end.0.row,
8138            column: symbol.range.end.0.column,
8139        }),
8140        signature: symbol.signature.to_vec(),
8141    }
8142}
8143
8144fn relativize_path(base: &Path, path: &Path) -> PathBuf {
8145    let mut path_components = path.components();
8146    let mut base_components = base.components();
8147    let mut components: Vec<Component> = Vec::new();
8148    loop {
8149        match (path_components.next(), base_components.next()) {
8150            (None, None) => break,
8151            (Some(a), None) => {
8152                components.push(a);
8153                components.extend(path_components.by_ref());
8154                break;
8155            }
8156            (None, _) => components.push(Component::ParentDir),
8157            (Some(a), Some(b)) if components.is_empty() && a == b => (),
8158            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
8159            (Some(a), Some(_)) => {
8160                components.push(Component::ParentDir);
8161                for _ in base_components {
8162                    components.push(Component::ParentDir);
8163                }
8164                components.push(a);
8165                components.extend(path_components.by_ref());
8166                break;
8167            }
8168        }
8169    }
8170    components.iter().map(|c| c.as_os_str()).collect()
8171}
8172
8173impl Item for Buffer {
8174    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
8175        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
8176    }
8177
8178    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
8179        File::from_dyn(self.file()).map(|file| ProjectPath {
8180            worktree_id: file.worktree_id(cx),
8181            path: file.path().clone(),
8182        })
8183    }
8184}
8185
8186async fn wait_for_loading_buffer(
8187    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
8188) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
8189    loop {
8190        if let Some(result) = receiver.borrow().as_ref() {
8191            match result {
8192                Ok(buffer) => return Ok(buffer.to_owned()),
8193                Err(e) => return Err(e.to_owned()),
8194            }
8195        }
8196        receiver.next().await;
8197    }
8198}