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