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