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                                                    let matches = if query
4233                                                        .file_matches(Some(&entry.path))
4234                                                    {
4235                                                        abs_path.clear();
4236                                                        abs_path.push(&snapshot.abs_path());
4237                                                        abs_path.push(&entry.path);
4238                                                        if let Some(file) =
4239                                                            fs.open_sync(&abs_path).await.log_err()
4240                                                        {
4241                                                            query.detect(file).unwrap_or(false)
4242                                                        } else {
4243                                                            false
4244                                                        }
4245                                                    } else {
4246                                                        false
4247                                                    };
4248
4249                                                    if matches {
4250                                                        let project_path =
4251                                                            (snapshot.id(), entry.path.clone());
4252                                                        if matching_paths_tx
4253                                                            .send(project_path)
4254                                                            .await
4255                                                            .is_err()
4256                                                        {
4257                                                            break;
4258                                                        }
4259                                                    }
4260                                                }
4261
4262                                                snapshot_start_ix = snapshot_end_ix;
4263                                            }
4264                                        }
4265                                    });
4266                                }
4267                            })
4268                            .await;
4269                    }
4270                })
4271                .detach();
4272
4273            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4274            let open_buffers = self
4275                .opened_buffers
4276                .values()
4277                .filter_map(|b| b.upgrade(cx))
4278                .collect::<HashSet<_>>();
4279            cx.spawn(|this, cx| async move {
4280                for buffer in &open_buffers {
4281                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4282                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4283                }
4284
4285                let open_buffers = Rc::new(RefCell::new(open_buffers));
4286                while let Some(project_path) = matching_paths_rx.next().await {
4287                    if buffers_tx.is_closed() {
4288                        break;
4289                    }
4290
4291                    let this = this.clone();
4292                    let open_buffers = open_buffers.clone();
4293                    let buffers_tx = buffers_tx.clone();
4294                    cx.spawn(|mut cx| async move {
4295                        if let Some(buffer) = this
4296                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4297                            .await
4298                            .log_err()
4299                        {
4300                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4301                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4302                                buffers_tx.send((buffer, snapshot)).await?;
4303                            }
4304                        }
4305
4306                        Ok::<_, anyhow::Error>(())
4307                    })
4308                    .detach();
4309                }
4310
4311                Ok::<_, anyhow::Error>(())
4312            })
4313            .detach_and_log_err(cx);
4314
4315            let background = cx.background().clone();
4316            cx.background().spawn(async move {
4317                let query = &query;
4318                let mut matched_buffers = Vec::new();
4319                for _ in 0..workers {
4320                    matched_buffers.push(HashMap::default());
4321                }
4322                background
4323                    .scoped(|scope| {
4324                        for worker_matched_buffers in matched_buffers.iter_mut() {
4325                            let mut buffers_rx = buffers_rx.clone();
4326                            scope.spawn(async move {
4327                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4328                                    let buffer_matches = if query.file_matches(
4329                                        snapshot.file().map(|file| file.path().as_ref()),
4330                                    ) {
4331                                        query
4332                                            .search(snapshot.as_rope())
4333                                            .await
4334                                            .iter()
4335                                            .map(|range| {
4336                                                snapshot.anchor_before(range.start)
4337                                                    ..snapshot.anchor_after(range.end)
4338                                            })
4339                                            .collect()
4340                                    } else {
4341                                        Vec::new()
4342                                    };
4343                                    if !buffer_matches.is_empty() {
4344                                        worker_matched_buffers
4345                                            .insert(buffer.clone(), buffer_matches);
4346                                    }
4347                                }
4348                            });
4349                        }
4350                    })
4351                    .await;
4352                Ok(matched_buffers.into_iter().flatten().collect())
4353            })
4354        } else if let Some(project_id) = self.remote_id() {
4355            let request = self.client.request(query.to_proto(project_id));
4356            cx.spawn(|this, mut cx| async move {
4357                let response = request.await?;
4358                let mut result = HashMap::default();
4359                for location in response.locations {
4360                    let target_buffer = this
4361                        .update(&mut cx, |this, cx| {
4362                            this.wait_for_remote_buffer(location.buffer_id, cx)
4363                        })
4364                        .await?;
4365                    let start = location
4366                        .start
4367                        .and_then(deserialize_anchor)
4368                        .ok_or_else(|| anyhow!("missing target start"))?;
4369                    let end = location
4370                        .end
4371                        .and_then(deserialize_anchor)
4372                        .ok_or_else(|| anyhow!("missing target end"))?;
4373                    result
4374                        .entry(target_buffer)
4375                        .or_insert(Vec::new())
4376                        .push(start..end)
4377                }
4378                Ok(result)
4379            })
4380        } else {
4381            Task::ready(Ok(Default::default()))
4382        }
4383    }
4384
4385    // TODO: Wire this up to allow selecting a server?
4386    fn request_lsp<R: LspCommand>(
4387        &self,
4388        buffer_handle: ModelHandle<Buffer>,
4389        request: R,
4390        cx: &mut ModelContext<Self>,
4391    ) -> Task<Result<R::Response>>
4392    where
4393        <R::LspRequest as lsp::request::Request>::Result: Send,
4394    {
4395        let buffer = buffer_handle.read(cx);
4396        if self.is_local() {
4397            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4398            if let Some((file, language_server)) = file.zip(
4399                self.primary_language_servers_for_buffer(buffer, cx)
4400                    .map(|(_, server)| server.clone()),
4401            ) {
4402                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
4403                return cx.spawn(|this, cx| async move {
4404                    if !request.check_capabilities(language_server.capabilities()) {
4405                        return Ok(Default::default());
4406                    }
4407
4408                    let response = language_server
4409                        .request::<R::LspRequest>(lsp_params)
4410                        .await
4411                        .context("lsp request failed")?;
4412                    request
4413                        .response_from_lsp(
4414                            response,
4415                            this,
4416                            buffer_handle,
4417                            language_server.server_id(),
4418                            cx,
4419                        )
4420                        .await
4421                });
4422            }
4423        } else if let Some(project_id) = self.remote_id() {
4424            let rpc = self.client.clone();
4425            let message = request.to_proto(project_id, buffer);
4426            return cx.spawn_weak(|this, cx| async move {
4427                // Ensure the project is still alive by the time the task
4428                // is scheduled.
4429                this.upgrade(&cx)
4430                    .ok_or_else(|| anyhow!("project dropped"))?;
4431
4432                let response = rpc.request(message).await?;
4433
4434                let this = this
4435                    .upgrade(&cx)
4436                    .ok_or_else(|| anyhow!("project dropped"))?;
4437                if this.read_with(&cx, |this, _| this.is_read_only()) {
4438                    Err(anyhow!("disconnected before completing request"))
4439                } else {
4440                    request
4441                        .response_from_proto(response, this, buffer_handle, cx)
4442                        .await
4443                }
4444            });
4445        }
4446        Task::ready(Ok(Default::default()))
4447    }
4448
4449    pub fn find_or_create_local_worktree(
4450        &mut self,
4451        abs_path: impl AsRef<Path>,
4452        visible: bool,
4453        cx: &mut ModelContext<Self>,
4454    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4455        let abs_path = abs_path.as_ref();
4456        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4457            Task::ready(Ok((tree, relative_path)))
4458        } else {
4459            let worktree = self.create_local_worktree(abs_path, visible, cx);
4460            cx.foreground()
4461                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4462        }
4463    }
4464
4465    pub fn find_local_worktree(
4466        &self,
4467        abs_path: &Path,
4468        cx: &AppContext,
4469    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4470        for tree in &self.worktrees {
4471            if let Some(tree) = tree.upgrade(cx) {
4472                if let Some(relative_path) = tree
4473                    .read(cx)
4474                    .as_local()
4475                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4476                {
4477                    return Some((tree.clone(), relative_path.into()));
4478                }
4479            }
4480        }
4481        None
4482    }
4483
4484    pub fn is_shared(&self) -> bool {
4485        match &self.client_state {
4486            Some(ProjectClientState::Local { .. }) => true,
4487            _ => false,
4488        }
4489    }
4490
4491    fn create_local_worktree(
4492        &mut self,
4493        abs_path: impl AsRef<Path>,
4494        visible: bool,
4495        cx: &mut ModelContext<Self>,
4496    ) -> Task<Result<ModelHandle<Worktree>>> {
4497        let fs = self.fs.clone();
4498        let client = self.client.clone();
4499        let next_entry_id = self.next_entry_id.clone();
4500        let path: Arc<Path> = abs_path.as_ref().into();
4501        let task = self
4502            .loading_local_worktrees
4503            .entry(path.clone())
4504            .or_insert_with(|| {
4505                cx.spawn(|project, mut cx| {
4506                    async move {
4507                        let worktree = Worktree::local(
4508                            client.clone(),
4509                            path.clone(),
4510                            visible,
4511                            fs,
4512                            next_entry_id,
4513                            &mut cx,
4514                        )
4515                        .await;
4516
4517                        project.update(&mut cx, |project, _| {
4518                            project.loading_local_worktrees.remove(&path);
4519                        });
4520
4521                        let worktree = worktree?;
4522                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
4523                        Ok(worktree)
4524                    }
4525                    .map_err(Arc::new)
4526                })
4527                .shared()
4528            })
4529            .clone();
4530        cx.foreground().spawn(async move {
4531            match task.await {
4532                Ok(worktree) => Ok(worktree),
4533                Err(err) => Err(anyhow!("{}", err)),
4534            }
4535        })
4536    }
4537
4538    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
4539        self.worktrees.retain(|worktree| {
4540            if let Some(worktree) = worktree.upgrade(cx) {
4541                let id = worktree.read(cx).id();
4542                if id == id_to_remove {
4543                    cx.emit(Event::WorktreeRemoved(id));
4544                    false
4545                } else {
4546                    true
4547                }
4548            } else {
4549                false
4550            }
4551        });
4552        self.metadata_changed(cx);
4553    }
4554
4555    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
4556        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4557        if worktree.read(cx).is_local() {
4558            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4559                worktree::Event::UpdatedEntries(changes) => {
4560                    this.update_local_worktree_buffers(&worktree, &changes, cx);
4561                    this.update_local_worktree_language_servers(&worktree, changes, cx);
4562                }
4563                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4564                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4565                }
4566            })
4567            .detach();
4568        }
4569
4570        let push_strong_handle = {
4571            let worktree = worktree.read(cx);
4572            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4573        };
4574        if push_strong_handle {
4575            self.worktrees
4576                .push(WorktreeHandle::Strong(worktree.clone()));
4577        } else {
4578            self.worktrees
4579                .push(WorktreeHandle::Weak(worktree.downgrade()));
4580        }
4581
4582        cx.observe_release(worktree, |this, worktree, cx| {
4583            let _ = this.remove_worktree(worktree.id(), cx);
4584        })
4585        .detach();
4586
4587        cx.emit(Event::WorktreeAdded);
4588        self.metadata_changed(cx);
4589    }
4590
4591    fn update_local_worktree_buffers(
4592        &mut self,
4593        worktree_handle: &ModelHandle<Worktree>,
4594        changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4595        cx: &mut ModelContext<Self>,
4596    ) {
4597        let snapshot = worktree_handle.read(cx).snapshot();
4598
4599        let mut renamed_buffers = Vec::new();
4600        for (path, entry_id) in changes.keys() {
4601            let worktree_id = worktree_handle.read(cx).id();
4602            let project_path = ProjectPath {
4603                worktree_id,
4604                path: path.clone(),
4605            };
4606
4607            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
4608                Some(&buffer_id) => buffer_id,
4609                None => match self.local_buffer_ids_by_path.get(&project_path) {
4610                    Some(&buffer_id) => buffer_id,
4611                    None => continue,
4612                },
4613            };
4614
4615            let open_buffer = self.opened_buffers.get(&buffer_id);
4616            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
4617                buffer
4618            } else {
4619                self.opened_buffers.remove(&buffer_id);
4620                self.local_buffer_ids_by_path.remove(&project_path);
4621                self.local_buffer_ids_by_entry_id.remove(entry_id);
4622                continue;
4623            };
4624
4625            buffer.update(cx, |buffer, cx| {
4626                if let Some(old_file) = File::from_dyn(buffer.file()) {
4627                    if old_file.worktree != *worktree_handle {
4628                        return;
4629                    }
4630
4631                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
4632                        File {
4633                            is_local: true,
4634                            entry_id: entry.id,
4635                            mtime: entry.mtime,
4636                            path: entry.path.clone(),
4637                            worktree: worktree_handle.clone(),
4638                            is_deleted: false,
4639                        }
4640                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
4641                        File {
4642                            is_local: true,
4643                            entry_id: entry.id,
4644                            mtime: entry.mtime,
4645                            path: entry.path.clone(),
4646                            worktree: worktree_handle.clone(),
4647                            is_deleted: false,
4648                        }
4649                    } else {
4650                        File {
4651                            is_local: true,
4652                            entry_id: old_file.entry_id,
4653                            path: old_file.path().clone(),
4654                            mtime: old_file.mtime(),
4655                            worktree: worktree_handle.clone(),
4656                            is_deleted: true,
4657                        }
4658                    };
4659
4660                    let old_path = old_file.abs_path(cx);
4661                    if new_file.abs_path(cx) != old_path {
4662                        renamed_buffers.push((cx.handle(), old_file.clone()));
4663                        self.local_buffer_ids_by_path.remove(&project_path);
4664                        self.local_buffer_ids_by_path.insert(
4665                            ProjectPath {
4666                                worktree_id,
4667                                path: path.clone(),
4668                            },
4669                            buffer_id,
4670                        );
4671                    }
4672
4673                    if new_file.entry_id != *entry_id {
4674                        self.local_buffer_ids_by_entry_id.remove(entry_id);
4675                        self.local_buffer_ids_by_entry_id
4676                            .insert(new_file.entry_id, buffer_id);
4677                    }
4678
4679                    if new_file != *old_file {
4680                        if let Some(project_id) = self.remote_id() {
4681                            self.client
4682                                .send(proto::UpdateBufferFile {
4683                                    project_id,
4684                                    buffer_id: buffer_id as u64,
4685                                    file: Some(new_file.to_proto()),
4686                                })
4687                                .log_err();
4688                        }
4689
4690                        buffer.file_updated(Arc::new(new_file), cx).detach();
4691                    }
4692                }
4693            });
4694        }
4695
4696        for (buffer, old_file) in renamed_buffers {
4697            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
4698            self.detect_language_for_buffer(&buffer, cx);
4699            self.register_buffer_with_language_servers(&buffer, cx);
4700        }
4701    }
4702
4703    fn update_local_worktree_language_servers(
4704        &mut self,
4705        worktree_handle: &ModelHandle<Worktree>,
4706        changes: &HashMap<(Arc<Path>, ProjectEntryId), PathChange>,
4707        cx: &mut ModelContext<Self>,
4708    ) {
4709        let worktree_id = worktree_handle.read(cx).id();
4710        let abs_path = worktree_handle.read(cx).abs_path();
4711        for ((server_worktree_id, _), server_id) in &self.language_server_ids {
4712            if *server_worktree_id == worktree_id {
4713                if let Some(server) = self.language_servers.get(server_id) {
4714                    if let LanguageServerState::Running {
4715                        server,
4716                        watched_paths,
4717                        ..
4718                    } = server
4719                    {
4720                        let params = lsp::DidChangeWatchedFilesParams {
4721                            changes: changes
4722                                .iter()
4723                                .filter_map(|((path, _), change)| {
4724                                    let path = abs_path.join(path);
4725                                    if watched_paths.matches(&path) {
4726                                        Some(lsp::FileEvent {
4727                                            uri: lsp::Url::from_file_path(path).unwrap(),
4728                                            typ: match change {
4729                                                PathChange::Added => lsp::FileChangeType::CREATED,
4730                                                PathChange::Removed => lsp::FileChangeType::DELETED,
4731                                                PathChange::Updated
4732                                                | PathChange::AddedOrUpdated => {
4733                                                    lsp::FileChangeType::CHANGED
4734                                                }
4735                                            },
4736                                        })
4737                                    } else {
4738                                        None
4739                                    }
4740                                })
4741                                .collect(),
4742                        };
4743
4744                        if !params.changes.is_empty() {
4745                            server
4746                                .notify::<lsp::notification::DidChangeWatchedFiles>(params)
4747                                .log_err();
4748                        }
4749                    }
4750                }
4751            }
4752        }
4753    }
4754
4755    fn update_local_worktree_buffers_git_repos(
4756        &mut self,
4757        worktree_handle: ModelHandle<Worktree>,
4758        repos: &HashMap<Arc<Path>, LocalRepositoryEntry>,
4759        cx: &mut ModelContext<Self>,
4760    ) {
4761        debug_assert!(worktree_handle.read(cx).is_local());
4762
4763        for (_, buffer) in &self.opened_buffers {
4764            if let Some(buffer) = buffer.upgrade(cx) {
4765                let file = match File::from_dyn(buffer.read(cx).file()) {
4766                    Some(file) => file,
4767                    None => continue,
4768                };
4769                if file.worktree != worktree_handle {
4770                    continue;
4771                }
4772
4773                let path = file.path().clone();
4774
4775                let worktree = worktree_handle.read(cx);
4776
4777                let (work_directory, repo) = match repos
4778                    .iter()
4779                    .find(|(work_directory, _)| path.starts_with(work_directory))
4780                {
4781                    Some(repo) => repo.clone(),
4782                    None => return,
4783                };
4784
4785                let relative_repo = match path.strip_prefix(work_directory).log_err() {
4786                    Some(relative_repo) => relative_repo.to_owned(),
4787                    None => return,
4788                };
4789
4790                drop(worktree);
4791
4792                let remote_id = self.remote_id();
4793                let client = self.client.clone();
4794                let git_ptr = repo.repo_ptr.clone();
4795                let diff_base_task = cx
4796                    .background()
4797                    .spawn(async move { git_ptr.lock().load_index_text(&relative_repo) });
4798
4799                cx.spawn(|_, mut cx| async move {
4800                    let diff_base = diff_base_task.await;
4801
4802                    let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4803                        buffer.set_diff_base(diff_base.clone(), cx);
4804                        buffer.remote_id()
4805                    });
4806
4807                    if let Some(project_id) = remote_id {
4808                        client
4809                            .send(proto::UpdateDiffBase {
4810                                project_id,
4811                                buffer_id: buffer_id as u64,
4812                                diff_base,
4813                            })
4814                            .log_err();
4815                    }
4816                })
4817                .detach();
4818            }
4819        }
4820    }
4821
4822    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4823        let new_active_entry = entry.and_then(|project_path| {
4824            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4825            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4826            Some(entry.id)
4827        });
4828        if new_active_entry != self.active_entry {
4829            self.active_entry = new_active_entry;
4830            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4831        }
4832    }
4833
4834    pub fn language_servers_running_disk_based_diagnostics(
4835        &self,
4836    ) -> impl Iterator<Item = LanguageServerId> + '_ {
4837        self.language_server_statuses
4838            .iter()
4839            .filter_map(|(id, status)| {
4840                if status.has_pending_diagnostic_updates {
4841                    Some(*id)
4842                } else {
4843                    None
4844                }
4845            })
4846    }
4847
4848    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4849        let mut summary = DiagnosticSummary::default();
4850        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
4851            summary.error_count += path_summary.error_count;
4852            summary.warning_count += path_summary.warning_count;
4853        }
4854        summary
4855    }
4856
4857    pub fn diagnostic_summaries<'a>(
4858        &'a self,
4859        cx: &'a AppContext,
4860    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4861        self.visible_worktrees(cx).flat_map(move |worktree| {
4862            let worktree = worktree.read(cx);
4863            let worktree_id = worktree.id();
4864            worktree
4865                .diagnostic_summaries()
4866                .map(move |(path, server_id, summary)| {
4867                    (ProjectPath { worktree_id, path }, server_id, summary)
4868                })
4869        })
4870    }
4871
4872    pub fn disk_based_diagnostics_started(
4873        &mut self,
4874        language_server_id: LanguageServerId,
4875        cx: &mut ModelContext<Self>,
4876    ) {
4877        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4878    }
4879
4880    pub fn disk_based_diagnostics_finished(
4881        &mut self,
4882        language_server_id: LanguageServerId,
4883        cx: &mut ModelContext<Self>,
4884    ) {
4885        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4886    }
4887
4888    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4889        self.active_entry
4890    }
4891
4892    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4893        self.worktree_for_id(path.worktree_id, cx)?
4894            .read(cx)
4895            .entry_for_path(&path.path)
4896            .cloned()
4897    }
4898
4899    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4900        let worktree = self.worktree_for_entry(entry_id, cx)?;
4901        let worktree = worktree.read(cx);
4902        let worktree_id = worktree.id();
4903        let path = worktree.entry_for_id(entry_id)?.path.clone();
4904        Some(ProjectPath { worktree_id, path })
4905    }
4906
4907    // RPC message handlers
4908
4909    async fn handle_unshare_project(
4910        this: ModelHandle<Self>,
4911        _: TypedEnvelope<proto::UnshareProject>,
4912        _: Arc<Client>,
4913        mut cx: AsyncAppContext,
4914    ) -> Result<()> {
4915        this.update(&mut cx, |this, cx| {
4916            if this.is_local() {
4917                this.unshare(cx)?;
4918            } else {
4919                this.disconnected_from_host(cx);
4920            }
4921            Ok(())
4922        })
4923    }
4924
4925    async fn handle_add_collaborator(
4926        this: ModelHandle<Self>,
4927        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4928        _: Arc<Client>,
4929        mut cx: AsyncAppContext,
4930    ) -> Result<()> {
4931        let collaborator = envelope
4932            .payload
4933            .collaborator
4934            .take()
4935            .ok_or_else(|| anyhow!("empty collaborator"))?;
4936
4937        let collaborator = Collaborator::from_proto(collaborator)?;
4938        this.update(&mut cx, |this, cx| {
4939            this.shared_buffers.remove(&collaborator.peer_id);
4940            this.collaborators
4941                .insert(collaborator.peer_id, collaborator);
4942            cx.notify();
4943        });
4944
4945        Ok(())
4946    }
4947
4948    async fn handle_update_project_collaborator(
4949        this: ModelHandle<Self>,
4950        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4951        _: Arc<Client>,
4952        mut cx: AsyncAppContext,
4953    ) -> Result<()> {
4954        let old_peer_id = envelope
4955            .payload
4956            .old_peer_id
4957            .ok_or_else(|| anyhow!("missing old peer id"))?;
4958        let new_peer_id = envelope
4959            .payload
4960            .new_peer_id
4961            .ok_or_else(|| anyhow!("missing new peer id"))?;
4962        this.update(&mut cx, |this, cx| {
4963            let collaborator = this
4964                .collaborators
4965                .remove(&old_peer_id)
4966                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4967            let is_host = collaborator.replica_id == 0;
4968            this.collaborators.insert(new_peer_id, collaborator);
4969
4970            let buffers = this.shared_buffers.remove(&old_peer_id);
4971            log::info!(
4972                "peer {} became {}. moving buffers {:?}",
4973                old_peer_id,
4974                new_peer_id,
4975                &buffers
4976            );
4977            if let Some(buffers) = buffers {
4978                this.shared_buffers.insert(new_peer_id, buffers);
4979            }
4980
4981            if is_host {
4982                this.opened_buffers
4983                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
4984                this.buffer_ordered_messages_tx
4985                    .unbounded_send(BufferOrderedMessage::Resync)
4986                    .unwrap();
4987            }
4988
4989            cx.emit(Event::CollaboratorUpdated {
4990                old_peer_id,
4991                new_peer_id,
4992            });
4993            cx.notify();
4994            Ok(())
4995        })
4996    }
4997
4998    async fn handle_remove_collaborator(
4999        this: ModelHandle<Self>,
5000        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5001        _: Arc<Client>,
5002        mut cx: AsyncAppContext,
5003    ) -> Result<()> {
5004        this.update(&mut cx, |this, cx| {
5005            let peer_id = envelope
5006                .payload
5007                .peer_id
5008                .ok_or_else(|| anyhow!("invalid peer id"))?;
5009            let replica_id = this
5010                .collaborators
5011                .remove(&peer_id)
5012                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
5013                .replica_id;
5014            for buffer in this.opened_buffers.values() {
5015                if let Some(buffer) = buffer.upgrade(cx) {
5016                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5017                }
5018            }
5019            this.shared_buffers.remove(&peer_id);
5020
5021            cx.emit(Event::CollaboratorLeft(peer_id));
5022            cx.notify();
5023            Ok(())
5024        })
5025    }
5026
5027    async fn handle_update_project(
5028        this: ModelHandle<Self>,
5029        envelope: TypedEnvelope<proto::UpdateProject>,
5030        _: Arc<Client>,
5031        mut cx: AsyncAppContext,
5032    ) -> Result<()> {
5033        this.update(&mut cx, |this, cx| {
5034            // Don't handle messages that were sent before the response to us joining the project
5035            if envelope.message_id > this.join_project_response_message_id {
5036                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5037            }
5038            Ok(())
5039        })
5040    }
5041
5042    async fn handle_update_worktree(
5043        this: ModelHandle<Self>,
5044        envelope: TypedEnvelope<proto::UpdateWorktree>,
5045        _: Arc<Client>,
5046        mut cx: AsyncAppContext,
5047    ) -> Result<()> {
5048        this.update(&mut cx, |this, cx| {
5049            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5050            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5051                worktree.update(cx, |worktree, _| {
5052                    let worktree = worktree.as_remote_mut().unwrap();
5053                    worktree.update_from_remote(envelope.payload);
5054                });
5055            }
5056            Ok(())
5057        })
5058    }
5059
5060    async fn handle_create_project_entry(
5061        this: ModelHandle<Self>,
5062        envelope: TypedEnvelope<proto::CreateProjectEntry>,
5063        _: Arc<Client>,
5064        mut cx: AsyncAppContext,
5065    ) -> Result<proto::ProjectEntryResponse> {
5066        let worktree = this.update(&mut cx, |this, cx| {
5067            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5068            this.worktree_for_id(worktree_id, cx)
5069                .ok_or_else(|| anyhow!("worktree not found"))
5070        })?;
5071        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5072        let entry = worktree
5073            .update(&mut cx, |worktree, cx| {
5074                let worktree = worktree.as_local_mut().unwrap();
5075                let path = PathBuf::from(envelope.payload.path);
5076                worktree.create_entry(path, envelope.payload.is_directory, cx)
5077            })
5078            .await?;
5079        Ok(proto::ProjectEntryResponse {
5080            entry: Some((&entry).into()),
5081            worktree_scan_id: worktree_scan_id as u64,
5082        })
5083    }
5084
5085    async fn handle_rename_project_entry(
5086        this: ModelHandle<Self>,
5087        envelope: TypedEnvelope<proto::RenameProjectEntry>,
5088        _: Arc<Client>,
5089        mut cx: AsyncAppContext,
5090    ) -> Result<proto::ProjectEntryResponse> {
5091        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5092        let worktree = this.read_with(&cx, |this, cx| {
5093            this.worktree_for_entry(entry_id, cx)
5094                .ok_or_else(|| anyhow!("worktree not found"))
5095        })?;
5096        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5097        let entry = worktree
5098            .update(&mut cx, |worktree, cx| {
5099                let new_path = PathBuf::from(envelope.payload.new_path);
5100                worktree
5101                    .as_local_mut()
5102                    .unwrap()
5103                    .rename_entry(entry_id, new_path, cx)
5104                    .ok_or_else(|| anyhow!("invalid entry"))
5105            })?
5106            .await?;
5107        Ok(proto::ProjectEntryResponse {
5108            entry: Some((&entry).into()),
5109            worktree_scan_id: worktree_scan_id as u64,
5110        })
5111    }
5112
5113    async fn handle_copy_project_entry(
5114        this: ModelHandle<Self>,
5115        envelope: TypedEnvelope<proto::CopyProjectEntry>,
5116        _: Arc<Client>,
5117        mut cx: AsyncAppContext,
5118    ) -> Result<proto::ProjectEntryResponse> {
5119        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5120        let worktree = this.read_with(&cx, |this, cx| {
5121            this.worktree_for_entry(entry_id, cx)
5122                .ok_or_else(|| anyhow!("worktree not found"))
5123        })?;
5124        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5125        let entry = worktree
5126            .update(&mut cx, |worktree, cx| {
5127                let new_path = PathBuf::from(envelope.payload.new_path);
5128                worktree
5129                    .as_local_mut()
5130                    .unwrap()
5131                    .copy_entry(entry_id, new_path, cx)
5132                    .ok_or_else(|| anyhow!("invalid entry"))
5133            })?
5134            .await?;
5135        Ok(proto::ProjectEntryResponse {
5136            entry: Some((&entry).into()),
5137            worktree_scan_id: worktree_scan_id as u64,
5138        })
5139    }
5140
5141    async fn handle_delete_project_entry(
5142        this: ModelHandle<Self>,
5143        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
5144        _: Arc<Client>,
5145        mut cx: AsyncAppContext,
5146    ) -> Result<proto::ProjectEntryResponse> {
5147        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
5148        let worktree = this.read_with(&cx, |this, cx| {
5149            this.worktree_for_entry(entry_id, cx)
5150                .ok_or_else(|| anyhow!("worktree not found"))
5151        })?;
5152        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
5153        worktree
5154            .update(&mut cx, |worktree, cx| {
5155                worktree
5156                    .as_local_mut()
5157                    .unwrap()
5158                    .delete_entry(entry_id, cx)
5159                    .ok_or_else(|| anyhow!("invalid entry"))
5160            })?
5161            .await?;
5162        Ok(proto::ProjectEntryResponse {
5163            entry: None,
5164            worktree_scan_id: worktree_scan_id as u64,
5165        })
5166    }
5167
5168    async fn handle_update_diagnostic_summary(
5169        this: ModelHandle<Self>,
5170        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
5171        _: Arc<Client>,
5172        mut cx: AsyncAppContext,
5173    ) -> Result<()> {
5174        this.update(&mut cx, |this, cx| {
5175            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5176            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
5177                if let Some(summary) = envelope.payload.summary {
5178                    let project_path = ProjectPath {
5179                        worktree_id,
5180                        path: Path::new(&summary.path).into(),
5181                    };
5182                    worktree.update(cx, |worktree, _| {
5183                        worktree
5184                            .as_remote_mut()
5185                            .unwrap()
5186                            .update_diagnostic_summary(project_path.path.clone(), &summary);
5187                    });
5188                    cx.emit(Event::DiagnosticsUpdated {
5189                        language_server_id: LanguageServerId(summary.language_server_id as usize),
5190                        path: project_path,
5191                    });
5192                }
5193            }
5194            Ok(())
5195        })
5196    }
5197
5198    async fn handle_start_language_server(
5199        this: ModelHandle<Self>,
5200        envelope: TypedEnvelope<proto::StartLanguageServer>,
5201        _: Arc<Client>,
5202        mut cx: AsyncAppContext,
5203    ) -> Result<()> {
5204        let server = envelope
5205            .payload
5206            .server
5207            .ok_or_else(|| anyhow!("invalid server"))?;
5208        this.update(&mut cx, |this, cx| {
5209            this.language_server_statuses.insert(
5210                LanguageServerId(server.id as usize),
5211                LanguageServerStatus {
5212                    name: server.name,
5213                    pending_work: Default::default(),
5214                    has_pending_diagnostic_updates: false,
5215                    progress_tokens: Default::default(),
5216                },
5217            );
5218            cx.notify();
5219        });
5220        Ok(())
5221    }
5222
5223    async fn handle_update_language_server(
5224        this: ModelHandle<Self>,
5225        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
5226        _: Arc<Client>,
5227        mut cx: AsyncAppContext,
5228    ) -> Result<()> {
5229        this.update(&mut cx, |this, cx| {
5230            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
5231
5232            match envelope
5233                .payload
5234                .variant
5235                .ok_or_else(|| anyhow!("invalid variant"))?
5236            {
5237                proto::update_language_server::Variant::WorkStart(payload) => {
5238                    this.on_lsp_work_start(
5239                        language_server_id,
5240                        payload.token,
5241                        LanguageServerProgress {
5242                            message: payload.message,
5243                            percentage: payload.percentage.map(|p| p as usize),
5244                            last_update_at: Instant::now(),
5245                        },
5246                        cx,
5247                    );
5248                }
5249
5250                proto::update_language_server::Variant::WorkProgress(payload) => {
5251                    this.on_lsp_work_progress(
5252                        language_server_id,
5253                        payload.token,
5254                        LanguageServerProgress {
5255                            message: payload.message,
5256                            percentage: payload.percentage.map(|p| p as usize),
5257                            last_update_at: Instant::now(),
5258                        },
5259                        cx,
5260                    );
5261                }
5262
5263                proto::update_language_server::Variant::WorkEnd(payload) => {
5264                    this.on_lsp_work_end(language_server_id, payload.token, cx);
5265                }
5266
5267                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
5268                    this.disk_based_diagnostics_started(language_server_id, cx);
5269                }
5270
5271                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
5272                    this.disk_based_diagnostics_finished(language_server_id, cx)
5273                }
5274            }
5275
5276            Ok(())
5277        })
5278    }
5279
5280    async fn handle_update_buffer(
5281        this: ModelHandle<Self>,
5282        envelope: TypedEnvelope<proto::UpdateBuffer>,
5283        _: Arc<Client>,
5284        mut cx: AsyncAppContext,
5285    ) -> Result<proto::Ack> {
5286        this.update(&mut cx, |this, cx| {
5287            let payload = envelope.payload.clone();
5288            let buffer_id = payload.buffer_id;
5289            let ops = payload
5290                .operations
5291                .into_iter()
5292                .map(language::proto::deserialize_operation)
5293                .collect::<Result<Vec<_>, _>>()?;
5294            let is_remote = this.is_remote();
5295            match this.opened_buffers.entry(buffer_id) {
5296                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5297                    OpenBuffer::Strong(buffer) => {
5298                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5299                    }
5300                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5301                    OpenBuffer::Weak(_) => {}
5302                },
5303                hash_map::Entry::Vacant(e) => {
5304                    assert!(
5305                        is_remote,
5306                        "received buffer update from {:?}",
5307                        envelope.original_sender_id
5308                    );
5309                    e.insert(OpenBuffer::Operations(ops));
5310                }
5311            }
5312            Ok(proto::Ack {})
5313        })
5314    }
5315
5316    async fn handle_create_buffer_for_peer(
5317        this: ModelHandle<Self>,
5318        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5319        _: Arc<Client>,
5320        mut cx: AsyncAppContext,
5321    ) -> Result<()> {
5322        this.update(&mut cx, |this, cx| {
5323            match envelope
5324                .payload
5325                .variant
5326                .ok_or_else(|| anyhow!("missing variant"))?
5327            {
5328                proto::create_buffer_for_peer::Variant::State(mut state) => {
5329                    let mut buffer_file = None;
5330                    if let Some(file) = state.file.take() {
5331                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5332                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5333                            anyhow!("no worktree found for id {}", file.worktree_id)
5334                        })?;
5335                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5336                            as Arc<dyn language::File>);
5337                    }
5338
5339                    let buffer_id = state.id;
5340                    let buffer = cx.add_model(|_| {
5341                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5342                    });
5343                    this.incomplete_remote_buffers
5344                        .insert(buffer_id, Some(buffer));
5345                }
5346                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5347                    let buffer = this
5348                        .incomplete_remote_buffers
5349                        .get(&chunk.buffer_id)
5350                        .cloned()
5351                        .flatten()
5352                        .ok_or_else(|| {
5353                            anyhow!(
5354                                "received chunk for buffer {} without initial state",
5355                                chunk.buffer_id
5356                            )
5357                        })?;
5358                    let operations = chunk
5359                        .operations
5360                        .into_iter()
5361                        .map(language::proto::deserialize_operation)
5362                        .collect::<Result<Vec<_>>>()?;
5363                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5364
5365                    if chunk.is_last {
5366                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5367                        this.register_buffer(&buffer, cx)?;
5368                    }
5369                }
5370            }
5371
5372            Ok(())
5373        })
5374    }
5375
5376    async fn handle_update_diff_base(
5377        this: ModelHandle<Self>,
5378        envelope: TypedEnvelope<proto::UpdateDiffBase>,
5379        _: Arc<Client>,
5380        mut cx: AsyncAppContext,
5381    ) -> Result<()> {
5382        this.update(&mut cx, |this, cx| {
5383            let buffer_id = envelope.payload.buffer_id;
5384            let diff_base = envelope.payload.diff_base;
5385            if let Some(buffer) = this
5386                .opened_buffers
5387                .get_mut(&buffer_id)
5388                .and_then(|b| b.upgrade(cx))
5389                .or_else(|| {
5390                    this.incomplete_remote_buffers
5391                        .get(&buffer_id)
5392                        .cloned()
5393                        .flatten()
5394                })
5395            {
5396                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5397            }
5398            Ok(())
5399        })
5400    }
5401
5402    async fn handle_update_buffer_file(
5403        this: ModelHandle<Self>,
5404        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5405        _: Arc<Client>,
5406        mut cx: AsyncAppContext,
5407    ) -> Result<()> {
5408        let buffer_id = envelope.payload.buffer_id;
5409
5410        this.update(&mut cx, |this, cx| {
5411            let payload = envelope.payload.clone();
5412            if let Some(buffer) = this
5413                .opened_buffers
5414                .get(&buffer_id)
5415                .and_then(|b| b.upgrade(cx))
5416                .or_else(|| {
5417                    this.incomplete_remote_buffers
5418                        .get(&buffer_id)
5419                        .cloned()
5420                        .flatten()
5421                })
5422            {
5423                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5424                let worktree = this
5425                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5426                    .ok_or_else(|| anyhow!("no such worktree"))?;
5427                let file = File::from_proto(file, worktree, cx)?;
5428                buffer.update(cx, |buffer, cx| {
5429                    buffer.file_updated(Arc::new(file), cx).detach();
5430                });
5431                this.detect_language_for_buffer(&buffer, cx);
5432            }
5433            Ok(())
5434        })
5435    }
5436
5437    async fn handle_save_buffer(
5438        this: ModelHandle<Self>,
5439        envelope: TypedEnvelope<proto::SaveBuffer>,
5440        _: Arc<Client>,
5441        mut cx: AsyncAppContext,
5442    ) -> Result<proto::BufferSaved> {
5443        let buffer_id = envelope.payload.buffer_id;
5444        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5445            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5446            let buffer = this
5447                .opened_buffers
5448                .get(&buffer_id)
5449                .and_then(|buffer| buffer.upgrade(cx))
5450                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5451            anyhow::Ok((project_id, buffer))
5452        })?;
5453        buffer
5454            .update(&mut cx, |buffer, _| {
5455                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
5456            })
5457            .await?;
5458        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
5459
5460        let (saved_version, fingerprint, mtime) = this
5461            .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5462            .await?;
5463        Ok(proto::BufferSaved {
5464            project_id,
5465            buffer_id,
5466            version: serialize_version(&saved_version),
5467            mtime: Some(mtime.into()),
5468            fingerprint: language::proto::serialize_fingerprint(fingerprint),
5469        })
5470    }
5471
5472    async fn handle_reload_buffers(
5473        this: ModelHandle<Self>,
5474        envelope: TypedEnvelope<proto::ReloadBuffers>,
5475        _: Arc<Client>,
5476        mut cx: AsyncAppContext,
5477    ) -> Result<proto::ReloadBuffersResponse> {
5478        let sender_id = envelope.original_sender_id()?;
5479        let reload = this.update(&mut cx, |this, cx| {
5480            let mut buffers = HashSet::default();
5481            for buffer_id in &envelope.payload.buffer_ids {
5482                buffers.insert(
5483                    this.opened_buffers
5484                        .get(buffer_id)
5485                        .and_then(|buffer| buffer.upgrade(cx))
5486                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5487                );
5488            }
5489            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5490        })?;
5491
5492        let project_transaction = reload.await?;
5493        let project_transaction = this.update(&mut cx, |this, cx| {
5494            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5495        });
5496        Ok(proto::ReloadBuffersResponse {
5497            transaction: Some(project_transaction),
5498        })
5499    }
5500
5501    async fn handle_synchronize_buffers(
5502        this: ModelHandle<Self>,
5503        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5504        _: Arc<Client>,
5505        mut cx: AsyncAppContext,
5506    ) -> Result<proto::SynchronizeBuffersResponse> {
5507        let project_id = envelope.payload.project_id;
5508        let mut response = proto::SynchronizeBuffersResponse {
5509            buffers: Default::default(),
5510        };
5511
5512        this.update(&mut cx, |this, cx| {
5513            let Some(guest_id) = envelope.original_sender_id else {
5514                log::error!("missing original_sender_id on SynchronizeBuffers request");
5515                return;
5516            };
5517
5518            this.shared_buffers.entry(guest_id).or_default().clear();
5519            for buffer in envelope.payload.buffers {
5520                let buffer_id = buffer.id;
5521                let remote_version = language::proto::deserialize_version(&buffer.version);
5522                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5523                    this.shared_buffers
5524                        .entry(guest_id)
5525                        .or_default()
5526                        .insert(buffer_id);
5527
5528                    let buffer = buffer.read(cx);
5529                    response.buffers.push(proto::BufferVersion {
5530                        id: buffer_id,
5531                        version: language::proto::serialize_version(&buffer.version),
5532                    });
5533
5534                    let operations = buffer.serialize_ops(Some(remote_version), cx);
5535                    let client = this.client.clone();
5536                    if let Some(file) = buffer.file() {
5537                        client
5538                            .send(proto::UpdateBufferFile {
5539                                project_id,
5540                                buffer_id: buffer_id as u64,
5541                                file: Some(file.to_proto()),
5542                            })
5543                            .log_err();
5544                    }
5545
5546                    client
5547                        .send(proto::UpdateDiffBase {
5548                            project_id,
5549                            buffer_id: buffer_id as u64,
5550                            diff_base: buffer.diff_base().map(Into::into),
5551                        })
5552                        .log_err();
5553
5554                    client
5555                        .send(proto::BufferReloaded {
5556                            project_id,
5557                            buffer_id,
5558                            version: language::proto::serialize_version(buffer.saved_version()),
5559                            mtime: Some(buffer.saved_mtime().into()),
5560                            fingerprint: language::proto::serialize_fingerprint(
5561                                buffer.saved_version_fingerprint(),
5562                            ),
5563                            line_ending: language::proto::serialize_line_ending(
5564                                buffer.line_ending(),
5565                            ) as i32,
5566                        })
5567                        .log_err();
5568
5569                    cx.background()
5570                        .spawn(
5571                            async move {
5572                                let operations = operations.await;
5573                                for chunk in split_operations(operations) {
5574                                    client
5575                                        .request(proto::UpdateBuffer {
5576                                            project_id,
5577                                            buffer_id,
5578                                            operations: chunk,
5579                                        })
5580                                        .await?;
5581                                }
5582                                anyhow::Ok(())
5583                            }
5584                            .log_err(),
5585                        )
5586                        .detach();
5587                }
5588            }
5589        });
5590
5591        Ok(response)
5592    }
5593
5594    async fn handle_format_buffers(
5595        this: ModelHandle<Self>,
5596        envelope: TypedEnvelope<proto::FormatBuffers>,
5597        _: Arc<Client>,
5598        mut cx: AsyncAppContext,
5599    ) -> Result<proto::FormatBuffersResponse> {
5600        let sender_id = envelope.original_sender_id()?;
5601        let format = this.update(&mut cx, |this, cx| {
5602            let mut buffers = HashSet::default();
5603            for buffer_id in &envelope.payload.buffer_ids {
5604                buffers.insert(
5605                    this.opened_buffers
5606                        .get(buffer_id)
5607                        .and_then(|buffer| buffer.upgrade(cx))
5608                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5609                );
5610            }
5611            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5612            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5613        })?;
5614
5615        let project_transaction = format.await?;
5616        let project_transaction = this.update(&mut cx, |this, cx| {
5617            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5618        });
5619        Ok(proto::FormatBuffersResponse {
5620            transaction: Some(project_transaction),
5621        })
5622    }
5623
5624    async fn handle_apply_additional_edits_for_completion(
5625        this: ModelHandle<Self>,
5626        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5627        _: Arc<Client>,
5628        mut cx: AsyncAppContext,
5629    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5630        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5631            let buffer = this
5632                .opened_buffers
5633                .get(&envelope.payload.buffer_id)
5634                .and_then(|buffer| buffer.upgrade(cx))
5635                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5636            let language = buffer.read(cx).language();
5637            let completion = language::proto::deserialize_completion(
5638                envelope
5639                    .payload
5640                    .completion
5641                    .ok_or_else(|| anyhow!("invalid completion"))?,
5642                language.cloned(),
5643            );
5644            Ok::<_, anyhow::Error>((buffer, completion))
5645        })?;
5646
5647        let completion = completion.await?;
5648
5649        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5650            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5651        });
5652
5653        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5654            transaction: apply_additional_edits
5655                .await?
5656                .as_ref()
5657                .map(language::proto::serialize_transaction),
5658        })
5659    }
5660
5661    async fn handle_apply_code_action(
5662        this: ModelHandle<Self>,
5663        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5664        _: Arc<Client>,
5665        mut cx: AsyncAppContext,
5666    ) -> Result<proto::ApplyCodeActionResponse> {
5667        let sender_id = envelope.original_sender_id()?;
5668        let action = language::proto::deserialize_code_action(
5669            envelope
5670                .payload
5671                .action
5672                .ok_or_else(|| anyhow!("invalid action"))?,
5673        )?;
5674        let apply_code_action = this.update(&mut cx, |this, cx| {
5675            let buffer = this
5676                .opened_buffers
5677                .get(&envelope.payload.buffer_id)
5678                .and_then(|buffer| buffer.upgrade(cx))
5679                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5680            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5681        })?;
5682
5683        let project_transaction = apply_code_action.await?;
5684        let project_transaction = this.update(&mut cx, |this, cx| {
5685            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5686        });
5687        Ok(proto::ApplyCodeActionResponse {
5688            transaction: Some(project_transaction),
5689        })
5690    }
5691
5692    async fn handle_lsp_command<T: LspCommand>(
5693        this: ModelHandle<Self>,
5694        envelope: TypedEnvelope<T::ProtoRequest>,
5695        _: Arc<Client>,
5696        mut cx: AsyncAppContext,
5697    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5698    where
5699        <T::LspRequest as lsp::request::Request>::Result: Send,
5700    {
5701        let sender_id = envelope.original_sender_id()?;
5702        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5703        let buffer_handle = this.read_with(&cx, |this, _| {
5704            this.opened_buffers
5705                .get(&buffer_id)
5706                .and_then(|buffer| buffer.upgrade(&cx))
5707                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5708        })?;
5709        let request = T::from_proto(
5710            envelope.payload,
5711            this.clone(),
5712            buffer_handle.clone(),
5713            cx.clone(),
5714        )
5715        .await?;
5716        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5717        let response = this
5718            .update(&mut cx, |this, cx| {
5719                this.request_lsp(buffer_handle, request, cx)
5720            })
5721            .await?;
5722        this.update(&mut cx, |this, cx| {
5723            Ok(T::response_to_proto(
5724                response,
5725                this,
5726                sender_id,
5727                &buffer_version,
5728                cx,
5729            ))
5730        })
5731    }
5732
5733    async fn handle_get_project_symbols(
5734        this: ModelHandle<Self>,
5735        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5736        _: Arc<Client>,
5737        mut cx: AsyncAppContext,
5738    ) -> Result<proto::GetProjectSymbolsResponse> {
5739        let symbols = this
5740            .update(&mut cx, |this, cx| {
5741                this.symbols(&envelope.payload.query, cx)
5742            })
5743            .await?;
5744
5745        Ok(proto::GetProjectSymbolsResponse {
5746            symbols: symbols.iter().map(serialize_symbol).collect(),
5747        })
5748    }
5749
5750    async fn handle_search_project(
5751        this: ModelHandle<Self>,
5752        envelope: TypedEnvelope<proto::SearchProject>,
5753        _: Arc<Client>,
5754        mut cx: AsyncAppContext,
5755    ) -> Result<proto::SearchProjectResponse> {
5756        let peer_id = envelope.original_sender_id()?;
5757        let query = SearchQuery::from_proto(envelope.payload)?;
5758        let result = this
5759            .update(&mut cx, |this, cx| this.search(query, cx))
5760            .await?;
5761
5762        this.update(&mut cx, |this, cx| {
5763            let mut locations = Vec::new();
5764            for (buffer, ranges) in result {
5765                for range in ranges {
5766                    let start = serialize_anchor(&range.start);
5767                    let end = serialize_anchor(&range.end);
5768                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5769                    locations.push(proto::Location {
5770                        buffer_id,
5771                        start: Some(start),
5772                        end: Some(end),
5773                    });
5774                }
5775            }
5776            Ok(proto::SearchProjectResponse { locations })
5777        })
5778    }
5779
5780    async fn handle_open_buffer_for_symbol(
5781        this: ModelHandle<Self>,
5782        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5783        _: Arc<Client>,
5784        mut cx: AsyncAppContext,
5785    ) -> Result<proto::OpenBufferForSymbolResponse> {
5786        let peer_id = envelope.original_sender_id()?;
5787        let symbol = envelope
5788            .payload
5789            .symbol
5790            .ok_or_else(|| anyhow!("invalid symbol"))?;
5791        let symbol = this
5792            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5793            .await?;
5794        let symbol = this.read_with(&cx, |this, _| {
5795            let signature = this.symbol_signature(&symbol.path);
5796            if signature == symbol.signature {
5797                Ok(symbol)
5798            } else {
5799                Err(anyhow!("invalid symbol signature"))
5800            }
5801        })?;
5802        let buffer = this
5803            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5804            .await?;
5805
5806        Ok(proto::OpenBufferForSymbolResponse {
5807            buffer_id: this.update(&mut cx, |this, cx| {
5808                this.create_buffer_for_peer(&buffer, peer_id, cx)
5809            }),
5810        })
5811    }
5812
5813    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5814        let mut hasher = Sha256::new();
5815        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5816        hasher.update(project_path.path.to_string_lossy().as_bytes());
5817        hasher.update(self.nonce.to_be_bytes());
5818        hasher.finalize().as_slice().try_into().unwrap()
5819    }
5820
5821    async fn handle_open_buffer_by_id(
5822        this: ModelHandle<Self>,
5823        envelope: TypedEnvelope<proto::OpenBufferById>,
5824        _: Arc<Client>,
5825        mut cx: AsyncAppContext,
5826    ) -> Result<proto::OpenBufferResponse> {
5827        let peer_id = envelope.original_sender_id()?;
5828        let buffer = this
5829            .update(&mut cx, |this, cx| {
5830                this.open_buffer_by_id(envelope.payload.id, cx)
5831            })
5832            .await?;
5833        this.update(&mut cx, |this, cx| {
5834            Ok(proto::OpenBufferResponse {
5835                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5836            })
5837        })
5838    }
5839
5840    async fn handle_open_buffer_by_path(
5841        this: ModelHandle<Self>,
5842        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5843        _: Arc<Client>,
5844        mut cx: AsyncAppContext,
5845    ) -> Result<proto::OpenBufferResponse> {
5846        let peer_id = envelope.original_sender_id()?;
5847        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5848        let open_buffer = this.update(&mut cx, |this, cx| {
5849            this.open_buffer(
5850                ProjectPath {
5851                    worktree_id,
5852                    path: PathBuf::from(envelope.payload.path).into(),
5853                },
5854                cx,
5855            )
5856        });
5857
5858        let buffer = open_buffer.await?;
5859        this.update(&mut cx, |this, cx| {
5860            Ok(proto::OpenBufferResponse {
5861                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5862            })
5863        })
5864    }
5865
5866    fn serialize_project_transaction_for_peer(
5867        &mut self,
5868        project_transaction: ProjectTransaction,
5869        peer_id: proto::PeerId,
5870        cx: &mut AppContext,
5871    ) -> proto::ProjectTransaction {
5872        let mut serialized_transaction = proto::ProjectTransaction {
5873            buffer_ids: Default::default(),
5874            transactions: Default::default(),
5875        };
5876        for (buffer, transaction) in project_transaction.0 {
5877            serialized_transaction
5878                .buffer_ids
5879                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5880            serialized_transaction
5881                .transactions
5882                .push(language::proto::serialize_transaction(&transaction));
5883        }
5884        serialized_transaction
5885    }
5886
5887    fn deserialize_project_transaction(
5888        &mut self,
5889        message: proto::ProjectTransaction,
5890        push_to_history: bool,
5891        cx: &mut ModelContext<Self>,
5892    ) -> Task<Result<ProjectTransaction>> {
5893        cx.spawn(|this, mut cx| async move {
5894            let mut project_transaction = ProjectTransaction::default();
5895            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5896            {
5897                let buffer = this
5898                    .update(&mut cx, |this, cx| {
5899                        this.wait_for_remote_buffer(buffer_id, cx)
5900                    })
5901                    .await?;
5902                let transaction = language::proto::deserialize_transaction(transaction)?;
5903                project_transaction.0.insert(buffer, transaction);
5904            }
5905
5906            for (buffer, transaction) in &project_transaction.0 {
5907                buffer
5908                    .update(&mut cx, |buffer, _| {
5909                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5910                    })
5911                    .await?;
5912
5913                if push_to_history {
5914                    buffer.update(&mut cx, |buffer, _| {
5915                        buffer.push_transaction(transaction.clone(), Instant::now());
5916                    });
5917                }
5918            }
5919
5920            Ok(project_transaction)
5921        })
5922    }
5923
5924    fn create_buffer_for_peer(
5925        &mut self,
5926        buffer: &ModelHandle<Buffer>,
5927        peer_id: proto::PeerId,
5928        cx: &mut AppContext,
5929    ) -> u64 {
5930        let buffer_id = buffer.read(cx).remote_id();
5931        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
5932            updates_tx
5933                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
5934                .ok();
5935        }
5936        buffer_id
5937    }
5938
5939    fn wait_for_remote_buffer(
5940        &mut self,
5941        id: u64,
5942        cx: &mut ModelContext<Self>,
5943    ) -> Task<Result<ModelHandle<Buffer>>> {
5944        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5945
5946        cx.spawn_weak(|this, mut cx| async move {
5947            let buffer = loop {
5948                let Some(this) = this.upgrade(&cx) else {
5949                    return Err(anyhow!("project dropped"));
5950                };
5951                let buffer = this.read_with(&cx, |this, cx| {
5952                    this.opened_buffers
5953                        .get(&id)
5954                        .and_then(|buffer| buffer.upgrade(cx))
5955                });
5956                if let Some(buffer) = buffer {
5957                    break buffer;
5958                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5959                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5960                }
5961
5962                this.update(&mut cx, |this, _| {
5963                    this.incomplete_remote_buffers.entry(id).or_default();
5964                });
5965                drop(this);
5966                opened_buffer_rx
5967                    .next()
5968                    .await
5969                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5970            };
5971            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5972            Ok(buffer)
5973        })
5974    }
5975
5976    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
5977        let project_id = match self.client_state.as_ref() {
5978            Some(ProjectClientState::Remote {
5979                sharing_has_stopped,
5980                remote_id,
5981                ..
5982            }) => {
5983                if *sharing_has_stopped {
5984                    return Task::ready(Err(anyhow!(
5985                        "can't synchronize remote buffers on a readonly project"
5986                    )));
5987                } else {
5988                    *remote_id
5989                }
5990            }
5991            Some(ProjectClientState::Local { .. }) | None => {
5992                return Task::ready(Err(anyhow!(
5993                    "can't synchronize remote buffers on a local project"
5994                )))
5995            }
5996        };
5997
5998        let client = self.client.clone();
5999        cx.spawn(|this, cx| async move {
6000            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
6001                let buffers = this
6002                    .opened_buffers
6003                    .iter()
6004                    .filter_map(|(id, buffer)| {
6005                        let buffer = buffer.upgrade(cx)?;
6006                        Some(proto::BufferVersion {
6007                            id: *id,
6008                            version: language::proto::serialize_version(&buffer.read(cx).version),
6009                        })
6010                    })
6011                    .collect();
6012                let incomplete_buffer_ids = this
6013                    .incomplete_remote_buffers
6014                    .keys()
6015                    .copied()
6016                    .collect::<Vec<_>>();
6017
6018                (buffers, incomplete_buffer_ids)
6019            });
6020            let response = client
6021                .request(proto::SynchronizeBuffers {
6022                    project_id,
6023                    buffers,
6024                })
6025                .await?;
6026
6027            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
6028                let client = client.clone();
6029                let buffer_id = buffer.id;
6030                let remote_version = language::proto::deserialize_version(&buffer.version);
6031                this.read_with(&cx, |this, cx| {
6032                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
6033                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
6034                        cx.background().spawn(async move {
6035                            let operations = operations.await;
6036                            for chunk in split_operations(operations) {
6037                                client
6038                                    .request(proto::UpdateBuffer {
6039                                        project_id,
6040                                        buffer_id,
6041                                        operations: chunk,
6042                                    })
6043                                    .await?;
6044                            }
6045                            anyhow::Ok(())
6046                        })
6047                    } else {
6048                        Task::ready(Ok(()))
6049                    }
6050                })
6051            });
6052
6053            // Any incomplete buffers have open requests waiting. Request that the host sends
6054            // creates these buffers for us again to unblock any waiting futures.
6055            for id in incomplete_buffer_ids {
6056                cx.background()
6057                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
6058                    .detach();
6059            }
6060
6061            futures::future::join_all(send_updates_for_buffers)
6062                .await
6063                .into_iter()
6064                .collect()
6065        })
6066    }
6067
6068    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
6069        self.worktrees(cx)
6070            .map(|worktree| {
6071                let worktree = worktree.read(cx);
6072                proto::WorktreeMetadata {
6073                    id: worktree.id().to_proto(),
6074                    root_name: worktree.root_name().into(),
6075                    visible: worktree.is_visible(),
6076                    abs_path: worktree.abs_path().to_string_lossy().into(),
6077                }
6078            })
6079            .collect()
6080    }
6081
6082    fn set_worktrees_from_proto(
6083        &mut self,
6084        worktrees: Vec<proto::WorktreeMetadata>,
6085        cx: &mut ModelContext<Project>,
6086    ) -> Result<()> {
6087        let replica_id = self.replica_id();
6088        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
6089
6090        let mut old_worktrees_by_id = self
6091            .worktrees
6092            .drain(..)
6093            .filter_map(|worktree| {
6094                let worktree = worktree.upgrade(cx)?;
6095                Some((worktree.read(cx).id(), worktree))
6096            })
6097            .collect::<HashMap<_, _>>();
6098
6099        for worktree in worktrees {
6100            if let Some(old_worktree) =
6101                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
6102            {
6103                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
6104            } else {
6105                let worktree =
6106                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
6107                let _ = self.add_worktree(&worktree, cx);
6108            }
6109        }
6110
6111        self.metadata_changed(cx);
6112        for (id, _) in old_worktrees_by_id {
6113            cx.emit(Event::WorktreeRemoved(id));
6114        }
6115
6116        Ok(())
6117    }
6118
6119    fn set_collaborators_from_proto(
6120        &mut self,
6121        messages: Vec<proto::Collaborator>,
6122        cx: &mut ModelContext<Self>,
6123    ) -> Result<()> {
6124        let mut collaborators = HashMap::default();
6125        for message in messages {
6126            let collaborator = Collaborator::from_proto(message)?;
6127            collaborators.insert(collaborator.peer_id, collaborator);
6128        }
6129        for old_peer_id in self.collaborators.keys() {
6130            if !collaborators.contains_key(old_peer_id) {
6131                cx.emit(Event::CollaboratorLeft(*old_peer_id));
6132            }
6133        }
6134        self.collaborators = collaborators;
6135        Ok(())
6136    }
6137
6138    fn deserialize_symbol(
6139        &self,
6140        serialized_symbol: proto::Symbol,
6141    ) -> impl Future<Output = Result<Symbol>> {
6142        let languages = self.languages.clone();
6143        async move {
6144            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
6145            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6146            let start = serialized_symbol
6147                .start
6148                .ok_or_else(|| anyhow!("invalid start"))?;
6149            let end = serialized_symbol
6150                .end
6151                .ok_or_else(|| anyhow!("invalid end"))?;
6152            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6153            let path = ProjectPath {
6154                worktree_id,
6155                path: PathBuf::from(serialized_symbol.path).into(),
6156            };
6157            let language = languages
6158                .language_for_file(&path.path, None)
6159                .await
6160                .log_err();
6161            Ok(Symbol {
6162                language_server_name: LanguageServerName(
6163                    serialized_symbol.language_server_name.into(),
6164                ),
6165                source_worktree_id,
6166                path,
6167                label: {
6168                    match language {
6169                        Some(language) => {
6170                            language
6171                                .label_for_symbol(&serialized_symbol.name, kind)
6172                                .await
6173                        }
6174                        None => None,
6175                    }
6176                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6177                },
6178
6179                name: serialized_symbol.name,
6180                range: Unclipped(PointUtf16::new(start.row, start.column))
6181                    ..Unclipped(PointUtf16::new(end.row, end.column)),
6182                kind,
6183                signature: serialized_symbol
6184                    .signature
6185                    .try_into()
6186                    .map_err(|_| anyhow!("invalid signature"))?,
6187            })
6188        }
6189    }
6190
6191    async fn handle_buffer_saved(
6192        this: ModelHandle<Self>,
6193        envelope: TypedEnvelope<proto::BufferSaved>,
6194        _: Arc<Client>,
6195        mut cx: AsyncAppContext,
6196    ) -> Result<()> {
6197        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6198        let version = deserialize_version(&envelope.payload.version);
6199        let mtime = envelope
6200            .payload
6201            .mtime
6202            .ok_or_else(|| anyhow!("missing mtime"))?
6203            .into();
6204
6205        this.update(&mut cx, |this, cx| {
6206            let buffer = this
6207                .opened_buffers
6208                .get(&envelope.payload.buffer_id)
6209                .and_then(|buffer| buffer.upgrade(cx))
6210                .or_else(|| {
6211                    this.incomplete_remote_buffers
6212                        .get(&envelope.payload.buffer_id)
6213                        .and_then(|b| b.clone())
6214                });
6215            if let Some(buffer) = buffer {
6216                buffer.update(cx, |buffer, cx| {
6217                    buffer.did_save(version, fingerprint, mtime, cx);
6218                });
6219            }
6220            Ok(())
6221        })
6222    }
6223
6224    async fn handle_buffer_reloaded(
6225        this: ModelHandle<Self>,
6226        envelope: TypedEnvelope<proto::BufferReloaded>,
6227        _: Arc<Client>,
6228        mut cx: AsyncAppContext,
6229    ) -> Result<()> {
6230        let payload = envelope.payload;
6231        let version = deserialize_version(&payload.version);
6232        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6233        let line_ending = deserialize_line_ending(
6234            proto::LineEnding::from_i32(payload.line_ending)
6235                .ok_or_else(|| anyhow!("missing line ending"))?,
6236        );
6237        let mtime = payload
6238            .mtime
6239            .ok_or_else(|| anyhow!("missing mtime"))?
6240            .into();
6241        this.update(&mut cx, |this, cx| {
6242            let buffer = this
6243                .opened_buffers
6244                .get(&payload.buffer_id)
6245                .and_then(|buffer| buffer.upgrade(cx))
6246                .or_else(|| {
6247                    this.incomplete_remote_buffers
6248                        .get(&payload.buffer_id)
6249                        .cloned()
6250                        .flatten()
6251                });
6252            if let Some(buffer) = buffer {
6253                buffer.update(cx, |buffer, cx| {
6254                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6255                });
6256            }
6257            Ok(())
6258        })
6259    }
6260
6261    #[allow(clippy::type_complexity)]
6262    fn edits_from_lsp(
6263        &mut self,
6264        buffer: &ModelHandle<Buffer>,
6265        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6266        server_id: LanguageServerId,
6267        version: Option<i32>,
6268        cx: &mut ModelContext<Self>,
6269    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6270        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
6271        cx.background().spawn(async move {
6272            let snapshot = snapshot?;
6273            let mut lsp_edits = lsp_edits
6274                .into_iter()
6275                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6276                .collect::<Vec<_>>();
6277            lsp_edits.sort_by_key(|(range, _)| range.start);
6278
6279            let mut lsp_edits = lsp_edits.into_iter().peekable();
6280            let mut edits = Vec::new();
6281            while let Some((range, mut new_text)) = lsp_edits.next() {
6282                // Clip invalid ranges provided by the language server.
6283                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6284                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
6285
6286                // Combine any LSP edits that are adjacent.
6287                //
6288                // Also, combine LSP edits that are separated from each other by only
6289                // a newline. This is important because for some code actions,
6290                // Rust-analyzer rewrites the entire buffer via a series of edits that
6291                // are separated by unchanged newline characters.
6292                //
6293                // In order for the diffing logic below to work properly, any edits that
6294                // cancel each other out must be combined into one.
6295                while let Some((next_range, next_text)) = lsp_edits.peek() {
6296                    if next_range.start.0 > range.end {
6297                        if next_range.start.0.row > range.end.row + 1
6298                            || next_range.start.0.column > 0
6299                            || snapshot.clip_point_utf16(
6300                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6301                                Bias::Left,
6302                            ) > range.end
6303                        {
6304                            break;
6305                        }
6306                        new_text.push('\n');
6307                    }
6308                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6309                    new_text.push_str(next_text);
6310                    lsp_edits.next();
6311                }
6312
6313                // For multiline edits, perform a diff of the old and new text so that
6314                // we can identify the changes more precisely, preserving the locations
6315                // of any anchors positioned in the unchanged regions.
6316                if range.end.row > range.start.row {
6317                    let mut offset = range.start.to_offset(&snapshot);
6318                    let old_text = snapshot.text_for_range(range).collect::<String>();
6319
6320                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6321                    let mut moved_since_edit = true;
6322                    for change in diff.iter_all_changes() {
6323                        let tag = change.tag();
6324                        let value = change.value();
6325                        match tag {
6326                            ChangeTag::Equal => {
6327                                offset += value.len();
6328                                moved_since_edit = true;
6329                            }
6330                            ChangeTag::Delete => {
6331                                let start = snapshot.anchor_after(offset);
6332                                let end = snapshot.anchor_before(offset + value.len());
6333                                if moved_since_edit {
6334                                    edits.push((start..end, String::new()));
6335                                } else {
6336                                    edits.last_mut().unwrap().0.end = end;
6337                                }
6338                                offset += value.len();
6339                                moved_since_edit = false;
6340                            }
6341                            ChangeTag::Insert => {
6342                                if moved_since_edit {
6343                                    let anchor = snapshot.anchor_after(offset);
6344                                    edits.push((anchor..anchor, value.to_string()));
6345                                } else {
6346                                    edits.last_mut().unwrap().1.push_str(value);
6347                                }
6348                                moved_since_edit = false;
6349                            }
6350                        }
6351                    }
6352                } else if range.end == range.start {
6353                    let anchor = snapshot.anchor_after(range.start);
6354                    edits.push((anchor..anchor, new_text));
6355                } else {
6356                    let edit_start = snapshot.anchor_after(range.start);
6357                    let edit_end = snapshot.anchor_before(range.end);
6358                    edits.push((edit_start..edit_end, new_text));
6359                }
6360            }
6361
6362            Ok(edits)
6363        })
6364    }
6365
6366    fn buffer_snapshot_for_lsp_version(
6367        &mut self,
6368        buffer: &ModelHandle<Buffer>,
6369        server_id: LanguageServerId,
6370        version: Option<i32>,
6371        cx: &AppContext,
6372    ) -> Result<TextBufferSnapshot> {
6373        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6374
6375        if let Some(version) = version {
6376            let buffer_id = buffer.read(cx).remote_id();
6377            let snapshots = self
6378                .buffer_snapshots
6379                .get_mut(&buffer_id)
6380                .and_then(|m| m.get_mut(&server_id))
6381                .ok_or_else(|| {
6382                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
6383                })?;
6384
6385            let found_snapshot = snapshots
6386                .binary_search_by_key(&version, |e| e.version)
6387                .map(|ix| snapshots[ix].snapshot.clone())
6388                .map_err(|_| {
6389                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
6390                })?;
6391
6392            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
6393            Ok(found_snapshot)
6394        } else {
6395            Ok((buffer.read(cx)).text_snapshot())
6396        }
6397    }
6398
6399    pub fn language_servers(
6400        &self,
6401    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
6402        self.language_server_ids
6403            .iter()
6404            .map(|((worktree_id, server_name), server_id)| {
6405                (*server_id, server_name.clone(), *worktree_id)
6406            })
6407    }
6408
6409    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
6410        if let LanguageServerState::Running { server, .. } = self.language_servers.get(&id)? {
6411            Some(server.clone())
6412        } else {
6413            None
6414        }
6415    }
6416
6417    pub fn language_servers_for_buffer(
6418        &self,
6419        buffer: &Buffer,
6420        cx: &AppContext,
6421    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6422        self.language_server_ids_for_buffer(buffer, cx)
6423            .into_iter()
6424            .filter_map(|server_id| {
6425                let server = self.language_servers.get(&server_id)?;
6426                if let LanguageServerState::Running {
6427                    adapter, server, ..
6428                } = server
6429                {
6430                    Some((adapter, server))
6431                } else {
6432                    None
6433                }
6434            })
6435    }
6436
6437    fn primary_language_servers_for_buffer(
6438        &self,
6439        buffer: &Buffer,
6440        cx: &AppContext,
6441    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6442        self.language_servers_for_buffer(buffer, cx).next()
6443    }
6444
6445    fn language_server_for_buffer(
6446        &self,
6447        buffer: &Buffer,
6448        server_id: LanguageServerId,
6449        cx: &AppContext,
6450    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6451        self.language_servers_for_buffer(buffer, cx)
6452            .find(|(_, s)| s.server_id() == server_id)
6453    }
6454
6455    fn language_server_ids_for_buffer(
6456        &self,
6457        buffer: &Buffer,
6458        cx: &AppContext,
6459    ) -> Vec<LanguageServerId> {
6460        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6461            let worktree_id = file.worktree_id(cx);
6462            language
6463                .lsp_adapters()
6464                .iter()
6465                .flat_map(|adapter| {
6466                    let key = (worktree_id, adapter.name.clone());
6467                    self.language_server_ids.get(&key).copied()
6468                })
6469                .collect()
6470        } else {
6471            Vec::new()
6472        }
6473    }
6474}
6475
6476impl WorktreeHandle {
6477    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6478        match self {
6479            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6480            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6481        }
6482    }
6483}
6484
6485impl OpenBuffer {
6486    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
6487        match self {
6488            OpenBuffer::Strong(handle) => Some(handle.clone()),
6489            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6490            OpenBuffer::Operations(_) => None,
6491        }
6492    }
6493}
6494
6495pub struct PathMatchCandidateSet {
6496    pub snapshot: Snapshot,
6497    pub include_ignored: bool,
6498    pub include_root_name: bool,
6499}
6500
6501impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6502    type Candidates = PathMatchCandidateSetIter<'a>;
6503
6504    fn id(&self) -> usize {
6505        self.snapshot.id().to_usize()
6506    }
6507
6508    fn len(&self) -> usize {
6509        if self.include_ignored {
6510            self.snapshot.file_count()
6511        } else {
6512            self.snapshot.visible_file_count()
6513        }
6514    }
6515
6516    fn prefix(&self) -> Arc<str> {
6517        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6518            self.snapshot.root_name().into()
6519        } else if self.include_root_name {
6520            format!("{}/", self.snapshot.root_name()).into()
6521        } else {
6522            "".into()
6523        }
6524    }
6525
6526    fn candidates(&'a self, start: usize) -> Self::Candidates {
6527        PathMatchCandidateSetIter {
6528            traversal: self.snapshot.files(self.include_ignored, start),
6529        }
6530    }
6531}
6532
6533pub struct PathMatchCandidateSetIter<'a> {
6534    traversal: Traversal<'a>,
6535}
6536
6537impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6538    type Item = fuzzy::PathMatchCandidate<'a>;
6539
6540    fn next(&mut self) -> Option<Self::Item> {
6541        self.traversal.next().map(|entry| {
6542            if let EntryKind::File(char_bag) = entry.kind {
6543                fuzzy::PathMatchCandidate {
6544                    path: &entry.path,
6545                    char_bag,
6546                }
6547            } else {
6548                unreachable!()
6549            }
6550        })
6551    }
6552}
6553
6554impl Entity for Project {
6555    type Event = Event;
6556
6557    fn release(&mut self, cx: &mut gpui::AppContext) {
6558        match &self.client_state {
6559            Some(ProjectClientState::Local { .. }) => {
6560                let _ = self.unshare_internal(cx);
6561            }
6562            Some(ProjectClientState::Remote { remote_id, .. }) => {
6563                let _ = self.client.send(proto::LeaveProject {
6564                    project_id: *remote_id,
6565                });
6566                self.disconnected_from_host_internal(cx);
6567            }
6568            _ => {}
6569        }
6570    }
6571
6572    fn app_will_quit(
6573        &mut self,
6574        _: &mut AppContext,
6575    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6576        let shutdown_futures = self
6577            .language_servers
6578            .drain()
6579            .map(|(_, server_state)| async {
6580                match server_state {
6581                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6582                    LanguageServerState::Starting(starting_server) => {
6583                        starting_server.await?.shutdown()?.await
6584                    }
6585                }
6586            })
6587            .collect::<Vec<_>>();
6588
6589        Some(
6590            async move {
6591                futures::future::join_all(shutdown_futures).await;
6592            }
6593            .boxed(),
6594        )
6595    }
6596}
6597
6598impl Collaborator {
6599    fn from_proto(message: proto::Collaborator) -> Result<Self> {
6600        Ok(Self {
6601            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6602            replica_id: message.replica_id as ReplicaId,
6603        })
6604    }
6605}
6606
6607impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6608    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6609        Self {
6610            worktree_id,
6611            path: path.as_ref().into(),
6612        }
6613    }
6614}
6615
6616fn split_operations(
6617    mut operations: Vec<proto::Operation>,
6618) -> impl Iterator<Item = Vec<proto::Operation>> {
6619    #[cfg(any(test, feature = "test-support"))]
6620    const CHUNK_SIZE: usize = 5;
6621
6622    #[cfg(not(any(test, feature = "test-support")))]
6623    const CHUNK_SIZE: usize = 100;
6624
6625    let mut done = false;
6626    std::iter::from_fn(move || {
6627        if done {
6628            return None;
6629        }
6630
6631        let operations = operations
6632            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6633            .collect::<Vec<_>>();
6634        if operations.is_empty() {
6635            done = true;
6636        }
6637        Some(operations)
6638    })
6639}
6640
6641fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6642    proto::Symbol {
6643        language_server_name: symbol.language_server_name.0.to_string(),
6644        source_worktree_id: symbol.source_worktree_id.to_proto(),
6645        worktree_id: symbol.path.worktree_id.to_proto(),
6646        path: symbol.path.path.to_string_lossy().to_string(),
6647        name: symbol.name.clone(),
6648        kind: unsafe { mem::transmute(symbol.kind) },
6649        start: Some(proto::PointUtf16 {
6650            row: symbol.range.start.0.row,
6651            column: symbol.range.start.0.column,
6652        }),
6653        end: Some(proto::PointUtf16 {
6654            row: symbol.range.end.0.row,
6655            column: symbol.range.end.0.column,
6656        }),
6657        signature: symbol.signature.to_vec(),
6658    }
6659}
6660
6661fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6662    let mut path_components = path.components();
6663    let mut base_components = base.components();
6664    let mut components: Vec<Component> = Vec::new();
6665    loop {
6666        match (path_components.next(), base_components.next()) {
6667            (None, None) => break,
6668            (Some(a), None) => {
6669                components.push(a);
6670                components.extend(path_components.by_ref());
6671                break;
6672            }
6673            (None, _) => components.push(Component::ParentDir),
6674            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6675            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6676            (Some(a), Some(_)) => {
6677                components.push(Component::ParentDir);
6678                for _ in base_components {
6679                    components.push(Component::ParentDir);
6680                }
6681                components.push(a);
6682                components.extend(path_components.by_ref());
6683                break;
6684            }
6685        }
6686    }
6687    components.iter().map(|c| c.as_os_str()).collect()
6688}
6689
6690impl Item for Buffer {
6691    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6692        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6693    }
6694
6695    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6696        File::from_dyn(self.file()).map(|file| ProjectPath {
6697            worktree_id: file.worktree_id(cx),
6698            path: file.path().clone(),
6699        })
6700    }
6701}