project.rs

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