project.rs

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