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