project.rs

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