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::{try_join_all, 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, RopeFingerprint, TextBufferSnapshot, ToOffset, ToPointUtf16,
  32    Transaction, 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, SystemTime},
  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_buffers(
1432        &self,
1433        buffers: HashSet<ModelHandle<Buffer>>,
1434        cx: &mut ModelContext<Self>,
1435    ) -> Task<Result<()>> {
1436        cx.spawn(|this, mut cx| async move {
1437            let save_tasks = buffers
1438                .into_iter()
1439                .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1440            try_join_all(save_tasks).await?;
1441            Ok(())
1442        })
1443    }
1444
1445    pub fn save_buffer(
1446        &self,
1447        buffer: ModelHandle<Buffer>,
1448        cx: &mut ModelContext<Self>,
1449    ) -> Task<Result<(clock::Global, RopeFingerprint, SystemTime)>> {
1450        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1451            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1452        };
1453        let worktree = file.worktree.clone();
1454        let path = file.path.clone();
1455        worktree.update(cx, |worktree, cx| match worktree {
1456            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1457            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1458        })
1459    }
1460
1461    pub fn save_buffer_as(
1462        &mut self,
1463        buffer: ModelHandle<Buffer>,
1464        abs_path: PathBuf,
1465        cx: &mut ModelContext<Self>,
1466    ) -> Task<Result<()>> {
1467        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1468        let old_path =
1469            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1470        cx.spawn(|this, mut cx| async move {
1471            if let Some(old_path) = old_path {
1472                this.update(&mut cx, |this, cx| {
1473                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1474                });
1475            }
1476            let (worktree, path) = worktree_task.await?;
1477            worktree
1478                .update(&mut cx, |worktree, cx| match worktree {
1479                    Worktree::Local(worktree) => {
1480                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1481                    }
1482                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1483                })
1484                .await?;
1485            this.update(&mut cx, |this, cx| {
1486                this.assign_language_to_buffer(&buffer, cx);
1487                this.register_buffer_with_language_server(&buffer, cx);
1488            });
1489            Ok(())
1490        })
1491    }
1492
1493    pub fn get_open_buffer(
1494        &mut self,
1495        path: &ProjectPath,
1496        cx: &mut ModelContext<Self>,
1497    ) -> Option<ModelHandle<Buffer>> {
1498        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1499        self.opened_buffers.values().find_map(|buffer| {
1500            let buffer = buffer.upgrade(cx)?;
1501            let file = File::from_dyn(buffer.read(cx).file())?;
1502            if file.worktree == worktree && file.path() == &path.path {
1503                Some(buffer)
1504            } else {
1505                None
1506            }
1507        })
1508    }
1509
1510    fn register_buffer(
1511        &mut self,
1512        buffer: &ModelHandle<Buffer>,
1513        cx: &mut ModelContext<Self>,
1514    ) -> Result<()> {
1515        buffer.update(cx, |buffer, _| {
1516            buffer.set_language_registry(self.languages.clone())
1517        });
1518
1519        let remote_id = buffer.read(cx).remote_id();
1520        let open_buffer = if self.is_remote() || self.is_shared() {
1521            OpenBuffer::Strong(buffer.clone())
1522        } else {
1523            OpenBuffer::Weak(buffer.downgrade())
1524        };
1525
1526        match self.opened_buffers.insert(remote_id, open_buffer) {
1527            None => {}
1528            Some(OpenBuffer::Operations(operations)) => {
1529                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1530            }
1531            Some(OpenBuffer::Weak(existing_handle)) => {
1532                if existing_handle.upgrade(cx).is_some() {
1533                    debug_panic!("already registered buffer with remote id {}", remote_id);
1534                    Err(anyhow!(
1535                        "already registered buffer with remote id {}",
1536                        remote_id
1537                    ))?
1538                }
1539            }
1540            Some(OpenBuffer::Strong(_)) => {
1541                debug_panic!("already registered buffer with remote id {}", remote_id);
1542                Err(anyhow!(
1543                    "already registered buffer with remote id {}",
1544                    remote_id
1545                ))?
1546            }
1547        }
1548        cx.subscribe(buffer, |this, buffer, event, cx| {
1549            this.on_buffer_event(buffer, event, cx);
1550        })
1551        .detach();
1552
1553        self.assign_language_to_buffer(buffer, cx);
1554        self.register_buffer_with_language_server(buffer, cx);
1555        cx.observe_release(buffer, |this, buffer, cx| {
1556            if let Some(file) = File::from_dyn(buffer.file()) {
1557                if file.is_local() {
1558                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1559                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1560                        server
1561                            .notify::<lsp::notification::DidCloseTextDocument>(
1562                                lsp::DidCloseTextDocumentParams {
1563                                    text_document: lsp::TextDocumentIdentifier::new(uri),
1564                                },
1565                            )
1566                            .log_err();
1567                    }
1568                }
1569            }
1570        })
1571        .detach();
1572
1573        *self.opened_buffer.0.borrow_mut() = ();
1574        Ok(())
1575    }
1576
1577    fn register_buffer_with_language_server(
1578        &mut self,
1579        buffer_handle: &ModelHandle<Buffer>,
1580        cx: &mut ModelContext<Self>,
1581    ) {
1582        let buffer = buffer_handle.read(cx);
1583        let buffer_id = buffer.remote_id();
1584        if let Some(file) = File::from_dyn(buffer.file()) {
1585            if file.is_local() {
1586                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1587                let initial_snapshot = buffer.text_snapshot();
1588
1589                let mut language_server = None;
1590                let mut language_id = None;
1591                if let Some(language) = buffer.language() {
1592                    let worktree_id = file.worktree_id(cx);
1593                    if let Some(adapter) = language.lsp_adapter() {
1594                        language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1595                        language_server = self
1596                            .language_server_ids
1597                            .get(&(worktree_id, adapter.name.clone()))
1598                            .and_then(|id| self.language_servers.get(id))
1599                            .and_then(|server_state| {
1600                                if let LanguageServerState::Running { server, .. } = server_state {
1601                                    Some(server.clone())
1602                                } else {
1603                                    None
1604                                }
1605                            });
1606                    }
1607                }
1608
1609                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1610                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1611                        self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1612                            .log_err();
1613                    }
1614                }
1615
1616                if let Some(server) = language_server {
1617                    server
1618                        .notify::<lsp::notification::DidOpenTextDocument>(
1619                            lsp::DidOpenTextDocumentParams {
1620                                text_document: lsp::TextDocumentItem::new(
1621                                    uri,
1622                                    language_id.unwrap_or_default(),
1623                                    0,
1624                                    initial_snapshot.text(),
1625                                ),
1626                            },
1627                        )
1628                        .log_err();
1629                    buffer_handle.update(cx, |buffer, cx| {
1630                        buffer.set_completion_triggers(
1631                            server
1632                                .capabilities()
1633                                .completion_provider
1634                                .as_ref()
1635                                .and_then(|provider| provider.trigger_characters.clone())
1636                                .unwrap_or_default(),
1637                            cx,
1638                        )
1639                    });
1640                    self.buffer_snapshots
1641                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1642                }
1643            }
1644        }
1645    }
1646
1647    fn unregister_buffer_from_language_server(
1648        &mut self,
1649        buffer: &ModelHandle<Buffer>,
1650        old_path: PathBuf,
1651        cx: &mut ModelContext<Self>,
1652    ) {
1653        buffer.update(cx, |buffer, cx| {
1654            buffer.update_diagnostics(Default::default(), cx);
1655            self.buffer_snapshots.remove(&buffer.remote_id());
1656            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1657                language_server
1658                    .notify::<lsp::notification::DidCloseTextDocument>(
1659                        lsp::DidCloseTextDocumentParams {
1660                            text_document: lsp::TextDocumentIdentifier::new(
1661                                lsp::Url::from_file_path(old_path).unwrap(),
1662                            ),
1663                        },
1664                    )
1665                    .log_err();
1666            }
1667        });
1668    }
1669
1670    fn on_buffer_event(
1671        &mut self,
1672        buffer: ModelHandle<Buffer>,
1673        event: &BufferEvent,
1674        cx: &mut ModelContext<Self>,
1675    ) -> Option<()> {
1676        match event {
1677            BufferEvent::Operation(operation) => {
1678                if let Some(project_id) = self.remote_id() {
1679                    let request = self.client.request(proto::UpdateBuffer {
1680                        project_id,
1681                        buffer_id: buffer.read(cx).remote_id(),
1682                        operations: vec![language::proto::serialize_operation(operation)],
1683                    });
1684                    cx.background().spawn(request).detach_and_log_err(cx);
1685                }
1686            }
1687            BufferEvent::Edited { .. } => {
1688                let language_server = self
1689                    .language_server_for_buffer(buffer.read(cx), cx)
1690                    .map(|(_, server)| server.clone())?;
1691                let buffer = buffer.read(cx);
1692                let file = File::from_dyn(buffer.file())?;
1693                let abs_path = file.as_local()?.abs_path(cx);
1694                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1695                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1696                let (version, prev_snapshot) = buffer_snapshots.last()?;
1697                let next_snapshot = buffer.text_snapshot();
1698                let next_version = version + 1;
1699
1700                let content_changes = buffer
1701                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1702                    .map(|edit| {
1703                        let edit_start = edit.new.start.0;
1704                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1705                        let new_text = next_snapshot
1706                            .text_for_range(edit.new.start.1..edit.new.end.1)
1707                            .collect();
1708                        lsp::TextDocumentContentChangeEvent {
1709                            range: Some(lsp::Range::new(
1710                                point_to_lsp(edit_start),
1711                                point_to_lsp(edit_end),
1712                            )),
1713                            range_length: None,
1714                            text: new_text,
1715                        }
1716                    })
1717                    .collect();
1718
1719                buffer_snapshots.push((next_version, next_snapshot));
1720
1721                language_server
1722                    .notify::<lsp::notification::DidChangeTextDocument>(
1723                        lsp::DidChangeTextDocumentParams {
1724                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1725                                uri,
1726                                next_version,
1727                            ),
1728                            content_changes,
1729                        },
1730                    )
1731                    .log_err();
1732            }
1733            BufferEvent::Saved => {
1734                let file = File::from_dyn(buffer.read(cx).file())?;
1735                let worktree_id = file.worktree_id(cx);
1736                let abs_path = file.as_local()?.abs_path(cx);
1737                let text_document = lsp::TextDocumentIdentifier {
1738                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1739                };
1740
1741                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1742                    server
1743                        .notify::<lsp::notification::DidSaveTextDocument>(
1744                            lsp::DidSaveTextDocumentParams {
1745                                text_document: text_document.clone(),
1746                                text: None,
1747                            },
1748                        )
1749                        .log_err();
1750                }
1751
1752                let language_server_id = self.language_server_id_for_buffer(buffer.read(cx), cx)?;
1753                if let Some(LanguageServerState::Running {
1754                    adapter,
1755                    simulate_disk_based_diagnostics_completion,
1756                    ..
1757                }) = self.language_servers.get_mut(&language_server_id)
1758                {
1759                    // After saving a buffer using a language server that doesn't provide
1760                    // a disk-based progress token, kick off a timer that will reset every
1761                    // time the buffer is saved. If the timer eventually fires, simulate
1762                    // disk-based diagnostics being finished so that other pieces of UI
1763                    // (e.g., project diagnostics view, diagnostic status bar) can update.
1764                    // We don't emit an event right away because the language server might take
1765                    // some time to publish diagnostics.
1766                    if adapter.disk_based_diagnostics_progress_token.is_none() {
1767                        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
1768
1769                        let task = cx.spawn_weak(|this, mut cx| async move {
1770                            cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
1771                            if let Some(this) = this.upgrade(&cx) {
1772                                this.update(&mut cx, |this, cx | {
1773                                    this.disk_based_diagnostics_finished(language_server_id, cx);
1774                                    this.broadcast_language_server_update(
1775                                        language_server_id,
1776                                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1777                                            proto::LspDiskBasedDiagnosticsUpdated {},
1778                                        ),
1779                                    );
1780                                });
1781                            }
1782                        });
1783                        *simulate_disk_based_diagnostics_completion = Some(task);
1784                    }
1785                }
1786            }
1787            _ => {}
1788        }
1789
1790        None
1791    }
1792
1793    fn language_servers_for_worktree(
1794        &self,
1795        worktree_id: WorktreeId,
1796    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1797        self.language_server_ids
1798            .iter()
1799            .filter_map(move |((language_server_worktree_id, _), id)| {
1800                if *language_server_worktree_id == worktree_id {
1801                    if let Some(LanguageServerState::Running {
1802                        adapter,
1803                        language,
1804                        server,
1805                        ..
1806                    }) = self.language_servers.get(id)
1807                    {
1808                        return Some((adapter, language, server));
1809                    }
1810                }
1811                None
1812            })
1813    }
1814
1815    fn maintain_buffer_languages(
1816        languages: &LanguageRegistry,
1817        cx: &mut ModelContext<Project>,
1818    ) -> Task<()> {
1819        let mut subscription = languages.subscribe();
1820        cx.spawn_weak(|project, mut cx| async move {
1821            while let Some(()) = subscription.next().await {
1822                if let Some(project) = project.upgrade(&cx) {
1823                    project.update(&mut cx, |project, cx| {
1824                        let mut plain_text_buffers = Vec::new();
1825                        let mut buffers_with_unknown_injections = Vec::new();
1826                        for buffer in project.opened_buffers.values() {
1827                            if let Some(handle) = buffer.upgrade(cx) {
1828                                let buffer = &handle.read(cx);
1829                                if buffer.language().is_none()
1830                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
1831                                {
1832                                    plain_text_buffers.push(handle);
1833                                } else if buffer.contains_unknown_injections() {
1834                                    buffers_with_unknown_injections.push(handle);
1835                                }
1836                            }
1837                        }
1838
1839                        for buffer in plain_text_buffers {
1840                            project.assign_language_to_buffer(&buffer, cx);
1841                            project.register_buffer_with_language_server(&buffer, cx);
1842                        }
1843
1844                        for buffer in buffers_with_unknown_injections {
1845                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
1846                        }
1847                    });
1848                }
1849            }
1850        })
1851    }
1852
1853    fn assign_language_to_buffer(
1854        &mut self,
1855        buffer: &ModelHandle<Buffer>,
1856        cx: &mut ModelContext<Self>,
1857    ) -> Option<()> {
1858        // If the buffer has a language, set it and start the language server if we haven't already.
1859        let full_path = buffer.read(cx).file()?.full_path(cx);
1860        let new_language = self.languages.language_for_path(&full_path)?;
1861        buffer.update(cx, |buffer, cx| {
1862            if buffer.language().map_or(true, |old_language| {
1863                !Arc::ptr_eq(old_language, &new_language)
1864            }) {
1865                buffer.set_language(Some(new_language.clone()), cx);
1866            }
1867        });
1868
1869        let file = File::from_dyn(buffer.read(cx).file())?;
1870        let worktree = file.worktree.read(cx).as_local()?;
1871        let worktree_id = worktree.id();
1872        let worktree_abs_path = worktree.abs_path().clone();
1873        self.start_language_server(worktree_id, worktree_abs_path, new_language, cx);
1874
1875        None
1876    }
1877
1878    fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
1879        use serde_json::Value;
1880
1881        match (source, target) {
1882            (Value::Object(source), Value::Object(target)) => {
1883                for (key, value) in source {
1884                    if let Some(target) = target.get_mut(&key) {
1885                        Self::merge_json_value_into(value, target);
1886                    } else {
1887                        target.insert(key.clone(), value);
1888                    }
1889                }
1890            }
1891
1892            (source, target) => *target = source,
1893        }
1894    }
1895
1896    fn start_language_server(
1897        &mut self,
1898        worktree_id: WorktreeId,
1899        worktree_path: Arc<Path>,
1900        language: Arc<Language>,
1901        cx: &mut ModelContext<Self>,
1902    ) {
1903        if !cx
1904            .global::<Settings>()
1905            .enable_language_server(Some(&language.name()))
1906        {
1907            return;
1908        }
1909
1910        let adapter = if let Some(adapter) = language.lsp_adapter() {
1911            adapter
1912        } else {
1913            return;
1914        };
1915        let key = (worktree_id, adapter.name.clone());
1916
1917        let mut initialization_options = adapter.initialization_options.clone();
1918
1919        let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
1920        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
1921        match (&mut initialization_options, override_options) {
1922            (Some(initialization_options), Some(override_options)) => {
1923                Self::merge_json_value_into(override_options, initialization_options);
1924            }
1925
1926            (None, override_options) => initialization_options = override_options,
1927
1928            _ => {}
1929        }
1930
1931        self.language_server_ids
1932            .entry(key.clone())
1933            .or_insert_with(|| {
1934                let server_id = post_inc(&mut self.next_language_server_id);
1935                let language_server = self.languages.start_language_server(
1936                    server_id,
1937                    language.clone(),
1938                    worktree_path,
1939                    self.client.http_client(),
1940                    cx,
1941                );
1942                self.language_servers.insert(
1943                    server_id,
1944                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
1945                        let language_server = language_server?.await.log_err()?;
1946                        let language_server = language_server
1947                            .initialize(initialization_options)
1948                            .await
1949                            .log_err()?;
1950                        let this = this.upgrade(&cx)?;
1951
1952                        language_server
1953                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
1954                                let this = this.downgrade();
1955                                let adapter = adapter.clone();
1956                                move |mut params, cx| {
1957                                    let this = this;
1958                                    let adapter = adapter.clone();
1959                                    cx.spawn(|mut cx| async move {
1960                                        adapter.process_diagnostics(&mut params).await;
1961                                        if let Some(this) = this.upgrade(&cx) {
1962                                            this.update(&mut cx, |this, cx| {
1963                                                this.update_diagnostics(
1964                                                    server_id,
1965                                                    params,
1966                                                    &adapter.disk_based_diagnostic_sources,
1967                                                    cx,
1968                                                )
1969                                                .log_err();
1970                                            });
1971                                        }
1972                                    })
1973                                    .detach();
1974                                }
1975                            })
1976                            .detach();
1977
1978                        language_server
1979                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1980                                let settings = this.read_with(&cx, |this, _| {
1981                                    this.language_server_settings.clone()
1982                                });
1983                                move |params, _| {
1984                                    let settings = settings.lock().clone();
1985                                    async move {
1986                                        Ok(params
1987                                            .items
1988                                            .into_iter()
1989                                            .map(|item| {
1990                                                if let Some(section) = &item.section {
1991                                                    settings
1992                                                        .get(section)
1993                                                        .cloned()
1994                                                        .unwrap_or(serde_json::Value::Null)
1995                                                } else {
1996                                                    settings.clone()
1997                                                }
1998                                            })
1999                                            .collect())
2000                                    }
2001                                }
2002                            })
2003                            .detach();
2004
2005                        // Even though we don't have handling for these requests, respond to them to
2006                        // avoid stalling any language server like `gopls` which waits for a response
2007                        // to these requests when initializing.
2008                        language_server
2009                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2010                                let this = this.downgrade();
2011                                move |params, mut cx| async move {
2012                                    if let Some(this) = this.upgrade(&cx) {
2013                                        this.update(&mut cx, |this, _| {
2014                                            if let Some(status) =
2015                                                this.language_server_statuses.get_mut(&server_id)
2016                                            {
2017                                                if let lsp::NumberOrString::String(token) =
2018                                                    params.token
2019                                                {
2020                                                    status.progress_tokens.insert(token);
2021                                                }
2022                                            }
2023                                        });
2024                                    }
2025                                    Ok(())
2026                                }
2027                            })
2028                            .detach();
2029                        language_server
2030                            .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2031                                Ok(())
2032                            })
2033                            .detach();
2034
2035                        language_server
2036                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2037                                let this = this.downgrade();
2038                                let adapter = adapter.clone();
2039                                let language_server = language_server.clone();
2040                                move |params, cx| {
2041                                    Self::on_lsp_workspace_edit(
2042                                        this,
2043                                        params,
2044                                        server_id,
2045                                        adapter.clone(),
2046                                        language_server.clone(),
2047                                        cx,
2048                                    )
2049                                }
2050                            })
2051                            .detach();
2052
2053                        let disk_based_diagnostics_progress_token =
2054                            adapter.disk_based_diagnostics_progress_token.clone();
2055
2056                        language_server
2057                            .on_notification::<lsp::notification::Progress, _>({
2058                                let this = this.downgrade();
2059                                move |params, mut cx| {
2060                                    if let Some(this) = this.upgrade(&cx) {
2061                                        this.update(&mut cx, |this, cx| {
2062                                            this.on_lsp_progress(
2063                                                params,
2064                                                server_id,
2065                                                disk_based_diagnostics_progress_token.clone(),
2066                                                cx,
2067                                            );
2068                                        });
2069                                    }
2070                                }
2071                            })
2072                            .detach();
2073
2074                        this.update(&mut cx, |this, cx| {
2075                            // If the language server for this key doesn't match the server id, don't store the
2076                            // server. Which will cause it to be dropped, killing the process
2077                            if this
2078                                .language_server_ids
2079                                .get(&key)
2080                                .map(|id| id != &server_id)
2081                                .unwrap_or(false)
2082                            {
2083                                return None;
2084                            }
2085
2086                            // Update language_servers collection with Running variant of LanguageServerState
2087                            // indicating that the server is up and running and ready
2088                            this.language_servers.insert(
2089                                server_id,
2090                                LanguageServerState::Running {
2091                                    adapter: adapter.clone(),
2092                                    language,
2093                                    server: language_server.clone(),
2094                                    simulate_disk_based_diagnostics_completion: None,
2095                                },
2096                            );
2097                            this.language_server_statuses.insert(
2098                                server_id,
2099                                LanguageServerStatus {
2100                                    name: language_server.name().to_string(),
2101                                    pending_work: Default::default(),
2102                                    has_pending_diagnostic_updates: false,
2103                                    progress_tokens: Default::default(),
2104                                },
2105                            );
2106                            language_server
2107                                .notify::<lsp::notification::DidChangeConfiguration>(
2108                                    lsp::DidChangeConfigurationParams {
2109                                        settings: this.language_server_settings.lock().clone(),
2110                                    },
2111                                )
2112                                .ok();
2113
2114                            if let Some(project_id) = this.remote_id() {
2115                                this.client
2116                                    .send(proto::StartLanguageServer {
2117                                        project_id,
2118                                        server: Some(proto::LanguageServer {
2119                                            id: server_id as u64,
2120                                            name: language_server.name().to_string(),
2121                                        }),
2122                                    })
2123                                    .log_err();
2124                            }
2125
2126                            // Tell the language server about every open buffer in the worktree that matches the language.
2127                            for buffer in this.opened_buffers.values() {
2128                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2129                                    let buffer = buffer_handle.read(cx);
2130                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2131                                        file
2132                                    } else {
2133                                        continue;
2134                                    };
2135                                    let language = if let Some(language) = buffer.language() {
2136                                        language
2137                                    } else {
2138                                        continue;
2139                                    };
2140                                    if file.worktree.read(cx).id() != key.0
2141                                        || language.lsp_adapter().map(|a| a.name.clone())
2142                                            != Some(key.1.clone())
2143                                    {
2144                                        continue;
2145                                    }
2146
2147                                    let file = file.as_local()?;
2148                                    let versions = this
2149                                        .buffer_snapshots
2150                                        .entry(buffer.remote_id())
2151                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2152
2153                                    let (version, initial_snapshot) = versions.last().unwrap();
2154                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2155                                    language_server
2156                                        .notify::<lsp::notification::DidOpenTextDocument>(
2157                                            lsp::DidOpenTextDocumentParams {
2158                                                text_document: lsp::TextDocumentItem::new(
2159                                                    uri,
2160                                                    adapter
2161                                                        .language_ids
2162                                                        .get(language.name().as_ref())
2163                                                        .cloned()
2164                                                        .unwrap_or_default(),
2165                                                    *version,
2166                                                    initial_snapshot.text(),
2167                                                ),
2168                                            },
2169                                        )
2170                                        .log_err()?;
2171                                    buffer_handle.update(cx, |buffer, cx| {
2172                                        buffer.set_completion_triggers(
2173                                            language_server
2174                                                .capabilities()
2175                                                .completion_provider
2176                                                .as_ref()
2177                                                .and_then(|provider| {
2178                                                    provider.trigger_characters.clone()
2179                                                })
2180                                                .unwrap_or_default(),
2181                                            cx,
2182                                        )
2183                                    });
2184                                }
2185                            }
2186
2187                            cx.notify();
2188                            Some(language_server)
2189                        })
2190                    })),
2191                );
2192
2193                server_id
2194            });
2195    }
2196
2197    // Returns a list of all of the worktrees which no longer have a language server and the root path
2198    // for the stopped server
2199    fn stop_language_server(
2200        &mut self,
2201        worktree_id: WorktreeId,
2202        adapter_name: LanguageServerName,
2203        cx: &mut ModelContext<Self>,
2204    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2205        let key = (worktree_id, adapter_name);
2206        if let Some(server_id) = self.language_server_ids.remove(&key) {
2207            // Remove other entries for this language server as well
2208            let mut orphaned_worktrees = vec![worktree_id];
2209            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2210            for other_key in other_keys {
2211                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2212                    self.language_server_ids.remove(&other_key);
2213                    orphaned_worktrees.push(other_key.0);
2214                }
2215            }
2216
2217            self.language_server_statuses.remove(&server_id);
2218            cx.notify();
2219
2220            let server_state = self.language_servers.remove(&server_id);
2221            cx.spawn_weak(|this, mut cx| async move {
2222                let mut root_path = None;
2223
2224                let server = match server_state {
2225                    Some(LanguageServerState::Starting(started_language_server)) => {
2226                        started_language_server.await
2227                    }
2228                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2229                    None => None,
2230                };
2231
2232                if let Some(server) = server {
2233                    root_path = Some(server.root_path().clone());
2234                    if let Some(shutdown) = server.shutdown() {
2235                        shutdown.await;
2236                    }
2237                }
2238
2239                if let Some(this) = this.upgrade(&cx) {
2240                    this.update(&mut cx, |this, cx| {
2241                        this.language_server_statuses.remove(&server_id);
2242                        cx.notify();
2243                    });
2244                }
2245
2246                (root_path, orphaned_worktrees)
2247            })
2248        } else {
2249            Task::ready((None, Vec::new()))
2250        }
2251    }
2252
2253    pub fn restart_language_servers_for_buffers(
2254        &mut self,
2255        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2256        cx: &mut ModelContext<Self>,
2257    ) -> Option<()> {
2258        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2259            .into_iter()
2260            .filter_map(|buffer| {
2261                let file = File::from_dyn(buffer.read(cx).file())?;
2262                let worktree = file.worktree.read(cx).as_local()?;
2263                let worktree_id = worktree.id();
2264                let worktree_abs_path = worktree.abs_path().clone();
2265                let full_path = file.full_path(cx);
2266                Some((worktree_id, worktree_abs_path, full_path))
2267            })
2268            .collect();
2269        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2270            let language = self.languages.language_for_path(&full_path)?;
2271            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2272        }
2273
2274        None
2275    }
2276
2277    fn restart_language_server(
2278        &mut self,
2279        worktree_id: WorktreeId,
2280        fallback_path: Arc<Path>,
2281        language: Arc<Language>,
2282        cx: &mut ModelContext<Self>,
2283    ) {
2284        let adapter = if let Some(adapter) = language.lsp_adapter() {
2285            adapter
2286        } else {
2287            return;
2288        };
2289
2290        let server_name = adapter.name.clone();
2291        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2292        cx.spawn_weak(|this, mut cx| async move {
2293            let (original_root_path, orphaned_worktrees) = stop.await;
2294            if let Some(this) = this.upgrade(&cx) {
2295                this.update(&mut cx, |this, cx| {
2296                    // Attempt to restart using original server path. Fallback to passed in
2297                    // path if we could not retrieve the root path
2298                    let root_path = original_root_path
2299                        .map(|path_buf| Arc::from(path_buf.as_path()))
2300                        .unwrap_or(fallback_path);
2301
2302                    this.start_language_server(worktree_id, root_path, language, cx);
2303
2304                    // Lookup new server id and set it for each of the orphaned worktrees
2305                    if let Some(new_server_id) = this
2306                        .language_server_ids
2307                        .get(&(worktree_id, server_name.clone()))
2308                        .cloned()
2309                    {
2310                        for orphaned_worktree in orphaned_worktrees {
2311                            this.language_server_ids
2312                                .insert((orphaned_worktree, server_name.clone()), new_server_id);
2313                        }
2314                    }
2315                });
2316            }
2317        })
2318        .detach();
2319    }
2320
2321    fn on_lsp_progress(
2322        &mut self,
2323        progress: lsp::ProgressParams,
2324        server_id: usize,
2325        disk_based_diagnostics_progress_token: Option<String>,
2326        cx: &mut ModelContext<Self>,
2327    ) {
2328        let token = match progress.token {
2329            lsp::NumberOrString::String(token) => token,
2330            lsp::NumberOrString::Number(token) => {
2331                log::info!("skipping numeric progress token {}", token);
2332                return;
2333            }
2334        };
2335        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2336        let language_server_status =
2337            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2338                status
2339            } else {
2340                return;
2341            };
2342
2343        if !language_server_status.progress_tokens.contains(&token) {
2344            return;
2345        }
2346
2347        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2348            .as_ref()
2349            .map_or(false, |disk_based_token| {
2350                token.starts_with(disk_based_token)
2351            });
2352
2353        match progress {
2354            lsp::WorkDoneProgress::Begin(report) => {
2355                if is_disk_based_diagnostics_progress {
2356                    language_server_status.has_pending_diagnostic_updates = true;
2357                    self.disk_based_diagnostics_started(server_id, cx);
2358                    self.broadcast_language_server_update(
2359                        server_id,
2360                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2361                            proto::LspDiskBasedDiagnosticsUpdating {},
2362                        ),
2363                    );
2364                } else {
2365                    self.on_lsp_work_start(
2366                        server_id,
2367                        token.clone(),
2368                        LanguageServerProgress {
2369                            message: report.message.clone(),
2370                            percentage: report.percentage.map(|p| p as usize),
2371                            last_update_at: Instant::now(),
2372                        },
2373                        cx,
2374                    );
2375                    self.broadcast_language_server_update(
2376                        server_id,
2377                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2378                            token,
2379                            message: report.message,
2380                            percentage: report.percentage.map(|p| p as u32),
2381                        }),
2382                    );
2383                }
2384            }
2385            lsp::WorkDoneProgress::Report(report) => {
2386                if !is_disk_based_diagnostics_progress {
2387                    self.on_lsp_work_progress(
2388                        server_id,
2389                        token.clone(),
2390                        LanguageServerProgress {
2391                            message: report.message.clone(),
2392                            percentage: report.percentage.map(|p| p as usize),
2393                            last_update_at: Instant::now(),
2394                        },
2395                        cx,
2396                    );
2397                    self.broadcast_language_server_update(
2398                        server_id,
2399                        proto::update_language_server::Variant::WorkProgress(
2400                            proto::LspWorkProgress {
2401                                token,
2402                                message: report.message,
2403                                percentage: report.percentage.map(|p| p as u32),
2404                            },
2405                        ),
2406                    );
2407                }
2408            }
2409            lsp::WorkDoneProgress::End(_) => {
2410                language_server_status.progress_tokens.remove(&token);
2411
2412                if is_disk_based_diagnostics_progress {
2413                    language_server_status.has_pending_diagnostic_updates = false;
2414                    self.disk_based_diagnostics_finished(server_id, cx);
2415                    self.broadcast_language_server_update(
2416                        server_id,
2417                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2418                            proto::LspDiskBasedDiagnosticsUpdated {},
2419                        ),
2420                    );
2421                } else {
2422                    self.on_lsp_work_end(server_id, token.clone(), cx);
2423                    self.broadcast_language_server_update(
2424                        server_id,
2425                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2426                            token,
2427                        }),
2428                    );
2429                }
2430            }
2431        }
2432    }
2433
2434    fn on_lsp_work_start(
2435        &mut self,
2436        language_server_id: usize,
2437        token: String,
2438        progress: LanguageServerProgress,
2439        cx: &mut ModelContext<Self>,
2440    ) {
2441        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2442            status.pending_work.insert(token, progress);
2443            cx.notify();
2444        }
2445    }
2446
2447    fn on_lsp_work_progress(
2448        &mut self,
2449        language_server_id: usize,
2450        token: String,
2451        progress: LanguageServerProgress,
2452        cx: &mut ModelContext<Self>,
2453    ) {
2454        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2455            let entry = status
2456                .pending_work
2457                .entry(token)
2458                .or_insert(LanguageServerProgress {
2459                    message: Default::default(),
2460                    percentage: Default::default(),
2461                    last_update_at: progress.last_update_at,
2462                });
2463            if progress.message.is_some() {
2464                entry.message = progress.message;
2465            }
2466            if progress.percentage.is_some() {
2467                entry.percentage = progress.percentage;
2468            }
2469            entry.last_update_at = progress.last_update_at;
2470            cx.notify();
2471        }
2472    }
2473
2474    fn on_lsp_work_end(
2475        &mut self,
2476        language_server_id: usize,
2477        token: String,
2478        cx: &mut ModelContext<Self>,
2479    ) {
2480        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2481            status.pending_work.remove(&token);
2482            cx.notify();
2483        }
2484    }
2485
2486    async fn on_lsp_workspace_edit(
2487        this: WeakModelHandle<Self>,
2488        params: lsp::ApplyWorkspaceEditParams,
2489        server_id: usize,
2490        adapter: Arc<CachedLspAdapter>,
2491        language_server: Arc<LanguageServer>,
2492        mut cx: AsyncAppContext,
2493    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2494        let this = this
2495            .upgrade(&cx)
2496            .ok_or_else(|| anyhow!("project project closed"))?;
2497        let transaction = Self::deserialize_workspace_edit(
2498            this.clone(),
2499            params.edit,
2500            true,
2501            adapter.clone(),
2502            language_server.clone(),
2503            &mut cx,
2504        )
2505        .await
2506        .log_err();
2507        this.update(&mut cx, |this, _| {
2508            if let Some(transaction) = transaction {
2509                this.last_workspace_edits_by_language_server
2510                    .insert(server_id, transaction);
2511            }
2512        });
2513        Ok(lsp::ApplyWorkspaceEditResponse {
2514            applied: true,
2515            failed_change: None,
2516            failure_reason: None,
2517        })
2518    }
2519
2520    fn broadcast_language_server_update(
2521        &self,
2522        language_server_id: usize,
2523        event: proto::update_language_server::Variant,
2524    ) {
2525        if let Some(project_id) = self.remote_id() {
2526            self.client
2527                .send(proto::UpdateLanguageServer {
2528                    project_id,
2529                    language_server_id: language_server_id as u64,
2530                    variant: Some(event),
2531                })
2532                .log_err();
2533        }
2534    }
2535
2536    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2537        for server_state in self.language_servers.values() {
2538            if let LanguageServerState::Running { server, .. } = server_state {
2539                server
2540                    .notify::<lsp::notification::DidChangeConfiguration>(
2541                        lsp::DidChangeConfigurationParams {
2542                            settings: settings.clone(),
2543                        },
2544                    )
2545                    .ok();
2546            }
2547        }
2548        *self.language_server_settings.lock() = settings;
2549    }
2550
2551    pub fn language_server_statuses(
2552        &self,
2553    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2554        self.language_server_statuses.values()
2555    }
2556
2557    pub fn update_diagnostics(
2558        &mut self,
2559        language_server_id: usize,
2560        params: lsp::PublishDiagnosticsParams,
2561        disk_based_sources: &[String],
2562        cx: &mut ModelContext<Self>,
2563    ) -> Result<()> {
2564        let abs_path = params
2565            .uri
2566            .to_file_path()
2567            .map_err(|_| anyhow!("URI is not a file"))?;
2568        let mut diagnostics = Vec::default();
2569        let mut primary_diagnostic_group_ids = HashMap::default();
2570        let mut sources_by_group_id = HashMap::default();
2571        let mut supporting_diagnostics = HashMap::default();
2572        for diagnostic in &params.diagnostics {
2573            let source = diagnostic.source.as_ref();
2574            let code = diagnostic.code.as_ref().map(|code| match code {
2575                lsp::NumberOrString::Number(code) => code.to_string(),
2576                lsp::NumberOrString::String(code) => code.clone(),
2577            });
2578            let range = range_from_lsp(diagnostic.range);
2579            let is_supporting = diagnostic
2580                .related_information
2581                .as_ref()
2582                .map_or(false, |infos| {
2583                    infos.iter().any(|info| {
2584                        primary_diagnostic_group_ids.contains_key(&(
2585                            source,
2586                            code.clone(),
2587                            range_from_lsp(info.location.range),
2588                        ))
2589                    })
2590                });
2591
2592            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2593                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2594            });
2595
2596            if is_supporting {
2597                supporting_diagnostics.insert(
2598                    (source, code.clone(), range),
2599                    (diagnostic.severity, is_unnecessary),
2600                );
2601            } else {
2602                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2603                let is_disk_based =
2604                    source.map_or(false, |source| disk_based_sources.contains(source));
2605
2606                sources_by_group_id.insert(group_id, source);
2607                primary_diagnostic_group_ids
2608                    .insert((source, code.clone(), range.clone()), group_id);
2609
2610                diagnostics.push(DiagnosticEntry {
2611                    range,
2612                    diagnostic: Diagnostic {
2613                        code: code.clone(),
2614                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2615                        message: diagnostic.message.clone(),
2616                        group_id,
2617                        is_primary: true,
2618                        is_valid: true,
2619                        is_disk_based,
2620                        is_unnecessary,
2621                    },
2622                });
2623                if let Some(infos) = &diagnostic.related_information {
2624                    for info in infos {
2625                        if info.location.uri == params.uri && !info.message.is_empty() {
2626                            let range = range_from_lsp(info.location.range);
2627                            diagnostics.push(DiagnosticEntry {
2628                                range,
2629                                diagnostic: Diagnostic {
2630                                    code: code.clone(),
2631                                    severity: DiagnosticSeverity::INFORMATION,
2632                                    message: info.message.clone(),
2633                                    group_id,
2634                                    is_primary: false,
2635                                    is_valid: true,
2636                                    is_disk_based,
2637                                    is_unnecessary: false,
2638                                },
2639                            });
2640                        }
2641                    }
2642                }
2643            }
2644        }
2645
2646        for entry in &mut diagnostics {
2647            let diagnostic = &mut entry.diagnostic;
2648            if !diagnostic.is_primary {
2649                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2650                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2651                    source,
2652                    diagnostic.code.clone(),
2653                    entry.range.clone(),
2654                )) {
2655                    if let Some(severity) = severity {
2656                        diagnostic.severity = severity;
2657                    }
2658                    diagnostic.is_unnecessary = is_unnecessary;
2659                }
2660            }
2661        }
2662
2663        self.update_diagnostic_entries(
2664            language_server_id,
2665            abs_path,
2666            params.version,
2667            diagnostics,
2668            cx,
2669        )?;
2670        Ok(())
2671    }
2672
2673    pub fn update_diagnostic_entries(
2674        &mut self,
2675        language_server_id: usize,
2676        abs_path: PathBuf,
2677        version: Option<i32>,
2678        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2679        cx: &mut ModelContext<Project>,
2680    ) -> Result<(), anyhow::Error> {
2681        let (worktree, relative_path) = self
2682            .find_local_worktree(&abs_path, cx)
2683            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2684
2685        let project_path = ProjectPath {
2686            worktree_id: worktree.read(cx).id(),
2687            path: relative_path.into(),
2688        };
2689
2690        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2691            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2692        }
2693
2694        let updated = worktree.update(cx, |worktree, cx| {
2695            worktree
2696                .as_local_mut()
2697                .ok_or_else(|| anyhow!("not a local worktree"))?
2698                .update_diagnostics(
2699                    language_server_id,
2700                    project_path.path.clone(),
2701                    diagnostics,
2702                    cx,
2703                )
2704        })?;
2705        if updated {
2706            cx.emit(Event::DiagnosticsUpdated {
2707                language_server_id,
2708                path: project_path,
2709            });
2710        }
2711        Ok(())
2712    }
2713
2714    fn update_buffer_diagnostics(
2715        &mut self,
2716        buffer: &ModelHandle<Buffer>,
2717        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2718        version: Option<i32>,
2719        cx: &mut ModelContext<Self>,
2720    ) -> Result<()> {
2721        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2722            Ordering::Equal
2723                .then_with(|| b.is_primary.cmp(&a.is_primary))
2724                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2725                .then_with(|| a.severity.cmp(&b.severity))
2726                .then_with(|| a.message.cmp(&b.message))
2727        }
2728
2729        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2730
2731        diagnostics.sort_unstable_by(|a, b| {
2732            Ordering::Equal
2733                .then_with(|| a.range.start.cmp(&b.range.start))
2734                .then_with(|| b.range.end.cmp(&a.range.end))
2735                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2736        });
2737
2738        let mut sanitized_diagnostics = Vec::new();
2739        let edits_since_save = Patch::new(
2740            snapshot
2741                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
2742                .collect(),
2743        );
2744        for entry in diagnostics {
2745            let start;
2746            let end;
2747            if entry.diagnostic.is_disk_based {
2748                // Some diagnostics are based on files on disk instead of buffers'
2749                // current contents. Adjust these diagnostics' ranges to reflect
2750                // any unsaved edits.
2751                start = edits_since_save.old_to_new(entry.range.start);
2752                end = edits_since_save.old_to_new(entry.range.end);
2753            } else {
2754                start = entry.range.start;
2755                end = entry.range.end;
2756            }
2757
2758            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2759                ..snapshot.clip_point_utf16(end, Bias::Right);
2760
2761            // Expand empty ranges by one codepoint
2762            if range.start == range.end {
2763                // This will be go to the next boundary when being clipped
2764                range.end.column += 1;
2765                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2766                if range.start == range.end && range.end.column > 0 {
2767                    range.start.column -= 1;
2768                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
2769                }
2770            }
2771
2772            sanitized_diagnostics.push(DiagnosticEntry {
2773                range,
2774                diagnostic: entry.diagnostic,
2775            });
2776        }
2777        drop(edits_since_save);
2778
2779        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2780        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2781        Ok(())
2782    }
2783
2784    pub fn reload_buffers(
2785        &self,
2786        buffers: HashSet<ModelHandle<Buffer>>,
2787        push_to_history: bool,
2788        cx: &mut ModelContext<Self>,
2789    ) -> Task<Result<ProjectTransaction>> {
2790        let mut local_buffers = Vec::new();
2791        let mut remote_buffers = None;
2792        for buffer_handle in buffers {
2793            let buffer = buffer_handle.read(cx);
2794            if buffer.is_dirty() {
2795                if let Some(file) = File::from_dyn(buffer.file()) {
2796                    if file.is_local() {
2797                        local_buffers.push(buffer_handle);
2798                    } else {
2799                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2800                    }
2801                }
2802            }
2803        }
2804
2805        let remote_buffers = self.remote_id().zip(remote_buffers);
2806        let client = self.client.clone();
2807
2808        cx.spawn(|this, mut cx| async move {
2809            let mut project_transaction = ProjectTransaction::default();
2810
2811            if let Some((project_id, remote_buffers)) = remote_buffers {
2812                let response = client
2813                    .request(proto::ReloadBuffers {
2814                        project_id,
2815                        buffer_ids: remote_buffers
2816                            .iter()
2817                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2818                            .collect(),
2819                    })
2820                    .await?
2821                    .transaction
2822                    .ok_or_else(|| anyhow!("missing transaction"))?;
2823                project_transaction = this
2824                    .update(&mut cx, |this, cx| {
2825                        this.deserialize_project_transaction(response, push_to_history, cx)
2826                    })
2827                    .await?;
2828            }
2829
2830            for buffer in local_buffers {
2831                let transaction = buffer
2832                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2833                    .await?;
2834                buffer.update(&mut cx, |buffer, cx| {
2835                    if let Some(transaction) = transaction {
2836                        if !push_to_history {
2837                            buffer.forget_transaction(transaction.id);
2838                        }
2839                        project_transaction.0.insert(cx.handle(), transaction);
2840                    }
2841                });
2842            }
2843
2844            Ok(project_transaction)
2845        })
2846    }
2847
2848    pub fn format(
2849        &self,
2850        buffers: HashSet<ModelHandle<Buffer>>,
2851        push_to_history: bool,
2852        trigger: FormatTrigger,
2853        cx: &mut ModelContext<Project>,
2854    ) -> Task<Result<ProjectTransaction>> {
2855        if self.is_local() {
2856            let mut buffers_with_paths_and_servers = buffers
2857                .into_iter()
2858                .filter_map(|buffer_handle| {
2859                    let buffer = buffer_handle.read(cx);
2860                    let file = File::from_dyn(buffer.file())?;
2861                    let buffer_abs_path = file.as_local()?.abs_path(cx);
2862                    let (_, server) = self.language_server_for_buffer(buffer, cx)?;
2863                    Some((buffer_handle, buffer_abs_path, server.clone()))
2864                })
2865                .collect::<Vec<_>>();
2866
2867            cx.spawn(|this, mut cx| async move {
2868                // Do not allow multiple concurrent formatting requests for the
2869                // same buffer.
2870                this.update(&mut cx, |this, _| {
2871                    buffers_with_paths_and_servers
2872                        .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2873                });
2874
2875                let _cleanup = defer({
2876                    let this = this.clone();
2877                    let mut cx = cx.clone();
2878                    let local_buffers = &buffers_with_paths_and_servers;
2879                    move || {
2880                        this.update(&mut cx, |this, _| {
2881                            for (buffer, _, _) in local_buffers {
2882                                this.buffers_being_formatted.remove(&buffer.id());
2883                            }
2884                        });
2885                    }
2886                });
2887
2888                let mut project_transaction = ProjectTransaction::default();
2889                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
2890                    let (format_on_save, formatter, tab_size) =
2891                        buffer.read_with(&cx, |buffer, cx| {
2892                            let settings = cx.global::<Settings>();
2893                            let language_name = buffer.language().map(|language| language.name());
2894                            (
2895                                settings.format_on_save(language_name.as_deref()),
2896                                settings.formatter(language_name.as_deref()),
2897                                settings.tab_size(language_name.as_deref()),
2898                            )
2899                        });
2900
2901                    let transaction = match (formatter, format_on_save) {
2902                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => continue,
2903
2904                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2905                        | (_, FormatOnSave::LanguageServer) => Self::format_via_lsp(
2906                            &this,
2907                            &buffer,
2908                            &buffer_abs_path,
2909                            &language_server,
2910                            tab_size,
2911                            &mut cx,
2912                        )
2913                        .await
2914                        .context("failed to format via language server")?,
2915
2916                        (
2917                            Formatter::External { command, arguments },
2918                            FormatOnSave::On | FormatOnSave::Off,
2919                        )
2920                        | (_, FormatOnSave::External { command, arguments }) => {
2921                            Self::format_via_external_command(
2922                                &buffer,
2923                                &buffer_abs_path,
2924                                &command,
2925                                &arguments,
2926                                &mut cx,
2927                            )
2928                            .await
2929                            .context(format!(
2930                                "failed to format via external command {:?}",
2931                                command
2932                            ))?
2933                        }
2934                    };
2935
2936                    if let Some(transaction) = transaction {
2937                        if !push_to_history {
2938                            buffer.update(&mut cx, |buffer, _| {
2939                                buffer.forget_transaction(transaction.id)
2940                            });
2941                        }
2942                        project_transaction.0.insert(buffer.clone(), transaction);
2943                    }
2944                }
2945
2946                Ok(project_transaction)
2947            })
2948        } else {
2949            let remote_id = self.remote_id();
2950            let client = self.client.clone();
2951            cx.spawn(|this, mut cx| async move {
2952                let mut project_transaction = ProjectTransaction::default();
2953                if let Some(project_id) = remote_id {
2954                    let response = client
2955                        .request(proto::FormatBuffers {
2956                            project_id,
2957                            trigger: trigger as i32,
2958                            buffer_ids: buffers
2959                                .iter()
2960                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2961                                .collect(),
2962                        })
2963                        .await?
2964                        .transaction
2965                        .ok_or_else(|| anyhow!("missing transaction"))?;
2966                    project_transaction = this
2967                        .update(&mut cx, |this, cx| {
2968                            this.deserialize_project_transaction(response, push_to_history, cx)
2969                        })
2970                        .await?;
2971                }
2972                Ok(project_transaction)
2973            })
2974        }
2975    }
2976
2977    async fn format_via_lsp(
2978        this: &ModelHandle<Self>,
2979        buffer: &ModelHandle<Buffer>,
2980        abs_path: &Path,
2981        language_server: &Arc<LanguageServer>,
2982        tab_size: NonZeroU32,
2983        cx: &mut AsyncAppContext,
2984    ) -> Result<Option<Transaction>> {
2985        let text_document =
2986            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
2987        let capabilities = &language_server.capabilities();
2988        let lsp_edits = if capabilities
2989            .document_formatting_provider
2990            .as_ref()
2991            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2992        {
2993            language_server
2994                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2995                    text_document,
2996                    options: lsp::FormattingOptions {
2997                        tab_size: tab_size.into(),
2998                        insert_spaces: true,
2999                        insert_final_newline: Some(true),
3000                        ..Default::default()
3001                    },
3002                    work_done_progress_params: Default::default(),
3003                })
3004                .await?
3005        } else if capabilities
3006            .document_range_formatting_provider
3007            .as_ref()
3008            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3009        {
3010            let buffer_start = lsp::Position::new(0, 0);
3011            let buffer_end =
3012                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3013            language_server
3014                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3015                    text_document,
3016                    range: lsp::Range::new(buffer_start, buffer_end),
3017                    options: lsp::FormattingOptions {
3018                        tab_size: tab_size.into(),
3019                        insert_spaces: true,
3020                        insert_final_newline: Some(true),
3021                        ..Default::default()
3022                    },
3023                    work_done_progress_params: Default::default(),
3024                })
3025                .await?
3026        } else {
3027            None
3028        };
3029
3030        if let Some(lsp_edits) = lsp_edits {
3031            let edits = this
3032                .update(cx, |this, cx| {
3033                    this.edits_from_lsp(buffer, lsp_edits, None, cx)
3034                })
3035                .await?;
3036            buffer.update(cx, |buffer, cx| {
3037                buffer.finalize_last_transaction();
3038                buffer.start_transaction();
3039                for (range, text) in edits {
3040                    buffer.edit([(range, text)], None, cx);
3041                }
3042                if buffer.end_transaction(cx).is_some() {
3043                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
3044                    Ok(Some(transaction))
3045                } else {
3046                    Ok(None)
3047                }
3048            })
3049        } else {
3050            Ok(None)
3051        }
3052    }
3053
3054    async fn format_via_external_command(
3055        buffer: &ModelHandle<Buffer>,
3056        buffer_abs_path: &Path,
3057        command: &str,
3058        arguments: &[String],
3059        cx: &mut AsyncAppContext,
3060    ) -> Result<Option<Transaction>> {
3061        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3062            let file = File::from_dyn(buffer.file())?;
3063            let worktree = file.worktree.read(cx).as_local()?;
3064            let mut worktree_path = worktree.abs_path().to_path_buf();
3065            if worktree.root_entry()?.is_file() {
3066                worktree_path.pop();
3067            }
3068            Some(worktree_path)
3069        });
3070
3071        if let Some(working_dir_path) = working_dir_path {
3072            let mut child =
3073                smol::process::Command::new(command)
3074                    .args(arguments.iter().map(|arg| {
3075                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3076                    }))
3077                    .current_dir(&working_dir_path)
3078                    .stdin(smol::process::Stdio::piped())
3079                    .stdout(smol::process::Stdio::piped())
3080                    .stderr(smol::process::Stdio::piped())
3081                    .spawn()?;
3082            let stdin = child
3083                .stdin
3084                .as_mut()
3085                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3086            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3087            for chunk in text.chunks() {
3088                stdin.write_all(chunk.as_bytes()).await?;
3089            }
3090            stdin.flush().await?;
3091
3092            let output = child.output().await?;
3093            if !output.status.success() {
3094                return Err(anyhow!(
3095                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3096                    output.status.code(),
3097                    String::from_utf8_lossy(&output.stdout),
3098                    String::from_utf8_lossy(&output.stderr),
3099                ));
3100            }
3101
3102            let stdout = String::from_utf8(output.stdout)?;
3103            let diff = buffer
3104                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3105                .await;
3106            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3107        } else {
3108            Ok(None)
3109        }
3110    }
3111
3112    pub fn definition<T: ToPointUtf16>(
3113        &self,
3114        buffer: &ModelHandle<Buffer>,
3115        position: T,
3116        cx: &mut ModelContext<Self>,
3117    ) -> Task<Result<Vec<LocationLink>>> {
3118        let position = position.to_point_utf16(buffer.read(cx));
3119        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3120    }
3121
3122    pub fn type_definition<T: ToPointUtf16>(
3123        &self,
3124        buffer: &ModelHandle<Buffer>,
3125        position: T,
3126        cx: &mut ModelContext<Self>,
3127    ) -> Task<Result<Vec<LocationLink>>> {
3128        let position = position.to_point_utf16(buffer.read(cx));
3129        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3130    }
3131
3132    pub fn references<T: ToPointUtf16>(
3133        &self,
3134        buffer: &ModelHandle<Buffer>,
3135        position: T,
3136        cx: &mut ModelContext<Self>,
3137    ) -> Task<Result<Vec<Location>>> {
3138        let position = position.to_point_utf16(buffer.read(cx));
3139        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3140    }
3141
3142    pub fn document_highlights<T: ToPointUtf16>(
3143        &self,
3144        buffer: &ModelHandle<Buffer>,
3145        position: T,
3146        cx: &mut ModelContext<Self>,
3147    ) -> Task<Result<Vec<DocumentHighlight>>> {
3148        let position = position.to_point_utf16(buffer.read(cx));
3149        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3150    }
3151
3152    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3153        if self.is_local() {
3154            let mut requests = Vec::new();
3155            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3156                let worktree_id = *worktree_id;
3157                if let Some(worktree) = self
3158                    .worktree_for_id(worktree_id, cx)
3159                    .and_then(|worktree| worktree.read(cx).as_local())
3160                {
3161                    if let Some(LanguageServerState::Running {
3162                        adapter,
3163                        language,
3164                        server,
3165                        ..
3166                    }) = self.language_servers.get(server_id)
3167                    {
3168                        let adapter = adapter.clone();
3169                        let language = language.clone();
3170                        let worktree_abs_path = worktree.abs_path().clone();
3171                        requests.push(
3172                            server
3173                                .request::<lsp::request::WorkspaceSymbol>(
3174                                    lsp::WorkspaceSymbolParams {
3175                                        query: query.to_string(),
3176                                        ..Default::default()
3177                                    },
3178                                )
3179                                .log_err()
3180                                .map(move |response| {
3181                                    (
3182                                        adapter,
3183                                        language,
3184                                        worktree_id,
3185                                        worktree_abs_path,
3186                                        response.unwrap_or_default(),
3187                                    )
3188                                }),
3189                        );
3190                    }
3191                }
3192            }
3193
3194            cx.spawn_weak(|this, cx| async move {
3195                let responses = futures::future::join_all(requests).await;
3196                let this = if let Some(this) = this.upgrade(&cx) {
3197                    this
3198                } else {
3199                    return Ok(Default::default());
3200                };
3201                let symbols = this.read_with(&cx, |this, cx| {
3202                    let mut symbols = Vec::new();
3203                    for (
3204                        adapter,
3205                        adapter_language,
3206                        source_worktree_id,
3207                        worktree_abs_path,
3208                        response,
3209                    ) in responses
3210                    {
3211                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3212                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3213                            let mut worktree_id = source_worktree_id;
3214                            let path;
3215                            if let Some((worktree, rel_path)) =
3216                                this.find_local_worktree(&abs_path, cx)
3217                            {
3218                                worktree_id = worktree.read(cx).id();
3219                                path = rel_path;
3220                            } else {
3221                                path = relativize_path(&worktree_abs_path, &abs_path);
3222                            }
3223
3224                            let project_path = ProjectPath {
3225                                worktree_id,
3226                                path: path.into(),
3227                            };
3228                            let signature = this.symbol_signature(&project_path);
3229                            let language = this
3230                                .languages
3231                                .language_for_path(&project_path.path)
3232                                .unwrap_or(adapter_language.clone());
3233                            let language_server_name = adapter.name.clone();
3234                            Some(async move {
3235                                let label = language
3236                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3237                                    .await;
3238
3239                                Symbol {
3240                                    language_server_name,
3241                                    source_worktree_id,
3242                                    path: project_path,
3243                                    label: label.unwrap_or_else(|| {
3244                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3245                                    }),
3246                                    kind: lsp_symbol.kind,
3247                                    name: lsp_symbol.name,
3248                                    range: range_from_lsp(lsp_symbol.location.range),
3249                                    signature,
3250                                }
3251                            })
3252                        }));
3253                    }
3254                    symbols
3255                });
3256                Ok(futures::future::join_all(symbols).await)
3257            })
3258        } else if let Some(project_id) = self.remote_id() {
3259            let request = self.client.request(proto::GetProjectSymbols {
3260                project_id,
3261                query: query.to_string(),
3262            });
3263            cx.spawn_weak(|this, cx| async move {
3264                let response = request.await?;
3265                let mut symbols = Vec::new();
3266                if let Some(this) = this.upgrade(&cx) {
3267                    let new_symbols = this.read_with(&cx, |this, _| {
3268                        response
3269                            .symbols
3270                            .into_iter()
3271                            .map(|symbol| this.deserialize_symbol(symbol))
3272                            .collect::<Vec<_>>()
3273                    });
3274                    symbols = futures::future::join_all(new_symbols)
3275                        .await
3276                        .into_iter()
3277                        .filter_map(|symbol| symbol.log_err())
3278                        .collect::<Vec<_>>();
3279                }
3280                Ok(symbols)
3281            })
3282        } else {
3283            Task::ready(Ok(Default::default()))
3284        }
3285    }
3286
3287    pub fn open_buffer_for_symbol(
3288        &mut self,
3289        symbol: &Symbol,
3290        cx: &mut ModelContext<Self>,
3291    ) -> Task<Result<ModelHandle<Buffer>>> {
3292        if self.is_local() {
3293            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3294                symbol.source_worktree_id,
3295                symbol.language_server_name.clone(),
3296            )) {
3297                *id
3298            } else {
3299                return Task::ready(Err(anyhow!(
3300                    "language server for worktree and language not found"
3301                )));
3302            };
3303
3304            let worktree_abs_path = if let Some(worktree_abs_path) = self
3305                .worktree_for_id(symbol.path.worktree_id, cx)
3306                .and_then(|worktree| worktree.read(cx).as_local())
3307                .map(|local_worktree| local_worktree.abs_path())
3308            {
3309                worktree_abs_path
3310            } else {
3311                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3312            };
3313            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3314            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3315                uri
3316            } else {
3317                return Task::ready(Err(anyhow!("invalid symbol path")));
3318            };
3319
3320            self.open_local_buffer_via_lsp(
3321                symbol_uri,
3322                language_server_id,
3323                symbol.language_server_name.clone(),
3324                cx,
3325            )
3326        } else if let Some(project_id) = self.remote_id() {
3327            let request = self.client.request(proto::OpenBufferForSymbol {
3328                project_id,
3329                symbol: Some(serialize_symbol(symbol)),
3330            });
3331            cx.spawn(|this, mut cx| async move {
3332                let response = request.await?;
3333                this.update(&mut cx, |this, cx| {
3334                    this.wait_for_remote_buffer(response.buffer_id, cx)
3335                })
3336                .await
3337            })
3338        } else {
3339            Task::ready(Err(anyhow!("project does not have a remote id")))
3340        }
3341    }
3342
3343    pub fn hover<T: ToPointUtf16>(
3344        &self,
3345        buffer: &ModelHandle<Buffer>,
3346        position: T,
3347        cx: &mut ModelContext<Self>,
3348    ) -> Task<Result<Option<Hover>>> {
3349        let position = position.to_point_utf16(buffer.read(cx));
3350        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3351    }
3352
3353    pub fn completions<T: ToPointUtf16>(
3354        &self,
3355        source_buffer_handle: &ModelHandle<Buffer>,
3356        position: T,
3357        cx: &mut ModelContext<Self>,
3358    ) -> Task<Result<Vec<Completion>>> {
3359        let source_buffer_handle = source_buffer_handle.clone();
3360        let source_buffer = source_buffer_handle.read(cx);
3361        let buffer_id = source_buffer.remote_id();
3362        let language = source_buffer.language().cloned();
3363        let worktree;
3364        let buffer_abs_path;
3365        if let Some(file) = File::from_dyn(source_buffer.file()) {
3366            worktree = file.worktree.clone();
3367            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3368        } else {
3369            return Task::ready(Ok(Default::default()));
3370        };
3371
3372        let position = Unclipped(position.to_point_utf16(source_buffer));
3373        let anchor = source_buffer.anchor_after(position);
3374
3375        if worktree.read(cx).as_local().is_some() {
3376            let buffer_abs_path = buffer_abs_path.unwrap();
3377            let lang_server =
3378                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3379                    server.clone()
3380                } else {
3381                    return Task::ready(Ok(Default::default()));
3382                };
3383
3384            cx.spawn(|_, cx| async move {
3385                let completions = lang_server
3386                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3387                        text_document_position: lsp::TextDocumentPositionParams::new(
3388                            lsp::TextDocumentIdentifier::new(
3389                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3390                            ),
3391                            point_to_lsp(position.0),
3392                        ),
3393                        context: Default::default(),
3394                        work_done_progress_params: Default::default(),
3395                        partial_result_params: Default::default(),
3396                    })
3397                    .await
3398                    .context("lsp completion request failed")?;
3399
3400                let completions = if let Some(completions) = completions {
3401                    match completions {
3402                        lsp::CompletionResponse::Array(completions) => completions,
3403                        lsp::CompletionResponse::List(list) => list.items,
3404                    }
3405                } else {
3406                    Default::default()
3407                };
3408
3409                let completions = source_buffer_handle.read_with(&cx, |this, _| {
3410                    let snapshot = this.snapshot();
3411                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3412                    let mut range_for_token = None;
3413                    completions
3414                        .into_iter()
3415                        .filter_map(move |mut lsp_completion| {
3416                            // For now, we can only handle additional edits if they are returned
3417                            // when resolving the completion, not if they are present initially.
3418                            if lsp_completion
3419                                .additional_text_edits
3420                                .as_ref()
3421                                .map_or(false, |edits| !edits.is_empty())
3422                            {
3423                                return None;
3424                            }
3425
3426                            let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3427                            {
3428                                // If the language server provides a range to overwrite, then
3429                                // check that the range is valid.
3430                                Some(lsp::CompletionTextEdit::Edit(edit)) => {
3431                                    let range = range_from_lsp(edit.range);
3432                                    let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3433                                    let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3434                                    if start != range.start.0 || end != range.end.0 {
3435                                        log::info!("completion out of expected range");
3436                                        return None;
3437                                    }
3438                                    (
3439                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3440                                        edit.new_text.clone(),
3441                                    )
3442                                }
3443                                // If the language server does not provide a range, then infer
3444                                // the range based on the syntax tree.
3445                                None => {
3446                                    if position.0 != clipped_position {
3447                                        log::info!("completion out of expected range");
3448                                        return None;
3449                                    }
3450                                    let Range { start, end } = range_for_token
3451                                        .get_or_insert_with(|| {
3452                                            let offset = position.to_offset(&snapshot);
3453                                            let (range, kind) = snapshot.surrounding_word(offset);
3454                                            if kind == Some(CharKind::Word) {
3455                                                range
3456                                            } else {
3457                                                offset..offset
3458                                            }
3459                                        })
3460                                        .clone();
3461                                    let text = lsp_completion
3462                                        .insert_text
3463                                        .as_ref()
3464                                        .unwrap_or(&lsp_completion.label)
3465                                        .clone();
3466                                    (
3467                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3468                                        text,
3469                                    )
3470                                }
3471                                Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3472                                    log::info!("unsupported insert/replace completion");
3473                                    return None;
3474                                }
3475                            };
3476
3477                            LineEnding::normalize(&mut new_text);
3478                            let language = language.clone();
3479                            Some(async move {
3480                                let mut label = None;
3481                                if let Some(language) = language {
3482                                    language.process_completion(&mut lsp_completion).await;
3483                                    label = language.label_for_completion(&lsp_completion).await;
3484                                }
3485                                Completion {
3486                                    old_range,
3487                                    new_text,
3488                                    label: label.unwrap_or_else(|| {
3489                                        CodeLabel::plain(
3490                                            lsp_completion.label.clone(),
3491                                            lsp_completion.filter_text.as_deref(),
3492                                        )
3493                                    }),
3494                                    lsp_completion,
3495                                }
3496                            })
3497                        })
3498                });
3499
3500                Ok(futures::future::join_all(completions).await)
3501            })
3502        } else if let Some(project_id) = self.remote_id() {
3503            let rpc = self.client.clone();
3504            let message = proto::GetCompletions {
3505                project_id,
3506                buffer_id,
3507                position: Some(language::proto::serialize_anchor(&anchor)),
3508                version: serialize_version(&source_buffer.version()),
3509            };
3510            cx.spawn_weak(|this, mut cx| async move {
3511                let response = rpc.request(message).await?;
3512
3513                if this
3514                    .upgrade(&cx)
3515                    .ok_or_else(|| anyhow!("project was dropped"))?
3516                    .read_with(&cx, |this, _| this.is_read_only())
3517                {
3518                    return Err(anyhow!(
3519                        "failed to get completions: project was disconnected"
3520                    ));
3521                } else {
3522                    source_buffer_handle
3523                        .update(&mut cx, |buffer, _| {
3524                            buffer.wait_for_version(deserialize_version(response.version))
3525                        })
3526                        .await;
3527
3528                    let completions = response.completions.into_iter().map(|completion| {
3529                        language::proto::deserialize_completion(completion, language.clone())
3530                    });
3531                    futures::future::try_join_all(completions).await
3532                }
3533            })
3534        } else {
3535            Task::ready(Ok(Default::default()))
3536        }
3537    }
3538
3539    pub fn apply_additional_edits_for_completion(
3540        &self,
3541        buffer_handle: ModelHandle<Buffer>,
3542        completion: Completion,
3543        push_to_history: bool,
3544        cx: &mut ModelContext<Self>,
3545    ) -> Task<Result<Option<Transaction>>> {
3546        let buffer = buffer_handle.read(cx);
3547        let buffer_id = buffer.remote_id();
3548
3549        if self.is_local() {
3550            let lang_server = match self.language_server_for_buffer(buffer, cx) {
3551                Some((_, server)) => server.clone(),
3552                _ => return Task::ready(Ok(Default::default())),
3553            };
3554
3555            cx.spawn(|this, mut cx| async move {
3556                let resolved_completion = lang_server
3557                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3558                    .await?;
3559
3560                if let Some(edits) = resolved_completion.additional_text_edits {
3561                    let edits = this
3562                        .update(&mut cx, |this, cx| {
3563                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3564                        })
3565                        .await?;
3566
3567                    buffer_handle.update(&mut cx, |buffer, cx| {
3568                        buffer.finalize_last_transaction();
3569                        buffer.start_transaction();
3570
3571                        for (range, text) in edits {
3572                            let primary = &completion.old_range;
3573                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
3574                                && primary.end.cmp(&range.start, buffer).is_ge();
3575                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
3576                                && range.end.cmp(&primary.end, buffer).is_ge();
3577
3578                            //Skip addtional edits which overlap with the primary completion edit
3579                            //https://github.com/zed-industries/zed/pull/1871
3580                            if !start_within && !end_within {
3581                                buffer.edit([(range, text)], None, cx);
3582                            }
3583                        }
3584
3585                        let transaction = if buffer.end_transaction(cx).is_some() {
3586                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3587                            if !push_to_history {
3588                                buffer.forget_transaction(transaction.id);
3589                            }
3590                            Some(transaction)
3591                        } else {
3592                            None
3593                        };
3594                        Ok(transaction)
3595                    })
3596                } else {
3597                    Ok(None)
3598                }
3599            })
3600        } else if let Some(project_id) = self.remote_id() {
3601            let client = self.client.clone();
3602            cx.spawn(|_, mut cx| async move {
3603                let response = client
3604                    .request(proto::ApplyCompletionAdditionalEdits {
3605                        project_id,
3606                        buffer_id,
3607                        completion: Some(language::proto::serialize_completion(&completion)),
3608                    })
3609                    .await?;
3610
3611                if let Some(transaction) = response.transaction {
3612                    let transaction = language::proto::deserialize_transaction(transaction)?;
3613                    buffer_handle
3614                        .update(&mut cx, |buffer, _| {
3615                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3616                        })
3617                        .await;
3618                    if push_to_history {
3619                        buffer_handle.update(&mut cx, |buffer, _| {
3620                            buffer.push_transaction(transaction.clone(), Instant::now());
3621                        });
3622                    }
3623                    Ok(Some(transaction))
3624                } else {
3625                    Ok(None)
3626                }
3627            })
3628        } else {
3629            Task::ready(Err(anyhow!("project does not have a remote id")))
3630        }
3631    }
3632
3633    pub fn code_actions<T: Clone + ToOffset>(
3634        &self,
3635        buffer_handle: &ModelHandle<Buffer>,
3636        range: Range<T>,
3637        cx: &mut ModelContext<Self>,
3638    ) -> Task<Result<Vec<CodeAction>>> {
3639        let buffer_handle = buffer_handle.clone();
3640        let buffer = buffer_handle.read(cx);
3641        let snapshot = buffer.snapshot();
3642        let relevant_diagnostics = snapshot
3643            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3644            .map(|entry| entry.to_lsp_diagnostic_stub())
3645            .collect();
3646        let buffer_id = buffer.remote_id();
3647        let worktree;
3648        let buffer_abs_path;
3649        if let Some(file) = File::from_dyn(buffer.file()) {
3650            worktree = file.worktree.clone();
3651            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3652        } else {
3653            return Task::ready(Ok(Default::default()));
3654        };
3655        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3656
3657        if worktree.read(cx).as_local().is_some() {
3658            let buffer_abs_path = buffer_abs_path.unwrap();
3659            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3660            {
3661                server.clone()
3662            } else {
3663                return Task::ready(Ok(Default::default()));
3664            };
3665
3666            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3667            cx.foreground().spawn(async move {
3668                if lang_server.capabilities().code_action_provider.is_none() {
3669                    return Ok(Default::default());
3670                }
3671
3672                Ok(lang_server
3673                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3674                        text_document: lsp::TextDocumentIdentifier::new(
3675                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3676                        ),
3677                        range: lsp_range,
3678                        work_done_progress_params: Default::default(),
3679                        partial_result_params: Default::default(),
3680                        context: lsp::CodeActionContext {
3681                            diagnostics: relevant_diagnostics,
3682                            only: Some(vec![
3683                                lsp::CodeActionKind::EMPTY,
3684                                lsp::CodeActionKind::QUICKFIX,
3685                                lsp::CodeActionKind::REFACTOR,
3686                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3687                                lsp::CodeActionKind::SOURCE,
3688                            ]),
3689                        },
3690                    })
3691                    .await?
3692                    .unwrap_or_default()
3693                    .into_iter()
3694                    .filter_map(|entry| {
3695                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3696                            Some(CodeAction {
3697                                range: range.clone(),
3698                                lsp_action,
3699                            })
3700                        } else {
3701                            None
3702                        }
3703                    })
3704                    .collect())
3705            })
3706        } else if let Some(project_id) = self.remote_id() {
3707            let rpc = self.client.clone();
3708            let version = buffer.version();
3709            cx.spawn_weak(|this, mut cx| async move {
3710                let response = rpc
3711                    .request(proto::GetCodeActions {
3712                        project_id,
3713                        buffer_id,
3714                        start: Some(language::proto::serialize_anchor(&range.start)),
3715                        end: Some(language::proto::serialize_anchor(&range.end)),
3716                        version: serialize_version(&version),
3717                    })
3718                    .await?;
3719
3720                if this
3721                    .upgrade(&cx)
3722                    .ok_or_else(|| anyhow!("project was dropped"))?
3723                    .read_with(&cx, |this, _| this.is_read_only())
3724                {
3725                    return Err(anyhow!(
3726                        "failed to get code actions: project was disconnected"
3727                    ));
3728                } else {
3729                    buffer_handle
3730                        .update(&mut cx, |buffer, _| {
3731                            buffer.wait_for_version(deserialize_version(response.version))
3732                        })
3733                        .await;
3734
3735                    response
3736                        .actions
3737                        .into_iter()
3738                        .map(language::proto::deserialize_code_action)
3739                        .collect()
3740                }
3741            })
3742        } else {
3743            Task::ready(Ok(Default::default()))
3744        }
3745    }
3746
3747    pub fn apply_code_action(
3748        &self,
3749        buffer_handle: ModelHandle<Buffer>,
3750        mut action: CodeAction,
3751        push_to_history: bool,
3752        cx: &mut ModelContext<Self>,
3753    ) -> Task<Result<ProjectTransaction>> {
3754        if self.is_local() {
3755            let buffer = buffer_handle.read(cx);
3756            let (lsp_adapter, lang_server) =
3757                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3758                    (adapter.clone(), server.clone())
3759                } else {
3760                    return Task::ready(Ok(Default::default()));
3761                };
3762            let range = action.range.to_point_utf16(buffer);
3763
3764            cx.spawn(|this, mut cx| async move {
3765                if let Some(lsp_range) = action
3766                    .lsp_action
3767                    .data
3768                    .as_mut()
3769                    .and_then(|d| d.get_mut("codeActionParams"))
3770                    .and_then(|d| d.get_mut("range"))
3771                {
3772                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3773                    action.lsp_action = lang_server
3774                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3775                        .await?;
3776                } else {
3777                    let actions = this
3778                        .update(&mut cx, |this, cx| {
3779                            this.code_actions(&buffer_handle, action.range, cx)
3780                        })
3781                        .await?;
3782                    action.lsp_action = actions
3783                        .into_iter()
3784                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3785                        .ok_or_else(|| anyhow!("code action is outdated"))?
3786                        .lsp_action;
3787                }
3788
3789                if let Some(edit) = action.lsp_action.edit {
3790                    if edit.changes.is_some() || edit.document_changes.is_some() {
3791                        return Self::deserialize_workspace_edit(
3792                            this,
3793                            edit,
3794                            push_to_history,
3795                            lsp_adapter.clone(),
3796                            lang_server.clone(),
3797                            &mut cx,
3798                        )
3799                        .await;
3800                    }
3801                }
3802
3803                if let Some(command) = action.lsp_action.command {
3804                    this.update(&mut cx, |this, _| {
3805                        this.last_workspace_edits_by_language_server
3806                            .remove(&lang_server.server_id());
3807                    });
3808                    lang_server
3809                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3810                            command: command.command,
3811                            arguments: command.arguments.unwrap_or_default(),
3812                            ..Default::default()
3813                        })
3814                        .await?;
3815                    return Ok(this.update(&mut cx, |this, _| {
3816                        this.last_workspace_edits_by_language_server
3817                            .remove(&lang_server.server_id())
3818                            .unwrap_or_default()
3819                    }));
3820                }
3821
3822                Ok(ProjectTransaction::default())
3823            })
3824        } else if let Some(project_id) = self.remote_id() {
3825            let client = self.client.clone();
3826            let request = proto::ApplyCodeAction {
3827                project_id,
3828                buffer_id: buffer_handle.read(cx).remote_id(),
3829                action: Some(language::proto::serialize_code_action(&action)),
3830            };
3831            cx.spawn(|this, mut cx| async move {
3832                let response = client
3833                    .request(request)
3834                    .await?
3835                    .transaction
3836                    .ok_or_else(|| anyhow!("missing transaction"))?;
3837                this.update(&mut cx, |this, cx| {
3838                    this.deserialize_project_transaction(response, push_to_history, cx)
3839                })
3840                .await
3841            })
3842        } else {
3843            Task::ready(Err(anyhow!("project does not have a remote id")))
3844        }
3845    }
3846
3847    async fn deserialize_workspace_edit(
3848        this: ModelHandle<Self>,
3849        edit: lsp::WorkspaceEdit,
3850        push_to_history: bool,
3851        lsp_adapter: Arc<CachedLspAdapter>,
3852        language_server: Arc<LanguageServer>,
3853        cx: &mut AsyncAppContext,
3854    ) -> Result<ProjectTransaction> {
3855        let fs = this.read_with(cx, |this, _| this.fs.clone());
3856        let mut operations = Vec::new();
3857        if let Some(document_changes) = edit.document_changes {
3858            match document_changes {
3859                lsp::DocumentChanges::Edits(edits) => {
3860                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3861                }
3862                lsp::DocumentChanges::Operations(ops) => operations = ops,
3863            }
3864        } else if let Some(changes) = edit.changes {
3865            operations.extend(changes.into_iter().map(|(uri, edits)| {
3866                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3867                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3868                        uri,
3869                        version: None,
3870                    },
3871                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3872                })
3873            }));
3874        }
3875
3876        let mut project_transaction = ProjectTransaction::default();
3877        for operation in operations {
3878            match operation {
3879                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3880                    let abs_path = op
3881                        .uri
3882                        .to_file_path()
3883                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3884
3885                    if let Some(parent_path) = abs_path.parent() {
3886                        fs.create_dir(parent_path).await?;
3887                    }
3888                    if abs_path.ends_with("/") {
3889                        fs.create_dir(&abs_path).await?;
3890                    } else {
3891                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3892                            .await?;
3893                    }
3894                }
3895                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3896                    let source_abs_path = op
3897                        .old_uri
3898                        .to_file_path()
3899                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3900                    let target_abs_path = op
3901                        .new_uri
3902                        .to_file_path()
3903                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3904                    fs.rename(
3905                        &source_abs_path,
3906                        &target_abs_path,
3907                        op.options.map(Into::into).unwrap_or_default(),
3908                    )
3909                    .await?;
3910                }
3911                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3912                    let abs_path = op
3913                        .uri
3914                        .to_file_path()
3915                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3916                    let options = op.options.map(Into::into).unwrap_or_default();
3917                    if abs_path.ends_with("/") {
3918                        fs.remove_dir(&abs_path, options).await?;
3919                    } else {
3920                        fs.remove_file(&abs_path, options).await?;
3921                    }
3922                }
3923                lsp::DocumentChangeOperation::Edit(op) => {
3924                    let buffer_to_edit = this
3925                        .update(cx, |this, cx| {
3926                            this.open_local_buffer_via_lsp(
3927                                op.text_document.uri,
3928                                language_server.server_id(),
3929                                lsp_adapter.name.clone(),
3930                                cx,
3931                            )
3932                        })
3933                        .await?;
3934
3935                    let edits = this
3936                        .update(cx, |this, cx| {
3937                            let edits = op.edits.into_iter().map(|edit| match edit {
3938                                lsp::OneOf::Left(edit) => edit,
3939                                lsp::OneOf::Right(edit) => edit.text_edit,
3940                            });
3941                            this.edits_from_lsp(
3942                                &buffer_to_edit,
3943                                edits,
3944                                op.text_document.version,
3945                                cx,
3946                            )
3947                        })
3948                        .await?;
3949
3950                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3951                        buffer.finalize_last_transaction();
3952                        buffer.start_transaction();
3953                        for (range, text) in edits {
3954                            buffer.edit([(range, text)], None, cx);
3955                        }
3956                        let transaction = if buffer.end_transaction(cx).is_some() {
3957                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3958                            if !push_to_history {
3959                                buffer.forget_transaction(transaction.id);
3960                            }
3961                            Some(transaction)
3962                        } else {
3963                            None
3964                        };
3965
3966                        transaction
3967                    });
3968                    if let Some(transaction) = transaction {
3969                        project_transaction.0.insert(buffer_to_edit, transaction);
3970                    }
3971                }
3972            }
3973        }
3974
3975        Ok(project_transaction)
3976    }
3977
3978    pub fn prepare_rename<T: ToPointUtf16>(
3979        &self,
3980        buffer: ModelHandle<Buffer>,
3981        position: T,
3982        cx: &mut ModelContext<Self>,
3983    ) -> Task<Result<Option<Range<Anchor>>>> {
3984        let position = position.to_point_utf16(buffer.read(cx));
3985        self.request_lsp(buffer, PrepareRename { position }, cx)
3986    }
3987
3988    pub fn perform_rename<T: ToPointUtf16>(
3989        &self,
3990        buffer: ModelHandle<Buffer>,
3991        position: T,
3992        new_name: String,
3993        push_to_history: bool,
3994        cx: &mut ModelContext<Self>,
3995    ) -> Task<Result<ProjectTransaction>> {
3996        let position = position.to_point_utf16(buffer.read(cx));
3997        self.request_lsp(
3998            buffer,
3999            PerformRename {
4000                position,
4001                new_name,
4002                push_to_history,
4003            },
4004            cx,
4005        )
4006    }
4007
4008    #[allow(clippy::type_complexity)]
4009    pub fn search(
4010        &self,
4011        query: SearchQuery,
4012        cx: &mut ModelContext<Self>,
4013    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4014        if self.is_local() {
4015            let snapshots = self
4016                .visible_worktrees(cx)
4017                .filter_map(|tree| {
4018                    let tree = tree.read(cx).as_local()?;
4019                    Some(tree.snapshot())
4020                })
4021                .collect::<Vec<_>>();
4022
4023            let background = cx.background().clone();
4024            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4025            if path_count == 0 {
4026                return Task::ready(Ok(Default::default()));
4027            }
4028            let workers = background.num_cpus().min(path_count);
4029            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4030            cx.background()
4031                .spawn({
4032                    let fs = self.fs.clone();
4033                    let background = cx.background().clone();
4034                    let query = query.clone();
4035                    async move {
4036                        let fs = &fs;
4037                        let query = &query;
4038                        let matching_paths_tx = &matching_paths_tx;
4039                        let paths_per_worker = (path_count + workers - 1) / workers;
4040                        let snapshots = &snapshots;
4041                        background
4042                            .scoped(|scope| {
4043                                for worker_ix in 0..workers {
4044                                    let worker_start_ix = worker_ix * paths_per_worker;
4045                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4046                                    scope.spawn(async move {
4047                                        let mut snapshot_start_ix = 0;
4048                                        let mut abs_path = PathBuf::new();
4049                                        for snapshot in snapshots {
4050                                            let snapshot_end_ix =
4051                                                snapshot_start_ix + snapshot.visible_file_count();
4052                                            if worker_end_ix <= snapshot_start_ix {
4053                                                break;
4054                                            } else if worker_start_ix > snapshot_end_ix {
4055                                                snapshot_start_ix = snapshot_end_ix;
4056                                                continue;
4057                                            } else {
4058                                                let start_in_snapshot = worker_start_ix
4059                                                    .saturating_sub(snapshot_start_ix);
4060                                                let end_in_snapshot =
4061                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4062                                                        - snapshot_start_ix;
4063
4064                                                for entry in snapshot
4065                                                    .files(false, start_in_snapshot)
4066                                                    .take(end_in_snapshot - start_in_snapshot)
4067                                                {
4068                                                    if matching_paths_tx.is_closed() {
4069                                                        break;
4070                                                    }
4071
4072                                                    abs_path.clear();
4073                                                    abs_path.push(&snapshot.abs_path());
4074                                                    abs_path.push(&entry.path);
4075                                                    let matches = if let Some(file) =
4076                                                        fs.open_sync(&abs_path).await.log_err()
4077                                                    {
4078                                                        query.detect(file).unwrap_or(false)
4079                                                    } else {
4080                                                        false
4081                                                    };
4082
4083                                                    if matches {
4084                                                        let project_path =
4085                                                            (snapshot.id(), entry.path.clone());
4086                                                        if matching_paths_tx
4087                                                            .send(project_path)
4088                                                            .await
4089                                                            .is_err()
4090                                                        {
4091                                                            break;
4092                                                        }
4093                                                    }
4094                                                }
4095
4096                                                snapshot_start_ix = snapshot_end_ix;
4097                                            }
4098                                        }
4099                                    });
4100                                }
4101                            })
4102                            .await;
4103                    }
4104                })
4105                .detach();
4106
4107            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4108            let open_buffers = self
4109                .opened_buffers
4110                .values()
4111                .filter_map(|b| b.upgrade(cx))
4112                .collect::<HashSet<_>>();
4113            cx.spawn(|this, cx| async move {
4114                for buffer in &open_buffers {
4115                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4116                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4117                }
4118
4119                let open_buffers = Rc::new(RefCell::new(open_buffers));
4120                while let Some(project_path) = matching_paths_rx.next().await {
4121                    if buffers_tx.is_closed() {
4122                        break;
4123                    }
4124
4125                    let this = this.clone();
4126                    let open_buffers = open_buffers.clone();
4127                    let buffers_tx = buffers_tx.clone();
4128                    cx.spawn(|mut cx| async move {
4129                        if let Some(buffer) = this
4130                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4131                            .await
4132                            .log_err()
4133                        {
4134                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4135                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4136                                buffers_tx.send((buffer, snapshot)).await?;
4137                            }
4138                        }
4139
4140                        Ok::<_, anyhow::Error>(())
4141                    })
4142                    .detach();
4143                }
4144
4145                Ok::<_, anyhow::Error>(())
4146            })
4147            .detach_and_log_err(cx);
4148
4149            let background = cx.background().clone();
4150            cx.background().spawn(async move {
4151                let query = &query;
4152                let mut matched_buffers = Vec::new();
4153                for _ in 0..workers {
4154                    matched_buffers.push(HashMap::default());
4155                }
4156                background
4157                    .scoped(|scope| {
4158                        for worker_matched_buffers in matched_buffers.iter_mut() {
4159                            let mut buffers_rx = buffers_rx.clone();
4160                            scope.spawn(async move {
4161                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4162                                    let buffer_matches = query
4163                                        .search(snapshot.as_rope())
4164                                        .await
4165                                        .iter()
4166                                        .map(|range| {
4167                                            snapshot.anchor_before(range.start)
4168                                                ..snapshot.anchor_after(range.end)
4169                                        })
4170                                        .collect::<Vec<_>>();
4171                                    if !buffer_matches.is_empty() {
4172                                        worker_matched_buffers
4173                                            .insert(buffer.clone(), buffer_matches);
4174                                    }
4175                                }
4176                            });
4177                        }
4178                    })
4179                    .await;
4180                Ok(matched_buffers.into_iter().flatten().collect())
4181            })
4182        } else if let Some(project_id) = self.remote_id() {
4183            let request = self.client.request(query.to_proto(project_id));
4184            cx.spawn(|this, mut cx| async move {
4185                let response = request.await?;
4186                let mut result = HashMap::default();
4187                for location in response.locations {
4188                    let target_buffer = this
4189                        .update(&mut cx, |this, cx| {
4190                            this.wait_for_remote_buffer(location.buffer_id, cx)
4191                        })
4192                        .await?;
4193                    let start = location
4194                        .start
4195                        .and_then(deserialize_anchor)
4196                        .ok_or_else(|| anyhow!("missing target start"))?;
4197                    let end = location
4198                        .end
4199                        .and_then(deserialize_anchor)
4200                        .ok_or_else(|| anyhow!("missing target end"))?;
4201                    result
4202                        .entry(target_buffer)
4203                        .or_insert(Vec::new())
4204                        .push(start..end)
4205                }
4206                Ok(result)
4207            })
4208        } else {
4209            Task::ready(Ok(Default::default()))
4210        }
4211    }
4212
4213    fn request_lsp<R: LspCommand>(
4214        &self,
4215        buffer_handle: ModelHandle<Buffer>,
4216        request: R,
4217        cx: &mut ModelContext<Self>,
4218    ) -> Task<Result<R::Response>>
4219    where
4220        <R::LspRequest as lsp::request::Request>::Result: Send,
4221    {
4222        let buffer = buffer_handle.read(cx);
4223        if self.is_local() {
4224            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4225            if let Some((file, language_server)) = file.zip(
4226                self.language_server_for_buffer(buffer, cx)
4227                    .map(|(_, server)| server.clone()),
4228            ) {
4229                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4230                return cx.spawn(|this, cx| async move {
4231                    if !request.check_capabilities(language_server.capabilities()) {
4232                        return Ok(Default::default());
4233                    }
4234
4235                    let response = language_server
4236                        .request::<R::LspRequest>(lsp_params)
4237                        .await
4238                        .context("lsp request failed")?;
4239                    request
4240                        .response_from_lsp(response, this, buffer_handle, cx)
4241                        .await
4242                });
4243            }
4244        } else if let Some(project_id) = self.remote_id() {
4245            let rpc = self.client.clone();
4246            let message = request.to_proto(project_id, buffer);
4247            return cx.spawn_weak(|this, cx| async move {
4248                let response = rpc.request(message).await?;
4249                let this = this
4250                    .upgrade(&cx)
4251                    .ok_or_else(|| anyhow!("project dropped"))?;
4252                if this.read_with(&cx, |this, _| this.is_read_only()) {
4253                    Err(anyhow!("disconnected before completing request"))
4254                } else {
4255                    request
4256                        .response_from_proto(response, this, buffer_handle, cx)
4257                        .await
4258                }
4259            });
4260        }
4261        Task::ready(Ok(Default::default()))
4262    }
4263
4264    pub fn find_or_create_local_worktree(
4265        &mut self,
4266        abs_path: impl AsRef<Path>,
4267        visible: bool,
4268        cx: &mut ModelContext<Self>,
4269    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4270        let abs_path = abs_path.as_ref();
4271        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4272            Task::ready(Ok((tree, relative_path)))
4273        } else {
4274            let worktree = self.create_local_worktree(abs_path, visible, cx);
4275            cx.foreground()
4276                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4277        }
4278    }
4279
4280    pub fn find_local_worktree(
4281        &self,
4282        abs_path: &Path,
4283        cx: &AppContext,
4284    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4285        for tree in &self.worktrees {
4286            if let Some(tree) = tree.upgrade(cx) {
4287                if let Some(relative_path) = tree
4288                    .read(cx)
4289                    .as_local()
4290                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4291                {
4292                    return Some((tree.clone(), relative_path.into()));
4293                }
4294            }
4295        }
4296        None
4297    }
4298
4299    pub fn is_shared(&self) -> bool {
4300        match &self.client_state {
4301            Some(ProjectClientState::Local { .. }) => true,
4302            _ => false,
4303        }
4304    }
4305
4306    fn create_local_worktree(
4307        &mut self,
4308        abs_path: impl AsRef<Path>,
4309        visible: bool,
4310        cx: &mut ModelContext<Self>,
4311    ) -> Task<Result<ModelHandle<Worktree>>> {
4312        let fs = self.fs.clone();
4313        let client = self.client.clone();
4314        let next_entry_id = self.next_entry_id.clone();
4315        let path: Arc<Path> = abs_path.as_ref().into();
4316        let task = self
4317            .loading_local_worktrees
4318            .entry(path.clone())
4319            .or_insert_with(|| {
4320                cx.spawn(|project, mut cx| {
4321                    async move {
4322                        let worktree = Worktree::local(
4323                            client.clone(),
4324                            path.clone(),
4325                            visible,
4326                            fs,
4327                            next_entry_id,
4328                            &mut cx,
4329                        )
4330                        .await;
4331                        project.update(&mut cx, |project, _| {
4332                            project.loading_local_worktrees.remove(&path);
4333                        });
4334                        let worktree = worktree?;
4335
4336                        project
4337                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))
4338                            .await;
4339
4340                        Ok(worktree)
4341                    }
4342                    .map_err(Arc::new)
4343                })
4344                .shared()
4345            })
4346            .clone();
4347        cx.foreground().spawn(async move {
4348            match task.await {
4349                Ok(worktree) => Ok(worktree),
4350                Err(err) => Err(anyhow!("{}", err)),
4351            }
4352        })
4353    }
4354
4355    pub fn remove_worktree(
4356        &mut self,
4357        id_to_remove: WorktreeId,
4358        cx: &mut ModelContext<Self>,
4359    ) -> impl Future<Output = ()> {
4360        self.worktrees.retain(|worktree| {
4361            if let Some(worktree) = worktree.upgrade(cx) {
4362                let id = worktree.read(cx).id();
4363                if id == id_to_remove {
4364                    cx.emit(Event::WorktreeRemoved(id));
4365                    false
4366                } else {
4367                    true
4368                }
4369            } else {
4370                false
4371            }
4372        });
4373        self.metadata_changed(cx)
4374    }
4375
4376    fn add_worktree(
4377        &mut self,
4378        worktree: &ModelHandle<Worktree>,
4379        cx: &mut ModelContext<Self>,
4380    ) -> impl Future<Output = ()> {
4381        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4382        if worktree.read(cx).is_local() {
4383            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4384                worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
4385                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4386                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4387                }
4388            })
4389            .detach();
4390        }
4391
4392        let push_strong_handle = {
4393            let worktree = worktree.read(cx);
4394            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4395        };
4396        if push_strong_handle {
4397            self.worktrees
4398                .push(WorktreeHandle::Strong(worktree.clone()));
4399        } else {
4400            self.worktrees
4401                .push(WorktreeHandle::Weak(worktree.downgrade()));
4402        }
4403
4404        cx.observe_release(worktree, |this, worktree, cx| {
4405            let _ = this.remove_worktree(worktree.id(), cx);
4406        })
4407        .detach();
4408
4409        cx.emit(Event::WorktreeAdded);
4410        self.metadata_changed(cx)
4411    }
4412
4413    fn update_local_worktree_buffers(
4414        &mut self,
4415        worktree_handle: ModelHandle<Worktree>,
4416        cx: &mut ModelContext<Self>,
4417    ) {
4418        let snapshot = worktree_handle.read(cx).snapshot();
4419        let mut buffers_to_delete = Vec::new();
4420        let mut renamed_buffers = Vec::new();
4421        for (buffer_id, buffer) in &self.opened_buffers {
4422            if let Some(buffer) = buffer.upgrade(cx) {
4423                buffer.update(cx, |buffer, cx| {
4424                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4425                        if old_file.worktree != worktree_handle {
4426                            return;
4427                        }
4428
4429                        let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4430                        {
4431                            File {
4432                                is_local: true,
4433                                entry_id: entry.id,
4434                                mtime: entry.mtime,
4435                                path: entry.path.clone(),
4436                                worktree: worktree_handle.clone(),
4437                                is_deleted: false,
4438                            }
4439                        } else if let Some(entry) =
4440                            snapshot.entry_for_path(old_file.path().as_ref())
4441                        {
4442                            File {
4443                                is_local: true,
4444                                entry_id: entry.id,
4445                                mtime: entry.mtime,
4446                                path: entry.path.clone(),
4447                                worktree: worktree_handle.clone(),
4448                                is_deleted: false,
4449                            }
4450                        } else {
4451                            File {
4452                                is_local: true,
4453                                entry_id: old_file.entry_id,
4454                                path: old_file.path().clone(),
4455                                mtime: old_file.mtime(),
4456                                worktree: worktree_handle.clone(),
4457                                is_deleted: true,
4458                            }
4459                        };
4460
4461                        let old_path = old_file.abs_path(cx);
4462                        if new_file.abs_path(cx) != old_path {
4463                            renamed_buffers.push((cx.handle(), old_path));
4464                        }
4465
4466                        if new_file != *old_file {
4467                            if let Some(project_id) = self.remote_id() {
4468                                self.client
4469                                    .send(proto::UpdateBufferFile {
4470                                        project_id,
4471                                        buffer_id: *buffer_id as u64,
4472                                        file: Some(new_file.to_proto()),
4473                                    })
4474                                    .log_err();
4475                            }
4476
4477                            buffer.file_updated(Arc::new(new_file), cx).detach();
4478                        }
4479                    }
4480                });
4481            } else {
4482                buffers_to_delete.push(*buffer_id);
4483            }
4484        }
4485
4486        for buffer_id in buffers_to_delete {
4487            self.opened_buffers.remove(&buffer_id);
4488        }
4489
4490        for (buffer, old_path) in renamed_buffers {
4491            self.unregister_buffer_from_language_server(&buffer, old_path, cx);
4492            self.assign_language_to_buffer(&buffer, cx);
4493            self.register_buffer_with_language_server(&buffer, cx);
4494        }
4495    }
4496
4497    fn update_local_worktree_buffers_git_repos(
4498        &mut self,
4499        worktree: ModelHandle<Worktree>,
4500        repos: &[GitRepositoryEntry],
4501        cx: &mut ModelContext<Self>,
4502    ) {
4503        for (_, buffer) in &self.opened_buffers {
4504            if let Some(buffer) = buffer.upgrade(cx) {
4505                let file = match File::from_dyn(buffer.read(cx).file()) {
4506                    Some(file) => file,
4507                    None => continue,
4508                };
4509                if file.worktree != worktree {
4510                    continue;
4511                }
4512
4513                let path = file.path().clone();
4514
4515                let repo = match repos.iter().find(|repo| repo.manages(&path)) {
4516                    Some(repo) => repo.clone(),
4517                    None => return,
4518                };
4519
4520                let relative_repo = match path.strip_prefix(repo.content_path) {
4521                    Ok(relative_repo) => relative_repo.to_owned(),
4522                    Err(_) => return,
4523                };
4524
4525                let remote_id = self.remote_id();
4526                let client = self.client.clone();
4527
4528                cx.spawn(|_, mut cx| async move {
4529                    let diff_base = cx
4530                        .background()
4531                        .spawn(async move { repo.repo.lock().load_index_text(&relative_repo) })
4532                        .await;
4533
4534                    let buffer_id = buffer.update(&mut cx, |buffer, cx| {
4535                        buffer.set_diff_base(diff_base.clone(), cx);
4536                        buffer.remote_id()
4537                    });
4538
4539                    if let Some(project_id) = remote_id {
4540                        client
4541                            .send(proto::UpdateDiffBase {
4542                                project_id,
4543                                buffer_id: buffer_id as u64,
4544                                diff_base,
4545                            })
4546                            .log_err();
4547                    }
4548                })
4549                .detach();
4550            }
4551        }
4552    }
4553
4554    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
4555        let new_active_entry = entry.and_then(|project_path| {
4556            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4557            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4558            Some(entry.id)
4559        });
4560        if new_active_entry != self.active_entry {
4561            self.active_entry = new_active_entry;
4562            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4563        }
4564    }
4565
4566    pub fn language_servers_running_disk_based_diagnostics(
4567        &self,
4568    ) -> impl Iterator<Item = usize> + '_ {
4569        self.language_server_statuses
4570            .iter()
4571            .filter_map(|(id, status)| {
4572                if status.has_pending_diagnostic_updates {
4573                    Some(*id)
4574                } else {
4575                    None
4576                }
4577            })
4578    }
4579
4580    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
4581        let mut summary = DiagnosticSummary::default();
4582        for (_, path_summary) in self.diagnostic_summaries(cx) {
4583            summary.error_count += path_summary.error_count;
4584            summary.warning_count += path_summary.warning_count;
4585        }
4586        summary
4587    }
4588
4589    pub fn diagnostic_summaries<'a>(
4590        &'a self,
4591        cx: &'a AppContext,
4592    ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
4593        self.visible_worktrees(cx).flat_map(move |worktree| {
4594            let worktree = worktree.read(cx);
4595            let worktree_id = worktree.id();
4596            worktree
4597                .diagnostic_summaries()
4598                .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
4599        })
4600    }
4601
4602    pub fn disk_based_diagnostics_started(
4603        &mut self,
4604        language_server_id: usize,
4605        cx: &mut ModelContext<Self>,
4606    ) {
4607        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
4608    }
4609
4610    pub fn disk_based_diagnostics_finished(
4611        &mut self,
4612        language_server_id: usize,
4613        cx: &mut ModelContext<Self>,
4614    ) {
4615        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
4616    }
4617
4618    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4619        self.active_entry
4620    }
4621
4622    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
4623        self.worktree_for_id(path.worktree_id, cx)?
4624            .read(cx)
4625            .entry_for_path(&path.path)
4626            .cloned()
4627    }
4628
4629    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
4630        let worktree = self.worktree_for_entry(entry_id, cx)?;
4631        let worktree = worktree.read(cx);
4632        let worktree_id = worktree.id();
4633        let path = worktree.entry_for_id(entry_id)?.path.clone();
4634        Some(ProjectPath { worktree_id, path })
4635    }
4636
4637    // RPC message handlers
4638
4639    async fn handle_unshare_project(
4640        this: ModelHandle<Self>,
4641        _: TypedEnvelope<proto::UnshareProject>,
4642        _: Arc<Client>,
4643        mut cx: AsyncAppContext,
4644    ) -> Result<()> {
4645        this.update(&mut cx, |this, cx| {
4646            if this.is_local() {
4647                this.unshare(cx)?;
4648            } else {
4649                this.disconnected_from_host(cx);
4650            }
4651            Ok(())
4652        })
4653    }
4654
4655    async fn handle_add_collaborator(
4656        this: ModelHandle<Self>,
4657        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4658        _: Arc<Client>,
4659        mut cx: AsyncAppContext,
4660    ) -> Result<()> {
4661        let collaborator = envelope
4662            .payload
4663            .collaborator
4664            .take()
4665            .ok_or_else(|| anyhow!("empty collaborator"))?;
4666
4667        let collaborator = Collaborator::from_proto(collaborator)?;
4668        this.update(&mut cx, |this, cx| {
4669            this.collaborators
4670                .insert(collaborator.peer_id, collaborator);
4671            cx.notify();
4672        });
4673
4674        Ok(())
4675    }
4676
4677    async fn handle_update_project_collaborator(
4678        this: ModelHandle<Self>,
4679        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4680        _: Arc<Client>,
4681        mut cx: AsyncAppContext,
4682    ) -> Result<()> {
4683        let old_peer_id = envelope
4684            .payload
4685            .old_peer_id
4686            .ok_or_else(|| anyhow!("missing old peer id"))?;
4687        let new_peer_id = envelope
4688            .payload
4689            .new_peer_id
4690            .ok_or_else(|| anyhow!("missing new peer id"))?;
4691        this.update(&mut cx, |this, cx| {
4692            let collaborator = this
4693                .collaborators
4694                .remove(&old_peer_id)
4695                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4696            let is_host = collaborator.replica_id == 0;
4697            this.collaborators.insert(new_peer_id, collaborator);
4698
4699            let buffers = this.shared_buffers.remove(&old_peer_id);
4700            log::info!(
4701                "peer {} became {}. moving buffers {:?}",
4702                old_peer_id,
4703                new_peer_id,
4704                &buffers
4705            );
4706            if let Some(buffers) = buffers {
4707                this.shared_buffers.insert(new_peer_id, buffers);
4708            }
4709
4710            if is_host {
4711                this.synchronize_remote_buffers(cx).detach_and_log_err(cx);
4712            }
4713
4714            cx.emit(Event::CollaboratorUpdated {
4715                old_peer_id,
4716                new_peer_id,
4717            });
4718            cx.notify();
4719            Ok(())
4720        })
4721    }
4722
4723    async fn handle_remove_collaborator(
4724        this: ModelHandle<Self>,
4725        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4726        _: Arc<Client>,
4727        mut cx: AsyncAppContext,
4728    ) -> Result<()> {
4729        this.update(&mut cx, |this, cx| {
4730            let peer_id = envelope
4731                .payload
4732                .peer_id
4733                .ok_or_else(|| anyhow!("invalid peer id"))?;
4734            let replica_id = this
4735                .collaborators
4736                .remove(&peer_id)
4737                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4738                .replica_id;
4739            for buffer in this.opened_buffers.values() {
4740                if let Some(buffer) = buffer.upgrade(cx) {
4741                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4742                }
4743            }
4744            this.shared_buffers.remove(&peer_id);
4745
4746            cx.emit(Event::CollaboratorLeft(peer_id));
4747            cx.notify();
4748            Ok(())
4749        })
4750    }
4751
4752    async fn handle_update_project(
4753        this: ModelHandle<Self>,
4754        envelope: TypedEnvelope<proto::UpdateProject>,
4755        _: Arc<Client>,
4756        mut cx: AsyncAppContext,
4757    ) -> Result<()> {
4758        this.update(&mut cx, |this, cx| {
4759            this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4760            Ok(())
4761        })
4762    }
4763
4764    async fn handle_update_worktree(
4765        this: ModelHandle<Self>,
4766        envelope: TypedEnvelope<proto::UpdateWorktree>,
4767        _: Arc<Client>,
4768        mut cx: AsyncAppContext,
4769    ) -> Result<()> {
4770        this.update(&mut cx, |this, cx| {
4771            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4772            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4773                worktree.update(cx, |worktree, _| {
4774                    let worktree = worktree.as_remote_mut().unwrap();
4775                    worktree.update_from_remote(envelope.payload);
4776                });
4777            }
4778            Ok(())
4779        })
4780    }
4781
4782    async fn handle_create_project_entry(
4783        this: ModelHandle<Self>,
4784        envelope: TypedEnvelope<proto::CreateProjectEntry>,
4785        _: Arc<Client>,
4786        mut cx: AsyncAppContext,
4787    ) -> Result<proto::ProjectEntryResponse> {
4788        let worktree = this.update(&mut cx, |this, cx| {
4789            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4790            this.worktree_for_id(worktree_id, cx)
4791                .ok_or_else(|| anyhow!("worktree not found"))
4792        })?;
4793        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4794        let entry = worktree
4795            .update(&mut cx, |worktree, cx| {
4796                let worktree = worktree.as_local_mut().unwrap();
4797                let path = PathBuf::from(envelope.payload.path);
4798                worktree.create_entry(path, envelope.payload.is_directory, cx)
4799            })
4800            .await?;
4801        Ok(proto::ProjectEntryResponse {
4802            entry: Some((&entry).into()),
4803            worktree_scan_id: worktree_scan_id as u64,
4804        })
4805    }
4806
4807    async fn handle_rename_project_entry(
4808        this: ModelHandle<Self>,
4809        envelope: TypedEnvelope<proto::RenameProjectEntry>,
4810        _: Arc<Client>,
4811        mut cx: AsyncAppContext,
4812    ) -> Result<proto::ProjectEntryResponse> {
4813        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4814        let worktree = this.read_with(&cx, |this, cx| {
4815            this.worktree_for_entry(entry_id, cx)
4816                .ok_or_else(|| anyhow!("worktree not found"))
4817        })?;
4818        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4819        let entry = worktree
4820            .update(&mut cx, |worktree, cx| {
4821                let new_path = PathBuf::from(envelope.payload.new_path);
4822                worktree
4823                    .as_local_mut()
4824                    .unwrap()
4825                    .rename_entry(entry_id, new_path, cx)
4826                    .ok_or_else(|| anyhow!("invalid entry"))
4827            })?
4828            .await?;
4829        Ok(proto::ProjectEntryResponse {
4830            entry: Some((&entry).into()),
4831            worktree_scan_id: worktree_scan_id as u64,
4832        })
4833    }
4834
4835    async fn handle_copy_project_entry(
4836        this: ModelHandle<Self>,
4837        envelope: TypedEnvelope<proto::CopyProjectEntry>,
4838        _: Arc<Client>,
4839        mut cx: AsyncAppContext,
4840    ) -> Result<proto::ProjectEntryResponse> {
4841        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4842        let worktree = this.read_with(&cx, |this, cx| {
4843            this.worktree_for_entry(entry_id, cx)
4844                .ok_or_else(|| anyhow!("worktree not found"))
4845        })?;
4846        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4847        let entry = worktree
4848            .update(&mut cx, |worktree, cx| {
4849                let new_path = PathBuf::from(envelope.payload.new_path);
4850                worktree
4851                    .as_local_mut()
4852                    .unwrap()
4853                    .copy_entry(entry_id, new_path, cx)
4854                    .ok_or_else(|| anyhow!("invalid entry"))
4855            })?
4856            .await?;
4857        Ok(proto::ProjectEntryResponse {
4858            entry: Some((&entry).into()),
4859            worktree_scan_id: worktree_scan_id as u64,
4860        })
4861    }
4862
4863    async fn handle_delete_project_entry(
4864        this: ModelHandle<Self>,
4865        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
4866        _: Arc<Client>,
4867        mut cx: AsyncAppContext,
4868    ) -> Result<proto::ProjectEntryResponse> {
4869        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
4870        let worktree = this.read_with(&cx, |this, cx| {
4871            this.worktree_for_entry(entry_id, cx)
4872                .ok_or_else(|| anyhow!("worktree not found"))
4873        })?;
4874        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
4875        worktree
4876            .update(&mut cx, |worktree, cx| {
4877                worktree
4878                    .as_local_mut()
4879                    .unwrap()
4880                    .delete_entry(entry_id, cx)
4881                    .ok_or_else(|| anyhow!("invalid entry"))
4882            })?
4883            .await?;
4884        Ok(proto::ProjectEntryResponse {
4885            entry: None,
4886            worktree_scan_id: worktree_scan_id as u64,
4887        })
4888    }
4889
4890    async fn handle_update_diagnostic_summary(
4891        this: ModelHandle<Self>,
4892        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
4893        _: Arc<Client>,
4894        mut cx: AsyncAppContext,
4895    ) -> Result<()> {
4896        this.update(&mut cx, |this, cx| {
4897            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4898            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4899                if let Some(summary) = envelope.payload.summary {
4900                    let project_path = ProjectPath {
4901                        worktree_id,
4902                        path: Path::new(&summary.path).into(),
4903                    };
4904                    worktree.update(cx, |worktree, _| {
4905                        worktree
4906                            .as_remote_mut()
4907                            .unwrap()
4908                            .update_diagnostic_summary(project_path.path.clone(), &summary);
4909                    });
4910                    cx.emit(Event::DiagnosticsUpdated {
4911                        language_server_id: summary.language_server_id as usize,
4912                        path: project_path,
4913                    });
4914                }
4915            }
4916            Ok(())
4917        })
4918    }
4919
4920    async fn handle_start_language_server(
4921        this: ModelHandle<Self>,
4922        envelope: TypedEnvelope<proto::StartLanguageServer>,
4923        _: Arc<Client>,
4924        mut cx: AsyncAppContext,
4925    ) -> Result<()> {
4926        let server = envelope
4927            .payload
4928            .server
4929            .ok_or_else(|| anyhow!("invalid server"))?;
4930        this.update(&mut cx, |this, cx| {
4931            this.language_server_statuses.insert(
4932                server.id as usize,
4933                LanguageServerStatus {
4934                    name: server.name,
4935                    pending_work: Default::default(),
4936                    has_pending_diagnostic_updates: false,
4937                    progress_tokens: Default::default(),
4938                },
4939            );
4940            cx.notify();
4941        });
4942        Ok(())
4943    }
4944
4945    async fn handle_update_language_server(
4946        this: ModelHandle<Self>,
4947        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
4948        _: Arc<Client>,
4949        mut cx: AsyncAppContext,
4950    ) -> Result<()> {
4951        this.update(&mut cx, |this, cx| {
4952            let language_server_id = envelope.payload.language_server_id as usize;
4953
4954            match envelope
4955                .payload
4956                .variant
4957                .ok_or_else(|| anyhow!("invalid variant"))?
4958            {
4959                proto::update_language_server::Variant::WorkStart(payload) => {
4960                    this.on_lsp_work_start(
4961                        language_server_id,
4962                        payload.token,
4963                        LanguageServerProgress {
4964                            message: payload.message,
4965                            percentage: payload.percentage.map(|p| p as usize),
4966                            last_update_at: Instant::now(),
4967                        },
4968                        cx,
4969                    );
4970                }
4971
4972                proto::update_language_server::Variant::WorkProgress(payload) => {
4973                    this.on_lsp_work_progress(
4974                        language_server_id,
4975                        payload.token,
4976                        LanguageServerProgress {
4977                            message: payload.message,
4978                            percentage: payload.percentage.map(|p| p as usize),
4979                            last_update_at: Instant::now(),
4980                        },
4981                        cx,
4982                    );
4983                }
4984
4985                proto::update_language_server::Variant::WorkEnd(payload) => {
4986                    this.on_lsp_work_end(language_server_id, payload.token, cx);
4987                }
4988
4989                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
4990                    this.disk_based_diagnostics_started(language_server_id, cx);
4991                }
4992
4993                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
4994                    this.disk_based_diagnostics_finished(language_server_id, cx)
4995                }
4996            }
4997
4998            Ok(())
4999        })
5000    }
5001
5002    async fn handle_update_buffer(
5003        this: ModelHandle<Self>,
5004        envelope: TypedEnvelope<proto::UpdateBuffer>,
5005        _: Arc<Client>,
5006        mut cx: AsyncAppContext,
5007    ) -> Result<()> {
5008        this.update(&mut cx, |this, cx| {
5009            let payload = envelope.payload.clone();
5010            let buffer_id = payload.buffer_id;
5011            let ops = payload
5012                .operations
5013                .into_iter()
5014                .map(language::proto::deserialize_operation)
5015                .collect::<Result<Vec<_>, _>>()?;
5016            let is_remote = this.is_remote();
5017            match this.opened_buffers.entry(buffer_id) {
5018                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
5019                    OpenBuffer::Strong(buffer) => {
5020                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
5021                    }
5022                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
5023                    OpenBuffer::Weak(_) => {}
5024                },
5025                hash_map::Entry::Vacant(e) => {
5026                    assert!(
5027                        is_remote,
5028                        "received buffer update from {:?}",
5029                        envelope.original_sender_id
5030                    );
5031                    e.insert(OpenBuffer::Operations(ops));
5032                }
5033            }
5034            Ok(())
5035        })
5036    }
5037
5038    async fn handle_create_buffer_for_peer(
5039        this: ModelHandle<Self>,
5040        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5041        _: Arc<Client>,
5042        mut cx: AsyncAppContext,
5043    ) -> Result<()> {
5044        this.update(&mut cx, |this, cx| {
5045            match envelope
5046                .payload
5047                .variant
5048                .ok_or_else(|| anyhow!("missing variant"))?
5049            {
5050                proto::create_buffer_for_peer::Variant::State(mut state) => {
5051                    let mut buffer_file = None;
5052                    if let Some(file) = state.file.take() {
5053                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
5054                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
5055                            anyhow!("no worktree found for id {}", file.worktree_id)
5056                        })?;
5057                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
5058                            as Arc<dyn language::File>);
5059                    }
5060
5061                    let buffer_id = state.id;
5062                    let buffer = cx.add_model(|_| {
5063                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
5064                    });
5065                    this.incomplete_remote_buffers
5066                        .insert(buffer_id, Some(buffer));
5067                }
5068                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
5069                    let buffer = this
5070                        .incomplete_remote_buffers
5071                        .get(&chunk.buffer_id)
5072                        .cloned()
5073                        .flatten()
5074                        .ok_or_else(|| {
5075                            anyhow!(
5076                                "received chunk for buffer {} without initial state",
5077                                chunk.buffer_id
5078                            )
5079                        })?;
5080                    let operations = chunk
5081                        .operations
5082                        .into_iter()
5083                        .map(language::proto::deserialize_operation)
5084                        .collect::<Result<Vec<_>>>()?;
5085                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
5086
5087                    if chunk.is_last {
5088                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
5089                        this.register_buffer(&buffer, cx)?;
5090                    }
5091                }
5092            }
5093
5094            Ok(())
5095        })
5096    }
5097
5098    async fn handle_update_diff_base(
5099        this: ModelHandle<Self>,
5100        envelope: TypedEnvelope<proto::UpdateDiffBase>,
5101        _: Arc<Client>,
5102        mut cx: AsyncAppContext,
5103    ) -> Result<()> {
5104        this.update(&mut cx, |this, cx| {
5105            let buffer_id = envelope.payload.buffer_id;
5106            let diff_base = envelope.payload.diff_base;
5107            if let Some(buffer) = this
5108                .opened_buffers
5109                .get_mut(&buffer_id)
5110                .and_then(|b| b.upgrade(cx))
5111                .or_else(|| {
5112                    this.incomplete_remote_buffers
5113                        .get(&buffer_id)
5114                        .cloned()
5115                        .flatten()
5116                })
5117            {
5118                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
5119            }
5120            Ok(())
5121        })
5122    }
5123
5124    async fn handle_update_buffer_file(
5125        this: ModelHandle<Self>,
5126        envelope: TypedEnvelope<proto::UpdateBufferFile>,
5127        _: Arc<Client>,
5128        mut cx: AsyncAppContext,
5129    ) -> Result<()> {
5130        let buffer_id = envelope.payload.buffer_id;
5131        let is_incomplete = this.read_with(&cx, |this, _| {
5132            this.incomplete_remote_buffers.contains_key(&buffer_id)
5133        });
5134
5135        let buffer = if is_incomplete {
5136            Some(
5137                this.update(&mut cx, |this, cx| {
5138                    this.wait_for_remote_buffer(buffer_id, cx)
5139                })
5140                .await?,
5141            )
5142        } else {
5143            None
5144        };
5145
5146        this.update(&mut cx, |this, cx| {
5147            let payload = envelope.payload.clone();
5148            if let Some(buffer) = buffer.or_else(|| {
5149                this.opened_buffers
5150                    .get(&buffer_id)
5151                    .and_then(|b| b.upgrade(cx))
5152            }) {
5153                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
5154                let worktree = this
5155                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
5156                    .ok_or_else(|| anyhow!("no such worktree"))?;
5157                let file = File::from_proto(file, worktree, cx)?;
5158                buffer.update(cx, |buffer, cx| {
5159                    buffer.file_updated(Arc::new(file), cx).detach();
5160                });
5161                this.assign_language_to_buffer(&buffer, cx);
5162            }
5163            Ok(())
5164        })
5165    }
5166
5167    async fn handle_save_buffer(
5168        this: ModelHandle<Self>,
5169        envelope: TypedEnvelope<proto::SaveBuffer>,
5170        _: Arc<Client>,
5171        mut cx: AsyncAppContext,
5172    ) -> Result<proto::BufferSaved> {
5173        let buffer_id = envelope.payload.buffer_id;
5174        let requested_version = deserialize_version(envelope.payload.version);
5175
5176        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
5177            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
5178            let buffer = this
5179                .opened_buffers
5180                .get(&buffer_id)
5181                .and_then(|buffer| buffer.upgrade(cx))
5182                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
5183            Ok::<_, anyhow::Error>((project_id, buffer))
5184        })?;
5185        buffer
5186            .update(&mut cx, |buffer, _| {
5187                buffer.wait_for_version(requested_version)
5188            })
5189            .await;
5190
5191        let (saved_version, fingerprint, mtime) = this
5192            .update(&mut cx, |this, cx| this.save_buffer(buffer, cx))
5193            .await?;
5194        Ok(proto::BufferSaved {
5195            project_id,
5196            buffer_id,
5197            version: serialize_version(&saved_version),
5198            mtime: Some(mtime.into()),
5199            fingerprint: language::proto::serialize_fingerprint(fingerprint),
5200        })
5201    }
5202
5203    async fn handle_reload_buffers(
5204        this: ModelHandle<Self>,
5205        envelope: TypedEnvelope<proto::ReloadBuffers>,
5206        _: Arc<Client>,
5207        mut cx: AsyncAppContext,
5208    ) -> Result<proto::ReloadBuffersResponse> {
5209        let sender_id = envelope.original_sender_id()?;
5210        let reload = this.update(&mut cx, |this, cx| {
5211            let mut buffers = HashSet::default();
5212            for buffer_id in &envelope.payload.buffer_ids {
5213                buffers.insert(
5214                    this.opened_buffers
5215                        .get(buffer_id)
5216                        .and_then(|buffer| buffer.upgrade(cx))
5217                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5218                );
5219            }
5220            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
5221        })?;
5222
5223        let project_transaction = reload.await?;
5224        let project_transaction = this.update(&mut cx, |this, cx| {
5225            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5226        });
5227        Ok(proto::ReloadBuffersResponse {
5228            transaction: Some(project_transaction),
5229        })
5230    }
5231
5232    async fn handle_synchronize_buffers(
5233        this: ModelHandle<Self>,
5234        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5235        _: Arc<Client>,
5236        mut cx: AsyncAppContext,
5237    ) -> Result<proto::SynchronizeBuffersResponse> {
5238        let project_id = envelope.payload.project_id;
5239        let mut response = proto::SynchronizeBuffersResponse {
5240            buffers: Default::default(),
5241        };
5242
5243        this.update(&mut cx, |this, cx| {
5244            let Some(guest_id) = envelope.original_sender_id else {
5245                log::error!("missing original_sender_id on SynchronizeBuffers request");
5246                return;
5247            };
5248
5249            this.shared_buffers.entry(guest_id).or_default().clear();
5250            for buffer in envelope.payload.buffers {
5251                let buffer_id = buffer.id;
5252                let remote_version = language::proto::deserialize_version(buffer.version);
5253                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5254                    this.shared_buffers
5255                        .entry(guest_id)
5256                        .or_default()
5257                        .insert(buffer_id);
5258
5259                    let buffer = buffer.read(cx);
5260                    response.buffers.push(proto::BufferVersion {
5261                        id: buffer_id,
5262                        version: language::proto::serialize_version(&buffer.version),
5263                    });
5264
5265                    let operations = buffer.serialize_ops(Some(remote_version), cx);
5266                    let client = this.client.clone();
5267                    if let Some(file) = buffer.file() {
5268                        client
5269                            .send(proto::UpdateBufferFile {
5270                                project_id,
5271                                buffer_id: buffer_id as u64,
5272                                file: Some(file.to_proto()),
5273                            })
5274                            .log_err();
5275                    }
5276
5277                    client
5278                        .send(proto::UpdateDiffBase {
5279                            project_id,
5280                            buffer_id: buffer_id as u64,
5281                            diff_base: buffer.diff_base().map(Into::into),
5282                        })
5283                        .log_err();
5284
5285                    client
5286                        .send(proto::BufferReloaded {
5287                            project_id,
5288                            buffer_id,
5289                            version: language::proto::serialize_version(buffer.saved_version()),
5290                            mtime: Some(buffer.saved_mtime().into()),
5291                            fingerprint: language::proto::serialize_fingerprint(
5292                                buffer.saved_version_fingerprint(),
5293                            ),
5294                            line_ending: language::proto::serialize_line_ending(
5295                                buffer.line_ending(),
5296                            ) as i32,
5297                        })
5298                        .log_err();
5299
5300                    cx.background()
5301                        .spawn(
5302                            async move {
5303                                let operations = operations.await;
5304                                for chunk in split_operations(operations) {
5305                                    client
5306                                        .request(proto::UpdateBuffer {
5307                                            project_id,
5308                                            buffer_id,
5309                                            operations: chunk,
5310                                        })
5311                                        .await?;
5312                                }
5313                                anyhow::Ok(())
5314                            }
5315                            .log_err(),
5316                        )
5317                        .detach();
5318                }
5319            }
5320        });
5321
5322        Ok(response)
5323    }
5324
5325    async fn handle_format_buffers(
5326        this: ModelHandle<Self>,
5327        envelope: TypedEnvelope<proto::FormatBuffers>,
5328        _: Arc<Client>,
5329        mut cx: AsyncAppContext,
5330    ) -> Result<proto::FormatBuffersResponse> {
5331        let sender_id = envelope.original_sender_id()?;
5332        let format = this.update(&mut cx, |this, cx| {
5333            let mut buffers = HashSet::default();
5334            for buffer_id in &envelope.payload.buffer_ids {
5335                buffers.insert(
5336                    this.opened_buffers
5337                        .get(buffer_id)
5338                        .and_then(|buffer| buffer.upgrade(cx))
5339                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
5340                );
5341            }
5342            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
5343            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
5344        })?;
5345
5346        let project_transaction = format.await?;
5347        let project_transaction = this.update(&mut cx, |this, cx| {
5348            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5349        });
5350        Ok(proto::FormatBuffersResponse {
5351            transaction: Some(project_transaction),
5352        })
5353    }
5354
5355    async fn handle_get_completions(
5356        this: ModelHandle<Self>,
5357        envelope: TypedEnvelope<proto::GetCompletions>,
5358        _: Arc<Client>,
5359        mut cx: AsyncAppContext,
5360    ) -> Result<proto::GetCompletionsResponse> {
5361        let buffer = this.read_with(&cx, |this, cx| {
5362            this.opened_buffers
5363                .get(&envelope.payload.buffer_id)
5364                .and_then(|buffer| buffer.upgrade(cx))
5365                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5366        })?;
5367
5368        let position = envelope
5369            .payload
5370            .position
5371            .and_then(language::proto::deserialize_anchor)
5372            .map(|p| {
5373                buffer.read_with(&cx, |buffer, _| {
5374                    buffer.clip_point_utf16(Unclipped(p.to_point_utf16(buffer)), Bias::Left)
5375                })
5376            })
5377            .ok_or_else(|| anyhow!("invalid position"))?;
5378
5379        let version = deserialize_version(envelope.payload.version);
5380        buffer
5381            .update(&mut cx, |buffer, _| buffer.wait_for_version(version))
5382            .await;
5383        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5384
5385        let completions = this
5386            .update(&mut cx, |this, cx| this.completions(&buffer, position, cx))
5387            .await?;
5388
5389        Ok(proto::GetCompletionsResponse {
5390            completions: completions
5391                .iter()
5392                .map(language::proto::serialize_completion)
5393                .collect(),
5394            version: serialize_version(&version),
5395        })
5396    }
5397
5398    async fn handle_apply_additional_edits_for_completion(
5399        this: ModelHandle<Self>,
5400        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
5401        _: Arc<Client>,
5402        mut cx: AsyncAppContext,
5403    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
5404        let (buffer, completion) = this.update(&mut cx, |this, cx| {
5405            let buffer = this
5406                .opened_buffers
5407                .get(&envelope.payload.buffer_id)
5408                .and_then(|buffer| buffer.upgrade(cx))
5409                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5410            let language = buffer.read(cx).language();
5411            let completion = language::proto::deserialize_completion(
5412                envelope
5413                    .payload
5414                    .completion
5415                    .ok_or_else(|| anyhow!("invalid completion"))?,
5416                language.cloned(),
5417            );
5418            Ok::<_, anyhow::Error>((buffer, completion))
5419        })?;
5420
5421        let completion = completion.await?;
5422
5423        let apply_additional_edits = this.update(&mut cx, |this, cx| {
5424            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
5425        });
5426
5427        Ok(proto::ApplyCompletionAdditionalEditsResponse {
5428            transaction: apply_additional_edits
5429                .await?
5430                .as_ref()
5431                .map(language::proto::serialize_transaction),
5432        })
5433    }
5434
5435    async fn handle_get_code_actions(
5436        this: ModelHandle<Self>,
5437        envelope: TypedEnvelope<proto::GetCodeActions>,
5438        _: Arc<Client>,
5439        mut cx: AsyncAppContext,
5440    ) -> Result<proto::GetCodeActionsResponse> {
5441        let start = envelope
5442            .payload
5443            .start
5444            .and_then(language::proto::deserialize_anchor)
5445            .ok_or_else(|| anyhow!("invalid start"))?;
5446        let end = envelope
5447            .payload
5448            .end
5449            .and_then(language::proto::deserialize_anchor)
5450            .ok_or_else(|| anyhow!("invalid end"))?;
5451        let buffer = this.update(&mut cx, |this, cx| {
5452            this.opened_buffers
5453                .get(&envelope.payload.buffer_id)
5454                .and_then(|buffer| buffer.upgrade(cx))
5455                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
5456        })?;
5457        buffer
5458            .update(&mut cx, |buffer, _| {
5459                buffer.wait_for_version(deserialize_version(envelope.payload.version))
5460            })
5461            .await;
5462
5463        let version = buffer.read_with(&cx, |buffer, _| buffer.version());
5464        let code_actions = this.update(&mut cx, |this, cx| {
5465            Ok::<_, anyhow::Error>(this.code_actions(&buffer, start..end, cx))
5466        })?;
5467
5468        Ok(proto::GetCodeActionsResponse {
5469            actions: code_actions
5470                .await?
5471                .iter()
5472                .map(language::proto::serialize_code_action)
5473                .collect(),
5474            version: serialize_version(&version),
5475        })
5476    }
5477
5478    async fn handle_apply_code_action(
5479        this: ModelHandle<Self>,
5480        envelope: TypedEnvelope<proto::ApplyCodeAction>,
5481        _: Arc<Client>,
5482        mut cx: AsyncAppContext,
5483    ) -> Result<proto::ApplyCodeActionResponse> {
5484        let sender_id = envelope.original_sender_id()?;
5485        let action = language::proto::deserialize_code_action(
5486            envelope
5487                .payload
5488                .action
5489                .ok_or_else(|| anyhow!("invalid action"))?,
5490        )?;
5491        let apply_code_action = this.update(&mut cx, |this, cx| {
5492            let buffer = this
5493                .opened_buffers
5494                .get(&envelope.payload.buffer_id)
5495                .and_then(|buffer| buffer.upgrade(cx))
5496                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
5497            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
5498        })?;
5499
5500        let project_transaction = apply_code_action.await?;
5501        let project_transaction = this.update(&mut cx, |this, cx| {
5502            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
5503        });
5504        Ok(proto::ApplyCodeActionResponse {
5505            transaction: Some(project_transaction),
5506        })
5507    }
5508
5509    async fn handle_lsp_command<T: LspCommand>(
5510        this: ModelHandle<Self>,
5511        envelope: TypedEnvelope<T::ProtoRequest>,
5512        _: Arc<Client>,
5513        mut cx: AsyncAppContext,
5514    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
5515    where
5516        <T::LspRequest as lsp::request::Request>::Result: Send,
5517    {
5518        let sender_id = envelope.original_sender_id()?;
5519        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
5520        let buffer_handle = this.read_with(&cx, |this, _| {
5521            this.opened_buffers
5522                .get(&buffer_id)
5523                .and_then(|buffer| buffer.upgrade(&cx))
5524                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
5525        })?;
5526        let request = T::from_proto(
5527            envelope.payload,
5528            this.clone(),
5529            buffer_handle.clone(),
5530            cx.clone(),
5531        )
5532        .await?;
5533        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
5534        let response = this
5535            .update(&mut cx, |this, cx| {
5536                this.request_lsp(buffer_handle, request, cx)
5537            })
5538            .await?;
5539        this.update(&mut cx, |this, cx| {
5540            Ok(T::response_to_proto(
5541                response,
5542                this,
5543                sender_id,
5544                &buffer_version,
5545                cx,
5546            ))
5547        })
5548    }
5549
5550    async fn handle_get_project_symbols(
5551        this: ModelHandle<Self>,
5552        envelope: TypedEnvelope<proto::GetProjectSymbols>,
5553        _: Arc<Client>,
5554        mut cx: AsyncAppContext,
5555    ) -> Result<proto::GetProjectSymbolsResponse> {
5556        let symbols = this
5557            .update(&mut cx, |this, cx| {
5558                this.symbols(&envelope.payload.query, cx)
5559            })
5560            .await?;
5561
5562        Ok(proto::GetProjectSymbolsResponse {
5563            symbols: symbols.iter().map(serialize_symbol).collect(),
5564        })
5565    }
5566
5567    async fn handle_search_project(
5568        this: ModelHandle<Self>,
5569        envelope: TypedEnvelope<proto::SearchProject>,
5570        _: Arc<Client>,
5571        mut cx: AsyncAppContext,
5572    ) -> Result<proto::SearchProjectResponse> {
5573        let peer_id = envelope.original_sender_id()?;
5574        let query = SearchQuery::from_proto(envelope.payload)?;
5575        let result = this
5576            .update(&mut cx, |this, cx| this.search(query, cx))
5577            .await?;
5578
5579        this.update(&mut cx, |this, cx| {
5580            let mut locations = Vec::new();
5581            for (buffer, ranges) in result {
5582                for range in ranges {
5583                    let start = serialize_anchor(&range.start);
5584                    let end = serialize_anchor(&range.end);
5585                    let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5586                    locations.push(proto::Location {
5587                        buffer_id,
5588                        start: Some(start),
5589                        end: Some(end),
5590                    });
5591                }
5592            }
5593            Ok(proto::SearchProjectResponse { locations })
5594        })
5595    }
5596
5597    async fn handle_open_buffer_for_symbol(
5598        this: ModelHandle<Self>,
5599        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
5600        _: Arc<Client>,
5601        mut cx: AsyncAppContext,
5602    ) -> Result<proto::OpenBufferForSymbolResponse> {
5603        let peer_id = envelope.original_sender_id()?;
5604        let symbol = envelope
5605            .payload
5606            .symbol
5607            .ok_or_else(|| anyhow!("invalid symbol"))?;
5608        let symbol = this
5609            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
5610            .await?;
5611        let symbol = this.read_with(&cx, |this, _| {
5612            let signature = this.symbol_signature(&symbol.path);
5613            if signature == symbol.signature {
5614                Ok(symbol)
5615            } else {
5616                Err(anyhow!("invalid symbol signature"))
5617            }
5618        })?;
5619        let buffer = this
5620            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
5621            .await?;
5622
5623        Ok(proto::OpenBufferForSymbolResponse {
5624            buffer_id: this.update(&mut cx, |this, cx| {
5625                this.create_buffer_for_peer(&buffer, peer_id, cx)
5626            }),
5627        })
5628    }
5629
5630    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
5631        let mut hasher = Sha256::new();
5632        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
5633        hasher.update(project_path.path.to_string_lossy().as_bytes());
5634        hasher.update(self.nonce.to_be_bytes());
5635        hasher.finalize().as_slice().try_into().unwrap()
5636    }
5637
5638    async fn handle_open_buffer_by_id(
5639        this: ModelHandle<Self>,
5640        envelope: TypedEnvelope<proto::OpenBufferById>,
5641        _: Arc<Client>,
5642        mut cx: AsyncAppContext,
5643    ) -> Result<proto::OpenBufferResponse> {
5644        let peer_id = envelope.original_sender_id()?;
5645        let buffer = this
5646            .update(&mut cx, |this, cx| {
5647                this.open_buffer_by_id(envelope.payload.id, cx)
5648            })
5649            .await?;
5650        this.update(&mut cx, |this, cx| {
5651            Ok(proto::OpenBufferResponse {
5652                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5653            })
5654        })
5655    }
5656
5657    async fn handle_open_buffer_by_path(
5658        this: ModelHandle<Self>,
5659        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5660        _: Arc<Client>,
5661        mut cx: AsyncAppContext,
5662    ) -> Result<proto::OpenBufferResponse> {
5663        let peer_id = envelope.original_sender_id()?;
5664        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5665        let open_buffer = this.update(&mut cx, |this, cx| {
5666            this.open_buffer(
5667                ProjectPath {
5668                    worktree_id,
5669                    path: PathBuf::from(envelope.payload.path).into(),
5670                },
5671                cx,
5672            )
5673        });
5674
5675        let buffer = open_buffer.await?;
5676        this.update(&mut cx, |this, cx| {
5677            Ok(proto::OpenBufferResponse {
5678                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
5679            })
5680        })
5681    }
5682
5683    fn serialize_project_transaction_for_peer(
5684        &mut self,
5685        project_transaction: ProjectTransaction,
5686        peer_id: proto::PeerId,
5687        cx: &AppContext,
5688    ) -> proto::ProjectTransaction {
5689        let mut serialized_transaction = proto::ProjectTransaction {
5690            buffer_ids: Default::default(),
5691            transactions: Default::default(),
5692        };
5693        for (buffer, transaction) in project_transaction.0 {
5694            serialized_transaction
5695                .buffer_ids
5696                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
5697            serialized_transaction
5698                .transactions
5699                .push(language::proto::serialize_transaction(&transaction));
5700        }
5701        serialized_transaction
5702    }
5703
5704    fn deserialize_project_transaction(
5705        &mut self,
5706        message: proto::ProjectTransaction,
5707        push_to_history: bool,
5708        cx: &mut ModelContext<Self>,
5709    ) -> Task<Result<ProjectTransaction>> {
5710        cx.spawn(|this, mut cx| async move {
5711            let mut project_transaction = ProjectTransaction::default();
5712            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
5713            {
5714                let buffer = this
5715                    .update(&mut cx, |this, cx| {
5716                        this.wait_for_remote_buffer(buffer_id, cx)
5717                    })
5718                    .await?;
5719                let transaction = language::proto::deserialize_transaction(transaction)?;
5720                project_transaction.0.insert(buffer, transaction);
5721            }
5722
5723            for (buffer, transaction) in &project_transaction.0 {
5724                buffer
5725                    .update(&mut cx, |buffer, _| {
5726                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
5727                    })
5728                    .await;
5729
5730                if push_to_history {
5731                    buffer.update(&mut cx, |buffer, _| {
5732                        buffer.push_transaction(transaction.clone(), Instant::now());
5733                    });
5734                }
5735            }
5736
5737            Ok(project_transaction)
5738        })
5739    }
5740
5741    fn create_buffer_for_peer(
5742        &mut self,
5743        buffer: &ModelHandle<Buffer>,
5744        peer_id: proto::PeerId,
5745        cx: &AppContext,
5746    ) -> u64 {
5747        let buffer_id = buffer.read(cx).remote_id();
5748        if let Some(project_id) = self.remote_id() {
5749            let shared_buffers = self.shared_buffers.entry(peer_id).or_default();
5750            if shared_buffers.insert(buffer_id) {
5751                let buffer = buffer.read(cx);
5752                let state = buffer.to_proto();
5753                let operations = buffer.serialize_ops(None, cx);
5754                let client = self.client.clone();
5755                cx.background()
5756                    .spawn(
5757                        async move {
5758                            let operations = operations.await;
5759
5760                            client.send(proto::CreateBufferForPeer {
5761                                project_id,
5762                                peer_id: Some(peer_id),
5763                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
5764                            })?;
5765
5766                            let mut chunks = split_operations(operations).peekable();
5767                            while let Some(chunk) = chunks.next() {
5768                                let is_last = chunks.peek().is_none();
5769                                client.send(proto::CreateBufferForPeer {
5770                                    project_id,
5771                                    peer_id: Some(peer_id),
5772                                    variant: Some(proto::create_buffer_for_peer::Variant::Chunk(
5773                                        proto::BufferChunk {
5774                                            buffer_id,
5775                                            operations: chunk,
5776                                            is_last,
5777                                        },
5778                                    )),
5779                                })?;
5780                            }
5781
5782                            Ok(())
5783                        }
5784                        .log_err(),
5785                    )
5786                    .detach();
5787            }
5788        }
5789
5790        buffer_id
5791    }
5792
5793    fn wait_for_remote_buffer(
5794        &mut self,
5795        id: u64,
5796        cx: &mut ModelContext<Self>,
5797    ) -> Task<Result<ModelHandle<Buffer>>> {
5798        let mut opened_buffer_rx = self.opened_buffer.1.clone();
5799
5800        cx.spawn_weak(|this, mut cx| async move {
5801            let buffer = loop {
5802                let Some(this) = this.upgrade(&cx) else {
5803                    return Err(anyhow!("project dropped"));
5804                };
5805                let buffer = this.read_with(&cx, |this, cx| {
5806                    this.opened_buffers
5807                        .get(&id)
5808                        .and_then(|buffer| buffer.upgrade(cx))
5809                });
5810                if let Some(buffer) = buffer {
5811                    break buffer;
5812                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
5813                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
5814                }
5815
5816                this.update(&mut cx, |this, _| {
5817                    this.incomplete_remote_buffers.entry(id).or_default();
5818                });
5819                drop(this);
5820                opened_buffer_rx
5821                    .next()
5822                    .await
5823                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
5824            };
5825            buffer.update(&mut cx, |buffer, cx| buffer.git_diff_recalc(cx));
5826            Ok(buffer)
5827        })
5828    }
5829
5830    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
5831        let project_id = match self.client_state.as_ref() {
5832            Some(ProjectClientState::Remote {
5833                sharing_has_stopped,
5834                remote_id,
5835                ..
5836            }) => {
5837                if *sharing_has_stopped {
5838                    return Task::ready(Err(anyhow!(
5839                        "can't synchronize remote buffers on a readonly project"
5840                    )));
5841                } else {
5842                    *remote_id
5843                }
5844            }
5845            Some(ProjectClientState::Local { .. }) | None => {
5846                return Task::ready(Err(anyhow!(
5847                    "can't synchronize remote buffers on a local project"
5848                )))
5849            }
5850        };
5851
5852        let client = self.client.clone();
5853        cx.spawn(|this, cx| async move {
5854            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
5855                let buffers = this
5856                    .opened_buffers
5857                    .iter()
5858                    .filter_map(|(id, buffer)| {
5859                        let buffer = buffer.upgrade(cx)?;
5860                        Some(proto::BufferVersion {
5861                            id: *id,
5862                            version: language::proto::serialize_version(&buffer.read(cx).version),
5863                        })
5864                    })
5865                    .collect();
5866                let incomplete_buffer_ids = this
5867                    .incomplete_remote_buffers
5868                    .keys()
5869                    .copied()
5870                    .collect::<Vec<_>>();
5871
5872                (buffers, incomplete_buffer_ids)
5873            });
5874            let response = client
5875                .request(proto::SynchronizeBuffers {
5876                    project_id,
5877                    buffers,
5878                })
5879                .await?;
5880
5881            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
5882                let client = client.clone();
5883                let buffer_id = buffer.id;
5884                let remote_version = language::proto::deserialize_version(buffer.version);
5885                this.read_with(&cx, |this, cx| {
5886                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5887                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
5888                        cx.background().spawn(async move {
5889                            let operations = operations.await;
5890                            for chunk in split_operations(operations) {
5891                                client
5892                                    .request(proto::UpdateBuffer {
5893                                        project_id,
5894                                        buffer_id,
5895                                        operations: chunk,
5896                                    })
5897                                    .await?;
5898                            }
5899                            anyhow::Ok(())
5900                        })
5901                    } else {
5902                        Task::ready(Ok(()))
5903                    }
5904                })
5905            });
5906
5907            // Any incomplete buffers have open requests waiting. Request that the host sends
5908            // creates these buffers for us again to unblock any waiting futures.
5909            for id in incomplete_buffer_ids {
5910                cx.background()
5911                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
5912                    .detach();
5913            }
5914
5915            futures::future::join_all(send_updates_for_buffers)
5916                .await
5917                .into_iter()
5918                .collect()
5919        })
5920    }
5921
5922    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
5923        self.worktrees(cx)
5924            .map(|worktree| {
5925                let worktree = worktree.read(cx);
5926                proto::WorktreeMetadata {
5927                    id: worktree.id().to_proto(),
5928                    root_name: worktree.root_name().into(),
5929                    visible: worktree.is_visible(),
5930                    abs_path: worktree.abs_path().to_string_lossy().into(),
5931                }
5932            })
5933            .collect()
5934    }
5935
5936    fn set_worktrees_from_proto(
5937        &mut self,
5938        worktrees: Vec<proto::WorktreeMetadata>,
5939        cx: &mut ModelContext<Project>,
5940    ) -> Result<()> {
5941        let replica_id = self.replica_id();
5942        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
5943
5944        let mut old_worktrees_by_id = self
5945            .worktrees
5946            .drain(..)
5947            .filter_map(|worktree| {
5948                let worktree = worktree.upgrade(cx)?;
5949                Some((worktree.read(cx).id(), worktree))
5950            })
5951            .collect::<HashMap<_, _>>();
5952
5953        for worktree in worktrees {
5954            if let Some(old_worktree) =
5955                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
5956            {
5957                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
5958            } else {
5959                let worktree =
5960                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
5961                let _ = self.add_worktree(&worktree, cx);
5962            }
5963        }
5964
5965        let _ = self.metadata_changed(cx);
5966        for (id, _) in old_worktrees_by_id {
5967            cx.emit(Event::WorktreeRemoved(id));
5968        }
5969
5970        Ok(())
5971    }
5972
5973    fn set_collaborators_from_proto(
5974        &mut self,
5975        messages: Vec<proto::Collaborator>,
5976        cx: &mut ModelContext<Self>,
5977    ) -> Result<()> {
5978        let mut collaborators = HashMap::default();
5979        for message in messages {
5980            let collaborator = Collaborator::from_proto(message)?;
5981            collaborators.insert(collaborator.peer_id, collaborator);
5982        }
5983        for old_peer_id in self.collaborators.keys() {
5984            if !collaborators.contains_key(old_peer_id) {
5985                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5986            }
5987        }
5988        self.collaborators = collaborators;
5989        Ok(())
5990    }
5991
5992    fn deserialize_symbol(
5993        &self,
5994        serialized_symbol: proto::Symbol,
5995    ) -> impl Future<Output = Result<Symbol>> {
5996        let languages = self.languages.clone();
5997        async move {
5998            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
5999            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
6000            let start = serialized_symbol
6001                .start
6002                .ok_or_else(|| anyhow!("invalid start"))?;
6003            let end = serialized_symbol
6004                .end
6005                .ok_or_else(|| anyhow!("invalid end"))?;
6006            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
6007            let path = ProjectPath {
6008                worktree_id,
6009                path: PathBuf::from(serialized_symbol.path).into(),
6010            };
6011            let language = languages.language_for_path(&path.path);
6012            Ok(Symbol {
6013                language_server_name: LanguageServerName(
6014                    serialized_symbol.language_server_name.into(),
6015                ),
6016                source_worktree_id,
6017                path,
6018                label: {
6019                    match language {
6020                        Some(language) => {
6021                            language
6022                                .label_for_symbol(&serialized_symbol.name, kind)
6023                                .await
6024                        }
6025                        None => None,
6026                    }
6027                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
6028                },
6029
6030                name: serialized_symbol.name,
6031                range: Unclipped(PointUtf16::new(start.row, start.column))
6032                    ..Unclipped(PointUtf16::new(end.row, end.column)),
6033                kind,
6034                signature: serialized_symbol
6035                    .signature
6036                    .try_into()
6037                    .map_err(|_| anyhow!("invalid signature"))?,
6038            })
6039        }
6040    }
6041
6042    async fn handle_buffer_saved(
6043        this: ModelHandle<Self>,
6044        envelope: TypedEnvelope<proto::BufferSaved>,
6045        _: Arc<Client>,
6046        mut cx: AsyncAppContext,
6047    ) -> Result<()> {
6048        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
6049        let version = deserialize_version(envelope.payload.version);
6050        let mtime = envelope
6051            .payload
6052            .mtime
6053            .ok_or_else(|| anyhow!("missing mtime"))?
6054            .into();
6055
6056        this.update(&mut cx, |this, cx| {
6057            let buffer = this
6058                .opened_buffers
6059                .get(&envelope.payload.buffer_id)
6060                .and_then(|buffer| buffer.upgrade(cx));
6061            if let Some(buffer) = buffer {
6062                buffer.update(cx, |buffer, cx| {
6063                    buffer.did_save(version, fingerprint, mtime, cx);
6064                });
6065            }
6066            Ok(())
6067        })
6068    }
6069
6070    async fn handle_buffer_reloaded(
6071        this: ModelHandle<Self>,
6072        envelope: TypedEnvelope<proto::BufferReloaded>,
6073        _: Arc<Client>,
6074        mut cx: AsyncAppContext,
6075    ) -> Result<()> {
6076        let payload = envelope.payload;
6077        let version = deserialize_version(payload.version);
6078        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
6079        let line_ending = deserialize_line_ending(
6080            proto::LineEnding::from_i32(payload.line_ending)
6081                .ok_or_else(|| anyhow!("missing line ending"))?,
6082        );
6083        let mtime = payload
6084            .mtime
6085            .ok_or_else(|| anyhow!("missing mtime"))?
6086            .into();
6087        this.update(&mut cx, |this, cx| {
6088            let buffer = this
6089                .opened_buffers
6090                .get(&payload.buffer_id)
6091                .and_then(|buffer| buffer.upgrade(cx));
6092            if let Some(buffer) = buffer {
6093                buffer.update(cx, |buffer, cx| {
6094                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
6095                });
6096            }
6097            Ok(())
6098        })
6099    }
6100
6101    #[allow(clippy::type_complexity)]
6102    fn edits_from_lsp(
6103        &mut self,
6104        buffer: &ModelHandle<Buffer>,
6105        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
6106        version: Option<i32>,
6107        cx: &mut ModelContext<Self>,
6108    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
6109        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx);
6110        cx.background().spawn(async move {
6111            let snapshot = snapshot?;
6112            let mut lsp_edits = lsp_edits
6113                .into_iter()
6114                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
6115                .collect::<Vec<_>>();
6116            lsp_edits.sort_by_key(|(range, _)| range.start);
6117
6118            let mut lsp_edits = lsp_edits.into_iter().peekable();
6119            let mut edits = Vec::new();
6120            while let Some((range, mut new_text)) = lsp_edits.next() {
6121                // Clip invalid ranges provided by the language server.
6122                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
6123                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
6124
6125                // Combine any LSP edits that are adjacent.
6126                //
6127                // Also, combine LSP edits that are separated from each other by only
6128                // a newline. This is important because for some code actions,
6129                // Rust-analyzer rewrites the entire buffer via a series of edits that
6130                // are separated by unchanged newline characters.
6131                //
6132                // In order for the diffing logic below to work properly, any edits that
6133                // cancel each other out must be combined into one.
6134                while let Some((next_range, next_text)) = lsp_edits.peek() {
6135                    if next_range.start.0 > range.end {
6136                        if next_range.start.0.row > range.end.row + 1
6137                            || next_range.start.0.column > 0
6138                            || snapshot.clip_point_utf16(
6139                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
6140                                Bias::Left,
6141                            ) > range.end
6142                        {
6143                            break;
6144                        }
6145                        new_text.push('\n');
6146                    }
6147                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
6148                    new_text.push_str(next_text);
6149                    lsp_edits.next();
6150                }
6151
6152                // For multiline edits, perform a diff of the old and new text so that
6153                // we can identify the changes more precisely, preserving the locations
6154                // of any anchors positioned in the unchanged regions.
6155                if range.end.row > range.start.row {
6156                    let mut offset = range.start.to_offset(&snapshot);
6157                    let old_text = snapshot.text_for_range(range).collect::<String>();
6158
6159                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
6160                    let mut moved_since_edit = true;
6161                    for change in diff.iter_all_changes() {
6162                        let tag = change.tag();
6163                        let value = change.value();
6164                        match tag {
6165                            ChangeTag::Equal => {
6166                                offset += value.len();
6167                                moved_since_edit = true;
6168                            }
6169                            ChangeTag::Delete => {
6170                                let start = snapshot.anchor_after(offset);
6171                                let end = snapshot.anchor_before(offset + value.len());
6172                                if moved_since_edit {
6173                                    edits.push((start..end, String::new()));
6174                                } else {
6175                                    edits.last_mut().unwrap().0.end = end;
6176                                }
6177                                offset += value.len();
6178                                moved_since_edit = false;
6179                            }
6180                            ChangeTag::Insert => {
6181                                if moved_since_edit {
6182                                    let anchor = snapshot.anchor_after(offset);
6183                                    edits.push((anchor..anchor, value.to_string()));
6184                                } else {
6185                                    edits.last_mut().unwrap().1.push_str(value);
6186                                }
6187                                moved_since_edit = false;
6188                            }
6189                        }
6190                    }
6191                } else if range.end == range.start {
6192                    let anchor = snapshot.anchor_after(range.start);
6193                    edits.push((anchor..anchor, new_text));
6194                } else {
6195                    let edit_start = snapshot.anchor_after(range.start);
6196                    let edit_end = snapshot.anchor_before(range.end);
6197                    edits.push((edit_start..edit_end, new_text));
6198                }
6199            }
6200
6201            Ok(edits)
6202        })
6203    }
6204
6205    fn buffer_snapshot_for_lsp_version(
6206        &mut self,
6207        buffer: &ModelHandle<Buffer>,
6208        version: Option<i32>,
6209        cx: &AppContext,
6210    ) -> Result<TextBufferSnapshot> {
6211        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
6212
6213        if let Some(version) = version {
6214            let buffer_id = buffer.read(cx).remote_id();
6215            let snapshots = self
6216                .buffer_snapshots
6217                .get_mut(&buffer_id)
6218                .ok_or_else(|| anyhow!("no snapshot found for buffer {}", buffer_id))?;
6219            let found_snapshot = snapshots
6220                .binary_search_by_key(&version, |e| e.0)
6221                .map(|ix| snapshots[ix].1.clone())
6222                .map_err(|_| {
6223                    anyhow!(
6224                        "snapshot not found for buffer {} at version {}",
6225                        buffer_id,
6226                        version
6227                    )
6228                })?;
6229            snapshots.retain(|(snapshot_version, _)| {
6230                snapshot_version + OLD_VERSIONS_TO_RETAIN >= version
6231            });
6232            Ok(found_snapshot)
6233        } else {
6234            Ok((buffer.read(cx)).text_snapshot())
6235        }
6236    }
6237
6238    fn language_server_for_buffer(
6239        &self,
6240        buffer: &Buffer,
6241        cx: &AppContext,
6242    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
6243        let server_id = self.language_server_id_for_buffer(buffer, cx)?;
6244        let server = self.language_servers.get(&server_id)?;
6245        if let LanguageServerState::Running {
6246            adapter, server, ..
6247        } = server
6248        {
6249            Some((adapter, server))
6250        } else {
6251            None
6252        }
6253    }
6254
6255    fn language_server_id_for_buffer(&self, buffer: &Buffer, cx: &AppContext) -> Option<usize> {
6256        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
6257            let name = language.lsp_adapter()?.name.clone();
6258            let worktree_id = file.worktree_id(cx);
6259            let key = (worktree_id, name);
6260            self.language_server_ids.get(&key).copied()
6261        } else {
6262            None
6263        }
6264    }
6265}
6266
6267impl WorktreeHandle {
6268    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
6269        match self {
6270            WorktreeHandle::Strong(handle) => Some(handle.clone()),
6271            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
6272        }
6273    }
6274}
6275
6276impl OpenBuffer {
6277    pub fn upgrade(&self, cx: &impl UpgradeModelHandle) -> Option<ModelHandle<Buffer>> {
6278        match self {
6279            OpenBuffer::Strong(handle) => Some(handle.clone()),
6280            OpenBuffer::Weak(handle) => handle.upgrade(cx),
6281            OpenBuffer::Operations(_) => None,
6282        }
6283    }
6284}
6285
6286pub struct PathMatchCandidateSet {
6287    pub snapshot: Snapshot,
6288    pub include_ignored: bool,
6289    pub include_root_name: bool,
6290}
6291
6292impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6293    type Candidates = PathMatchCandidateSetIter<'a>;
6294
6295    fn id(&self) -> usize {
6296        self.snapshot.id().to_usize()
6297    }
6298
6299    fn len(&self) -> usize {
6300        if self.include_ignored {
6301            self.snapshot.file_count()
6302        } else {
6303            self.snapshot.visible_file_count()
6304        }
6305    }
6306
6307    fn prefix(&self) -> Arc<str> {
6308        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
6309            self.snapshot.root_name().into()
6310        } else if self.include_root_name {
6311            format!("{}/", self.snapshot.root_name()).into()
6312        } else {
6313            "".into()
6314        }
6315    }
6316
6317    fn candidates(&'a self, start: usize) -> Self::Candidates {
6318        PathMatchCandidateSetIter {
6319            traversal: self.snapshot.files(self.include_ignored, start),
6320        }
6321    }
6322}
6323
6324pub struct PathMatchCandidateSetIter<'a> {
6325    traversal: Traversal<'a>,
6326}
6327
6328impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6329    type Item = fuzzy::PathMatchCandidate<'a>;
6330
6331    fn next(&mut self) -> Option<Self::Item> {
6332        self.traversal.next().map(|entry| {
6333            if let EntryKind::File(char_bag) = entry.kind {
6334                fuzzy::PathMatchCandidate {
6335                    path: &entry.path,
6336                    char_bag,
6337                }
6338            } else {
6339                unreachable!()
6340            }
6341        })
6342    }
6343}
6344
6345impl Entity for Project {
6346    type Event = Event;
6347
6348    fn release(&mut self, _: &mut gpui::MutableAppContext) {
6349        match &self.client_state {
6350            Some(ProjectClientState::Local { remote_id, .. }) => {
6351                let _ = self.client.send(proto::UnshareProject {
6352                    project_id: *remote_id,
6353                });
6354            }
6355            Some(ProjectClientState::Remote { remote_id, .. }) => {
6356                let _ = self.client.send(proto::LeaveProject {
6357                    project_id: *remote_id,
6358                });
6359            }
6360            _ => {}
6361        }
6362    }
6363
6364    fn app_will_quit(
6365        &mut self,
6366        _: &mut MutableAppContext,
6367    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
6368        let shutdown_futures = self
6369            .language_servers
6370            .drain()
6371            .map(|(_, server_state)| async {
6372                match server_state {
6373                    LanguageServerState::Running { server, .. } => server.shutdown()?.await,
6374                    LanguageServerState::Starting(starting_server) => {
6375                        starting_server.await?.shutdown()?.await
6376                    }
6377                }
6378            })
6379            .collect::<Vec<_>>();
6380
6381        Some(
6382            async move {
6383                futures::future::join_all(shutdown_futures).await;
6384            }
6385            .boxed(),
6386        )
6387    }
6388}
6389
6390impl Collaborator {
6391    fn from_proto(message: proto::Collaborator) -> Result<Self> {
6392        Ok(Self {
6393            peer_id: message.peer_id.ok_or_else(|| anyhow!("invalid peer id"))?,
6394            replica_id: message.replica_id as ReplicaId,
6395        })
6396    }
6397}
6398
6399impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
6400    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6401        Self {
6402            worktree_id,
6403            path: path.as_ref().into(),
6404        }
6405    }
6406}
6407
6408fn split_operations(
6409    mut operations: Vec<proto::Operation>,
6410) -> impl Iterator<Item = Vec<proto::Operation>> {
6411    #[cfg(any(test, feature = "test-support"))]
6412    const CHUNK_SIZE: usize = 5;
6413
6414    #[cfg(not(any(test, feature = "test-support")))]
6415    const CHUNK_SIZE: usize = 100;
6416
6417    let mut done = false;
6418    std::iter::from_fn(move || {
6419        if done {
6420            return None;
6421        }
6422
6423        let operations = operations
6424            .drain(..cmp::min(CHUNK_SIZE, operations.len()))
6425            .collect::<Vec<_>>();
6426        if operations.is_empty() {
6427            done = true;
6428        }
6429        Some(operations)
6430    })
6431}
6432
6433fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
6434    proto::Symbol {
6435        language_server_name: symbol.language_server_name.0.to_string(),
6436        source_worktree_id: symbol.source_worktree_id.to_proto(),
6437        worktree_id: symbol.path.worktree_id.to_proto(),
6438        path: symbol.path.path.to_string_lossy().to_string(),
6439        name: symbol.name.clone(),
6440        kind: unsafe { mem::transmute(symbol.kind) },
6441        start: Some(proto::PointUtf16 {
6442            row: symbol.range.start.0.row,
6443            column: symbol.range.start.0.column,
6444        }),
6445        end: Some(proto::PointUtf16 {
6446            row: symbol.range.end.0.row,
6447            column: symbol.range.end.0.column,
6448        }),
6449        signature: symbol.signature.to_vec(),
6450    }
6451}
6452
6453fn relativize_path(base: &Path, path: &Path) -> PathBuf {
6454    let mut path_components = path.components();
6455    let mut base_components = base.components();
6456    let mut components: Vec<Component> = Vec::new();
6457    loop {
6458        match (path_components.next(), base_components.next()) {
6459            (None, None) => break,
6460            (Some(a), None) => {
6461                components.push(a);
6462                components.extend(path_components.by_ref());
6463                break;
6464            }
6465            (None, _) => components.push(Component::ParentDir),
6466            (Some(a), Some(b)) if components.is_empty() && a == b => (),
6467            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
6468            (Some(a), Some(_)) => {
6469                components.push(Component::ParentDir);
6470                for _ in base_components {
6471                    components.push(Component::ParentDir);
6472                }
6473                components.push(a);
6474                components.extend(path_components.by_ref());
6475                break;
6476            }
6477        }
6478    }
6479    components.iter().map(|c| c.as_os_str()).collect()
6480}
6481
6482impl Item for Buffer {
6483    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
6484        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
6485    }
6486
6487    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
6488        File::from_dyn(self.file()).map(|file| ProjectPath {
6489            worktree_id: file.worktree_id(cx),
6490            path: file.path().clone(),
6491        })
6492    }
6493}