project.rs

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