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