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