project.rs

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