project.rs

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