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, TextBufferSnapshot, ToOffset, ToPointUtf16, Transaction,
  32    Unclipped,
  33};
  34use lsp::{
  35    DiagnosticSeverity, DiagnosticTag, DocumentHighlightKind, LanguageServer, LanguageString,
  36    MarkedString,
  37};
  38use lsp_command::*;
  39use parking_lot::Mutex;
  40use postage::watch;
  41use rand::prelude::*;
  42use search::SearchQuery;
  43use serde::Serialize;
  44use settings::{FormatOnSave, Formatter, Settings};
  45use sha2::{Digest, Sha256};
  46use similar::{ChangeTag, TextDiff};
  47use std::{
  48    cell::RefCell,
  49    cmp::{self, Ordering},
  50    convert::TryInto,
  51    hash::Hash,
  52    mem,
  53    num::NonZeroU32,
  54    ops::Range,
  55    path::{Component, Path, PathBuf},
  56    rc::Rc,
  57    str,
  58    sync::{
  59        atomic::{AtomicUsize, Ordering::SeqCst},
  60        Arc,
  61    },
  62    time::{Duration, Instant},
  63};
  64use terminal::{Terminal, TerminalBuilder};
  65use util::{debug_panic, defer, post_inc, ResultExt, TryFutureExt as _};
  66
  67pub use fs::*;
  68pub use worktree::*;
  69
  70pub trait Item {
  71    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
  72    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
  73}
  74
  75// Language server state is stored across 3 collections:
  76//     language_servers =>
  77//         a mapping from unique server id to LanguageServerState which can either be a task for a
  78//         server in the process of starting, or a running server with adapter and language server arcs
  79//     language_server_ids => a mapping from worktreeId and server name to the unique server id
  80//     language_server_statuses => a mapping from unique server id to the current server status
  81//
  82// Multiple worktrees can map to the same language server for example when you jump to the definition
  83// of a file in the standard library. So language_server_ids is used to look up which server is active
  84// for a given worktree and language server name
  85//
  86// When starting a language server, first the id map is checked to make sure a server isn't already available
  87// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
  88// the Starting variant of LanguageServerState is stored in the language_servers map.
  89pub struct Project {
  90    worktrees: Vec<WorktreeHandle>,
  91    active_entry: Option<ProjectEntryId>,
  92    languages: Arc<LanguageRegistry>,
  93    language_servers: HashMap<usize, LanguageServerState>,
  94    language_server_ids: HashMap<(WorktreeId, LanguageServerName), usize>,
  95    language_server_statuses: BTreeMap<usize, LanguageServerStatus>,
  96    language_server_settings: Arc<Mutex<serde_json::Value>>,
  97    last_workspace_edits_by_language_server: HashMap<usize, ProjectTransaction>,
  98    next_language_server_id: usize,
  99    client: Arc<client::Client>,
 100    next_entry_id: Arc<AtomicUsize>,
 101    next_diagnostic_group_id: usize,
 102    user_store: ModelHandle<UserStore>,
 103    fs: Arc<dyn Fs>,
 104    client_state: Option<ProjectClientState>,
 105    collaborators: HashMap<proto::PeerId, Collaborator>,
 106    client_subscriptions: Vec<client::Subscription>,
 107    _subscriptions: Vec<gpui::Subscription>,
 108    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 109    shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
 110    #[allow(clippy::type_complexity)]
 111    loading_buffers_by_path: HashMap<
 112        ProjectPath,
 113        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 114    >,
 115    #[allow(clippy::type_complexity)]
 116    loading_local_worktrees:
 117        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 118    opened_buffers: HashMap<u64, OpenBuffer>,
 119    /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
 120    /// Used for re-issuing buffer requests when peers temporarily disconnect
 121    incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
 122    buffer_snapshots: HashMap<u64, Vec<(i32, TextBufferSnapshot)>>,
 123    buffers_being_formatted: HashSet<usize>,
 124    nonce: u128,
 125    _maintain_buffer_languages: Task<()>,
 126}
 127
 128enum OpenBuffer {
 129    Strong(ModelHandle<Buffer>),
 130    Weak(WeakModelHandle<Buffer>),
 131    Operations(Vec<Operation>),
 132}
 133
 134enum WorktreeHandle {
 135    Strong(ModelHandle<Worktree>),
 136    Weak(WeakModelHandle<Worktree>),
 137}
 138
 139enum ProjectClientState {
 140    Local {
 141        remote_id: u64,
 142        metadata_changed: mpsc::UnboundedSender<oneshot::Sender<()>>,
 143        _maintain_metadata: Task<()>,
 144    },
 145    Remote {
 146        sharing_has_stopped: bool,
 147        remote_id: u64,
 148        replica_id: ReplicaId,
 149    },
 150}
 151
 152#[derive(Clone, Debug)]
 153pub struct Collaborator {
 154    pub peer_id: proto::PeerId,
 155    pub replica_id: ReplicaId,
 156}
 157
 158#[derive(Clone, Debug, PartialEq, Eq)]
 159pub enum Event {
 160    ActiveEntryChanged(Option<ProjectEntryId>),
 161    WorktreeAdded,
 162    WorktreeRemoved(WorktreeId),
 163    DiskBasedDiagnosticsStarted {
 164        language_server_id: usize,
 165    },
 166    DiskBasedDiagnosticsFinished {
 167        language_server_id: usize,
 168    },
 169    DiagnosticsUpdated {
 170        path: ProjectPath,
 171        language_server_id: usize,
 172    },
 173    RemoteIdChanged(Option<u64>),
 174    DisconnectedFromHost,
 175    CollaboratorUpdated {
 176        old_peer_id: proto::PeerId,
 177        new_peer_id: proto::PeerId,
 178    },
 179    CollaboratorLeft(proto::PeerId),
 180}
 181
 182pub enum LanguageServerState {
 183    Starting(Task<Option<Arc<LanguageServer>>>),
 184    Running {
 185        language: Arc<Language>,
 186        adapter: Arc<CachedLspAdapter>,
 187        server: Arc<LanguageServer>,
 188        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 189    },
 190}
 191
 192#[derive(Serialize)]
 193pub struct LanguageServerStatus {
 194    pub name: String,
 195    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 196    pub has_pending_diagnostic_updates: bool,
 197    progress_tokens: HashSet<String>,
 198}
 199
 200#[derive(Clone, Debug, Serialize)]
 201pub struct LanguageServerProgress {
 202    pub message: Option<String>,
 203    pub percentage: Option<usize>,
 204    #[serde(skip_serializing)]
 205    pub last_update_at: Instant,
 206}
 207
 208#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 209pub struct ProjectPath {
 210    pub worktree_id: WorktreeId,
 211    pub path: Arc<Path>,
 212}
 213
 214#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 215pub struct DiagnosticSummary {
 216    pub language_server_id: usize,
 217    pub error_count: usize,
 218    pub warning_count: usize,
 219}
 220
 221#[derive(Debug, Clone)]
 222pub struct Location {
 223    pub buffer: ModelHandle<Buffer>,
 224    pub range: Range<language::Anchor>,
 225}
 226
 227#[derive(Debug, Clone)]
 228pub struct LocationLink {
 229    pub origin: Option<Location>,
 230    pub target: Location,
 231}
 232
 233#[derive(Debug)]
 234pub struct DocumentHighlight {
 235    pub range: Range<language::Anchor>,
 236    pub kind: DocumentHighlightKind,
 237}
 238
 239#[derive(Clone, Debug)]
 240pub struct Symbol {
 241    pub language_server_name: LanguageServerName,
 242    pub source_worktree_id: WorktreeId,
 243    pub path: ProjectPath,
 244    pub label: CodeLabel,
 245    pub name: String,
 246    pub kind: lsp::SymbolKind,
 247    pub range: Range<Unclipped<PointUtf16>>,
 248    pub signature: [u8; 32],
 249}
 250
 251#[derive(Clone, Debug, PartialEq)]
 252pub struct HoverBlock {
 253    pub text: String,
 254    pub language: Option<String>,
 255}
 256
 257impl HoverBlock {
 258    fn try_new(marked_string: MarkedString) -> Option<Self> {
 259        let result = match marked_string {
 260            MarkedString::LanguageString(LanguageString { language, value }) => HoverBlock {
 261                text: value,
 262                language: Some(language),
 263            },
 264            MarkedString::String(text) => HoverBlock {
 265                text,
 266                language: None,
 267            },
 268        };
 269        if result.text.is_empty() {
 270            None
 271        } else {
 272            Some(result)
 273        }
 274    }
 275}
 276
 277#[derive(Debug)]
 278pub struct Hover {
 279    pub contents: Vec<HoverBlock>,
 280    pub range: Option<Range<language::Anchor>>,
 281}
 282
 283#[derive(Default)]
 284pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 285
 286impl DiagnosticSummary {
 287    fn new<'a, T: 'a>(
 288        language_server_id: usize,
 289        diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>,
 290    ) -> Self {
 291        let mut this = Self {
 292            language_server_id,
 293            error_count: 0,
 294            warning_count: 0,
 295        };
 296
 297        for entry in diagnostics {
 298            if entry.diagnostic.is_primary {
 299                match entry.diagnostic.severity {
 300                    DiagnosticSeverity::ERROR => this.error_count += 1,
 301                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 302                    _ => {}
 303                }
 304            }
 305        }
 306
 307        this
 308    }
 309
 310    pub fn is_empty(&self) -> bool {
 311        self.error_count == 0 && self.warning_count == 0
 312    }
 313
 314    pub fn to_proto(&self, path: &Path) -> proto::DiagnosticSummary {
 315        proto::DiagnosticSummary {
 316            path: path.to_string_lossy().to_string(),
 317            language_server_id: self.language_server_id as u64,
 318            error_count: self.error_count as u32,
 319            warning_count: self.warning_count as u32,
 320        }
 321    }
 322}
 323
 324#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 325pub struct ProjectEntryId(usize);
 326
 327impl ProjectEntryId {
 328    pub const MAX: Self = Self(usize::MAX);
 329
 330    pub fn new(counter: &AtomicUsize) -> Self {
 331        Self(counter.fetch_add(1, SeqCst))
 332    }
 333
 334    pub fn from_proto(id: u64) -> Self {
 335        Self(id as usize)
 336    }
 337
 338    pub fn to_proto(&self) -> u64 {
 339        self.0 as u64
 340    }
 341
 342    pub fn to_usize(&self) -> usize {
 343        self.0
 344    }
 345}
 346
 347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 348pub enum FormatTrigger {
 349    Save,
 350    Manual,
 351}
 352
 353impl FormatTrigger {
 354    fn from_proto(value: i32) -> FormatTrigger {
 355        match value {
 356            0 => FormatTrigger::Save,
 357            1 => FormatTrigger::Manual,
 358            _ => FormatTrigger::Save,
 359        }
 360    }
 361}
 362
 363impl Project {
 364    pub fn init(client: &Arc<Client>) {
 365        client.add_model_message_handler(Self::handle_add_collaborator);
 366        client.add_model_message_handler(Self::handle_update_project_collaborator);
 367        client.add_model_message_handler(Self::handle_remove_collaborator);
 368        client.add_model_message_handler(Self::handle_buffer_reloaded);
 369        client.add_model_message_handler(Self::handle_buffer_saved);
 370        client.add_model_message_handler(Self::handle_start_language_server);
 371        client.add_model_message_handler(Self::handle_update_language_server);
 372        client.add_model_message_handler(Self::handle_update_project);
 373        client.add_model_message_handler(Self::handle_unshare_project);
 374        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 375        client.add_model_message_handler(Self::handle_update_buffer_file);
 376        client.add_model_message_handler(Self::handle_update_buffer);
 377        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 378        client.add_model_message_handler(Self::handle_update_worktree);
 379        client.add_model_request_handler(Self::handle_create_project_entry);
 380        client.add_model_request_handler(Self::handle_rename_project_entry);
 381        client.add_model_request_handler(Self::handle_copy_project_entry);
 382        client.add_model_request_handler(Self::handle_delete_project_entry);
 383        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 384        client.add_model_request_handler(Self::handle_apply_code_action);
 385        client.add_model_request_handler(Self::handle_reload_buffers);
 386        client.add_model_request_handler(Self::handle_synchronize_buffers);
 387        client.add_model_request_handler(Self::handle_format_buffers);
 388        client.add_model_request_handler(Self::handle_get_code_actions);
 389        client.add_model_request_handler(Self::handle_get_completions);
 390        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 391        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 392        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 393        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 394        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 395        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 396        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 397        client.add_model_request_handler(Self::handle_search_project);
 398        client.add_model_request_handler(Self::handle_get_project_symbols);
 399        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 400        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 401        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 402        client.add_model_request_handler(Self::handle_save_buffer);
 403        client.add_model_message_handler(Self::handle_update_diff_base);
 404    }
 405
 406    pub fn local(
 407        client: Arc<Client>,
 408        user_store: ModelHandle<UserStore>,
 409        languages: Arc<LanguageRegistry>,
 410        fs: Arc<dyn Fs>,
 411        cx: &mut MutableAppContext,
 412    ) -> ModelHandle<Self> {
 413        cx.add_model(|cx: &mut ModelContext<Self>| Self {
 414            worktrees: Default::default(),
 415            collaborators: Default::default(),
 416            opened_buffers: Default::default(),
 417            shared_buffers: Default::default(),
 418            incomplete_remote_buffers: Default::default(),
 419            loading_buffers_by_path: Default::default(),
 420            loading_local_worktrees: Default::default(),
 421            buffer_snapshots: Default::default(),
 422            client_state: None,
 423            opened_buffer: watch::channel(),
 424            client_subscriptions: Vec::new(),
 425            _subscriptions: vec![cx.observe_global::<Settings, _>(Self::on_settings_changed)],
 426            _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 427            active_entry: None,
 428            languages,
 429            client,
 430            user_store,
 431            fs,
 432            next_entry_id: Default::default(),
 433            next_diagnostic_group_id: Default::default(),
 434            language_servers: Default::default(),
 435            language_server_ids: Default::default(),
 436            language_server_statuses: Default::default(),
 437            last_workspace_edits_by_language_server: Default::default(),
 438            language_server_settings: Default::default(),
 439            buffers_being_formatted: Default::default(),
 440            next_language_server_id: 0,
 441            nonce: StdRng::from_entropy().gen(),
 442        })
 443    }
 444
 445    pub async fn remote(
 446        remote_id: u64,
 447        client: Arc<Client>,
 448        user_store: ModelHandle<UserStore>,
 449        languages: Arc<LanguageRegistry>,
 450        fs: Arc<dyn Fs>,
 451        mut cx: AsyncAppContext,
 452    ) -> Result<ModelHandle<Self>> {
 453        client.authenticate_and_connect(true, &cx).await?;
 454
 455        let subscription = client.subscribe_to_entity(remote_id);
 456        let response = client
 457            .request(proto::JoinProject {
 458                project_id: remote_id,
 459            })
 460            .await?;
 461        let this = cx.add_model(|cx| {
 462            let replica_id = response.replica_id as ReplicaId;
 463
 464            let mut worktrees = Vec::new();
 465            for worktree in response.worktrees {
 466                let worktree = cx.update(|cx| {
 467                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
 468                });
 469                worktrees.push(worktree);
 470            }
 471
 472            let mut this = Self {
 473                worktrees: Vec::new(),
 474                loading_buffers_by_path: Default::default(),
 475                opened_buffer: watch::channel(),
 476                shared_buffers: Default::default(),
 477                incomplete_remote_buffers: Default::default(),
 478                loading_local_worktrees: Default::default(),
 479                active_entry: None,
 480                collaborators: Default::default(),
 481                _maintain_buffer_languages: Self::maintain_buffer_languages(&languages, cx),
 482                languages,
 483                user_store: user_store.clone(),
 484                fs,
 485                next_entry_id: Default::default(),
 486                next_diagnostic_group_id: Default::default(),
 487                client_subscriptions: Default::default(),
 488                _subscriptions: Default::default(),
 489                client: client.clone(),
 490                client_state: Some(ProjectClientState::Remote {
 491                    sharing_has_stopped: false,
 492                    remote_id,
 493                    replica_id,
 494                }),
 495                language_servers: Default::default(),
 496                language_server_ids: Default::default(),
 497                language_server_settings: Default::default(),
 498                language_server_statuses: response
 499                    .language_servers
 500                    .into_iter()
 501                    .map(|server| {
 502                        (
 503                            server.id as usize,
 504                            LanguageServerStatus {
 505                                name: server.name,
 506                                pending_work: Default::default(),
 507                                has_pending_diagnostic_updates: false,
 508                                progress_tokens: Default::default(),
 509                            },
 510                        )
 511                    })
 512                    .collect(),
 513                last_workspace_edits_by_language_server: Default::default(),
 514                next_language_server_id: 0,
 515                opened_buffers: Default::default(),
 516                buffers_being_formatted: Default::default(),
 517                buffer_snapshots: Default::default(),
 518                nonce: StdRng::from_entropy().gen(),
 519            };
 520            for worktree in worktrees {
 521                let _ = this.add_worktree(&worktree, cx);
 522            }
 523            this
 524        });
 525        let subscription = subscription.set_model(&this, &mut cx);
 526
 527        let user_ids = response
 528            .collaborators
 529            .iter()
 530            .map(|peer| peer.user_id)
 531            .collect();
 532        user_store
 533            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 534            .await?;
 535
 536        this.update(&mut cx, |this, cx| {
 537            this.set_collaborators_from_proto(response.collaborators, cx)?;
 538            this.client_subscriptions.push(subscription);
 539            anyhow::Ok(())
 540        })?;
 541
 542        Ok(this)
 543    }
 544
 545    #[cfg(any(test, feature = "test-support"))]
 546    pub async fn test(
 547        fs: Arc<dyn Fs>,
 548        root_paths: impl IntoIterator<Item = &Path>,
 549        cx: &mut gpui::TestAppContext,
 550    ) -> ModelHandle<Project> {
 551        if !cx.read(|cx| cx.has_global::<Settings>()) {
 552            cx.update(|cx| {
 553                cx.set_global(Settings::test(cx));
 554            });
 555        }
 556
 557        let mut languages = LanguageRegistry::test();
 558        languages.set_executor(cx.background());
 559        let http_client = client::test::FakeHttpClient::with_404_response();
 560        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 561        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 562        let project =
 563            cx.update(|cx| Project::local(client, user_store, Arc::new(languages), fs, cx));
 564        for path in root_paths {
 565            let (tree, _) = project
 566                .update(cx, |project, cx| {
 567                    project.find_or_create_local_worktree(path, true, cx)
 568                })
 569                .await
 570                .unwrap();
 571            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 572                .await;
 573        }
 574        project
 575    }
 576
 577    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 578        let settings = cx.global::<Settings>();
 579
 580        let mut language_servers_to_start = Vec::new();
 581        for buffer in self.opened_buffers.values() {
 582            if let Some(buffer) = buffer.upgrade(cx) {
 583                let buffer = buffer.read(cx);
 584                if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language())
 585                {
 586                    if settings.enable_language_server(Some(&language.name())) {
 587                        let worktree = file.worktree.read(cx);
 588                        language_servers_to_start.push((
 589                            worktree.id(),
 590                            worktree.as_local().unwrap().abs_path().clone(),
 591                            language.clone(),
 592                        ));
 593                    }
 594                }
 595            }
 596        }
 597
 598        let mut language_servers_to_stop = Vec::new();
 599        for language in self.languages.to_vec() {
 600            if let Some(lsp_adapter) = language.lsp_adapter() {
 601                if !settings.enable_language_server(Some(&language.name())) {
 602                    let lsp_name = &lsp_adapter.name;
 603                    for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 604                        if lsp_name == started_lsp_name {
 605                            language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 606                        }
 607                    }
 608                }
 609            }
 610        }
 611
 612        // Stop all newly-disabled language servers.
 613        for (worktree_id, adapter_name) in language_servers_to_stop {
 614            self.stop_language_server(worktree_id, adapter_name, cx)
 615                .detach();
 616        }
 617
 618        // Start all the newly-enabled language servers.
 619        for (worktree_id, worktree_path, language) in language_servers_to_start {
 620            self.start_language_server(worktree_id, worktree_path, language, cx);
 621        }
 622
 623        cx.notify();
 624    }
 625
 626    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 627        self.opened_buffers
 628            .get(&remote_id)
 629            .and_then(|buffer| buffer.upgrade(cx))
 630    }
 631
 632    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 633        &self.languages
 634    }
 635
 636    pub fn client(&self) -> Arc<Client> {
 637        self.client.clone()
 638    }
 639
 640    pub fn user_store(&self) -> ModelHandle<UserStore> {
 641        self.user_store.clone()
 642    }
 643
 644    #[cfg(any(test, feature = "test-support"))]
 645    pub fn check_invariants(&self, cx: &AppContext) {
 646        if self.is_local() {
 647            let mut worktree_root_paths = HashMap::default();
 648            for worktree in self.worktrees(cx) {
 649                let worktree = worktree.read(cx);
 650                let abs_path = worktree.as_local().unwrap().abs_path().clone();
 651                let prev_worktree_id = worktree_root_paths.insert(abs_path.clone(), worktree.id());
 652                assert_eq!(
 653                    prev_worktree_id,
 654                    None,
 655                    "abs path {:?} for worktree {:?} is not unique ({:?} was already registered with the same path)",
 656                    abs_path,
 657                    worktree.id(),
 658                    prev_worktree_id
 659                )
 660            }
 661        } else {
 662            let replica_id = self.replica_id();
 663            for buffer in self.opened_buffers.values() {
 664                if let Some(buffer) = buffer.upgrade(cx) {
 665                    let buffer = buffer.read(cx);
 666                    assert_eq!(
 667                        buffer.deferred_ops_len(),
 668                        0,
 669                        "replica {}, buffer {} has deferred operations",
 670                        replica_id,
 671                        buffer.remote_id()
 672                    );
 673                }
 674            }
 675        }
 676    }
 677
 678    #[cfg(any(test, feature = "test-support"))]
 679    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 680        let path = path.into();
 681        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 682            self.opened_buffers.iter().any(|(_, buffer)| {
 683                if let Some(buffer) = buffer.upgrade(cx) {
 684                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 685                        if file.worktree == worktree && file.path() == &path.path {
 686                            return true;
 687                        }
 688                    }
 689                }
 690                false
 691            })
 692        } else {
 693            false
 694        }
 695    }
 696
 697    pub fn fs(&self) -> &Arc<dyn Fs> {
 698        &self.fs
 699    }
 700
 701    pub fn remote_id(&self) -> Option<u64> {
 702        match self.client_state.as_ref()? {
 703            ProjectClientState::Local { remote_id, .. }
 704            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
 705        }
 706    }
 707
 708    pub fn replica_id(&self) -> ReplicaId {
 709        match &self.client_state {
 710            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
 711            _ => 0,
 712        }
 713    }
 714
 715    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) -> impl Future<Output = ()> {
 716        let (tx, rx) = oneshot::channel();
 717        if let Some(ProjectClientState::Local {
 718            metadata_changed, ..
 719        }) = &mut self.client_state
 720        {
 721            let _ = metadata_changed.unbounded_send(tx);
 722        }
 723        cx.notify();
 724
 725        async move {
 726            // If the project is shared, this will resolve when the `_maintain_metadata` task has
 727            // a chance to update the metadata. Otherwise, it will resolve right away because `tx`
 728            // will get dropped.
 729            let _ = rx.await;
 730        }
 731    }
 732
 733    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
 734        &self.collaborators
 735    }
 736
 737    /// Collect all worktrees, including ones that don't appear in the project panel
 738    pub fn worktrees<'a>(
 739        &'a self,
 740        cx: &'a AppContext,
 741    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 742        self.worktrees
 743            .iter()
 744            .filter_map(move |worktree| worktree.upgrade(cx))
 745    }
 746
 747    /// Collect all user-visible worktrees, the ones that appear in the project panel
 748    pub fn visible_worktrees<'a>(
 749        &'a self,
 750        cx: &'a AppContext,
 751    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
 752        self.worktrees.iter().filter_map(|worktree| {
 753            worktree.upgrade(cx).and_then(|worktree| {
 754                if worktree.read(cx).is_visible() {
 755                    Some(worktree)
 756                } else {
 757                    None
 758                }
 759            })
 760        })
 761    }
 762
 763    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
 764        self.visible_worktrees(cx)
 765            .map(|tree| tree.read(cx).root_name())
 766    }
 767
 768    pub fn worktree_for_id(
 769        &self,
 770        id: WorktreeId,
 771        cx: &AppContext,
 772    ) -> Option<ModelHandle<Worktree>> {
 773        self.worktrees(cx)
 774            .find(|worktree| worktree.read(cx).id() == id)
 775    }
 776
 777    pub fn worktree_for_entry(
 778        &self,
 779        entry_id: ProjectEntryId,
 780        cx: &AppContext,
 781    ) -> Option<ModelHandle<Worktree>> {
 782        self.worktrees(cx)
 783            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 784    }
 785
 786    pub fn worktree_id_for_entry(
 787        &self,
 788        entry_id: ProjectEntryId,
 789        cx: &AppContext,
 790    ) -> Option<WorktreeId> {
 791        self.worktree_for_entry(entry_id, cx)
 792            .map(|worktree| worktree.read(cx).id())
 793    }
 794
 795    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
 796        paths.iter().all(|path| self.contains_path(path, cx))
 797    }
 798
 799    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
 800        for worktree in self.worktrees(cx) {
 801            let worktree = worktree.read(cx).as_local();
 802            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
 803                return true;
 804            }
 805        }
 806        false
 807    }
 808
 809    pub fn create_entry(
 810        &mut self,
 811        project_path: impl Into<ProjectPath>,
 812        is_directory: bool,
 813        cx: &mut ModelContext<Self>,
 814    ) -> Option<Task<Result<Entry>>> {
 815        let project_path = project_path.into();
 816        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 817        if self.is_local() {
 818            Some(worktree.update(cx, |worktree, cx| {
 819                worktree
 820                    .as_local_mut()
 821                    .unwrap()
 822                    .create_entry(project_path.path, is_directory, cx)
 823            }))
 824        } else {
 825            let client = self.client.clone();
 826            let project_id = self.remote_id().unwrap();
 827            Some(cx.spawn_weak(|_, mut cx| async move {
 828                let response = client
 829                    .request(proto::CreateProjectEntry {
 830                        worktree_id: project_path.worktree_id.to_proto(),
 831                        project_id,
 832                        path: project_path.path.to_string_lossy().into(),
 833                        is_directory,
 834                    })
 835                    .await?;
 836                let entry = response
 837                    .entry
 838                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 839                worktree
 840                    .update(&mut cx, |worktree, cx| {
 841                        worktree.as_remote_mut().unwrap().insert_entry(
 842                            entry,
 843                            response.worktree_scan_id as usize,
 844                            cx,
 845                        )
 846                    })
 847                    .await
 848            }))
 849        }
 850    }
 851
 852    pub fn copy_entry(
 853        &mut self,
 854        entry_id: ProjectEntryId,
 855        new_path: impl Into<Arc<Path>>,
 856        cx: &mut ModelContext<Self>,
 857    ) -> Option<Task<Result<Entry>>> {
 858        let worktree = self.worktree_for_entry(entry_id, cx)?;
 859        let new_path = new_path.into();
 860        if self.is_local() {
 861            worktree.update(cx, |worktree, cx| {
 862                worktree
 863                    .as_local_mut()
 864                    .unwrap()
 865                    .copy_entry(entry_id, new_path, cx)
 866            })
 867        } else {
 868            let client = self.client.clone();
 869            let project_id = self.remote_id().unwrap();
 870
 871            Some(cx.spawn_weak(|_, mut cx| async move {
 872                let response = client
 873                    .request(proto::CopyProjectEntry {
 874                        project_id,
 875                        entry_id: entry_id.to_proto(),
 876                        new_path: new_path.to_string_lossy().into(),
 877                    })
 878                    .await?;
 879                let entry = response
 880                    .entry
 881                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 882                worktree
 883                    .update(&mut cx, |worktree, cx| {
 884                        worktree.as_remote_mut().unwrap().insert_entry(
 885                            entry,
 886                            response.worktree_scan_id as usize,
 887                            cx,
 888                        )
 889                    })
 890                    .await
 891            }))
 892        }
 893    }
 894
 895    pub fn rename_entry(
 896        &mut self,
 897        entry_id: ProjectEntryId,
 898        new_path: impl Into<Arc<Path>>,
 899        cx: &mut ModelContext<Self>,
 900    ) -> Option<Task<Result<Entry>>> {
 901        let worktree = self.worktree_for_entry(entry_id, cx)?;
 902        let new_path = new_path.into();
 903        if self.is_local() {
 904            worktree.update(cx, |worktree, cx| {
 905                worktree
 906                    .as_local_mut()
 907                    .unwrap()
 908                    .rename_entry(entry_id, new_path, cx)
 909            })
 910        } else {
 911            let client = self.client.clone();
 912            let project_id = self.remote_id().unwrap();
 913
 914            Some(cx.spawn_weak(|_, mut cx| async move {
 915                let response = client
 916                    .request(proto::RenameProjectEntry {
 917                        project_id,
 918                        entry_id: entry_id.to_proto(),
 919                        new_path: new_path.to_string_lossy().into(),
 920                    })
 921                    .await?;
 922                let entry = response
 923                    .entry
 924                    .ok_or_else(|| anyhow!("missing entry in response"))?;
 925                worktree
 926                    .update(&mut cx, |worktree, cx| {
 927                        worktree.as_remote_mut().unwrap().insert_entry(
 928                            entry,
 929                            response.worktree_scan_id as usize,
 930                            cx,
 931                        )
 932                    })
 933                    .await
 934            }))
 935        }
 936    }
 937
 938    pub fn delete_entry(
 939        &mut self,
 940        entry_id: ProjectEntryId,
 941        cx: &mut ModelContext<Self>,
 942    ) -> Option<Task<Result<()>>> {
 943        let worktree = self.worktree_for_entry(entry_id, cx)?;
 944        if self.is_local() {
 945            worktree.update(cx, |worktree, cx| {
 946                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
 947            })
 948        } else {
 949            let client = self.client.clone();
 950            let project_id = self.remote_id().unwrap();
 951            Some(cx.spawn_weak(|_, mut cx| async move {
 952                let response = client
 953                    .request(proto::DeleteProjectEntry {
 954                        project_id,
 955                        entry_id: entry_id.to_proto(),
 956                    })
 957                    .await?;
 958                worktree
 959                    .update(&mut cx, move |worktree, cx| {
 960                        worktree.as_remote_mut().unwrap().delete_entry(
 961                            entry_id,
 962                            response.worktree_scan_id as usize,
 963                            cx,
 964                        )
 965                    })
 966                    .await
 967            }))
 968        }
 969    }
 970
 971    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
 972        if self.client_state.is_some() {
 973            return Err(anyhow!("project was already shared"));
 974        }
 975
 976        for open_buffer in self.opened_buffers.values_mut() {
 977            match open_buffer {
 978                OpenBuffer::Strong(_) => {}
 979                OpenBuffer::Weak(buffer) => {
 980                    if let Some(buffer) = buffer.upgrade(cx) {
 981                        *open_buffer = OpenBuffer::Strong(buffer);
 982                    }
 983                }
 984                OpenBuffer::Operations(_) => unreachable!(),
 985            }
 986        }
 987
 988        for worktree_handle in self.worktrees.iter_mut() {
 989            match worktree_handle {
 990                WorktreeHandle::Strong(_) => {}
 991                WorktreeHandle::Weak(worktree) => {
 992                    if let Some(worktree) = worktree.upgrade(cx) {
 993                        *worktree_handle = WorktreeHandle::Strong(worktree);
 994                    }
 995                }
 996            }
 997        }
 998
 999        for (server_id, status) in &self.language_server_statuses {
1000            self.client
1001                .send(proto::StartLanguageServer {
1002                    project_id,
1003                    server: Some(proto::LanguageServer {
1004                        id: *server_id as u64,
1005                        name: status.name.clone(),
1006                    }),
1007                })
1008                .log_err();
1009        }
1010
1011        self.client_subscriptions.push(
1012            self.client
1013                .subscribe_to_entity(project_id)
1014                .set_model(&cx.handle(), &mut cx.to_async()),
1015        );
1016
1017        let (metadata_changed_tx, mut metadata_changed_rx) = mpsc::unbounded();
1018        self.client_state = Some(ProjectClientState::Local {
1019            remote_id: project_id,
1020            metadata_changed: metadata_changed_tx,
1021            _maintain_metadata: cx.spawn_weak(move |this, mut cx| async move {
1022                let mut txs = Vec::new();
1023                while let Some(tx) = metadata_changed_rx.next().await {
1024                    txs.push(tx);
1025                    while let Ok(Some(next_tx)) = metadata_changed_rx.try_next() {
1026                        txs.push(next_tx);
1027                    }
1028
1029                    let Some(this) = this.upgrade(&cx) else { break };
1030                    let worktrees =
1031                        this.read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1032                    let update_project = this
1033                        .read_with(&cx, |this, cx| {
1034                            this.client.request(proto::UpdateProject {
1035                                project_id,
1036                                worktrees: this.worktree_metadata_protos(cx),
1037                            })
1038                        })
1039                        .await;
1040                    if update_project.is_ok() {
1041                        for worktree in worktrees {
1042                            worktree.update(&mut cx, |worktree, cx| {
1043                                let worktree = worktree.as_local_mut().unwrap();
1044                                worktree.share(project_id, cx).detach_and_log_err(cx)
1045                            });
1046                        }
1047                    }
1048
1049                    for tx in txs.drain(..) {
1050                        let _ = tx.send(());
1051                    }
1052                }
1053            }),
1054        });
1055
1056        let _ = self.metadata_changed(cx);
1057        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1058        cx.notify();
1059        Ok(())
1060    }
1061
1062    pub fn reshared(
1063        &mut self,
1064        message: proto::ResharedProject,
1065        cx: &mut ModelContext<Self>,
1066    ) -> Result<()> {
1067        self.set_collaborators_from_proto(message.collaborators, cx)?;
1068        let _ = self.metadata_changed(cx);
1069        Ok(())
1070    }
1071
1072    pub fn rejoined(
1073        &mut self,
1074        message: proto::RejoinedProject,
1075        cx: &mut ModelContext<Self>,
1076    ) -> Result<()> {
1077        self.set_worktrees_from_proto(message.worktrees, cx)?;
1078        self.set_collaborators_from_proto(message.collaborators, cx)?;
1079        self.language_server_statuses = message
1080            .language_servers
1081            .into_iter()
1082            .map(|server| {
1083                (
1084                    server.id as usize,
1085                    LanguageServerStatus {
1086                        name: server.name,
1087                        pending_work: Default::default(),
1088                        has_pending_diagnostic_updates: false,
1089                        progress_tokens: Default::default(),
1090                    },
1091                )
1092            })
1093            .collect();
1094        self.synchronize_remote_buffers(cx).detach_and_log_err(cx);
1095
1096        cx.notify();
1097        Ok(())
1098    }
1099
1100    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1101        if self.is_remote() {
1102            return Err(anyhow!("attempted to unshare a remote project"));
1103        }
1104
1105        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1106            self.collaborators.clear();
1107            self.shared_buffers.clear();
1108            self.client_subscriptions.clear();
1109
1110            for worktree_handle in self.worktrees.iter_mut() {
1111                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1112                    let is_visible = worktree.update(cx, |worktree, _| {
1113                        worktree.as_local_mut().unwrap().unshare();
1114                        worktree.is_visible()
1115                    });
1116                    if !is_visible {
1117                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1118                    }
1119                }
1120            }
1121
1122            for open_buffer in self.opened_buffers.values_mut() {
1123                if let OpenBuffer::Strong(buffer) = open_buffer {
1124                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1125                }
1126            }
1127
1128            let _ = self.metadata_changed(cx);
1129            cx.notify();
1130            self.client.send(proto::UnshareProject {
1131                project_id: remote_id,
1132            })?;
1133
1134            Ok(())
1135        } else {
1136            Err(anyhow!("attempted to unshare an unshared project"))
1137        }
1138    }
1139
1140    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1141        if let Some(ProjectClientState::Remote {
1142            sharing_has_stopped,
1143            ..
1144        }) = &mut self.client_state
1145        {
1146            *sharing_has_stopped = true;
1147            self.collaborators.clear();
1148            for worktree in &self.worktrees {
1149                if let Some(worktree) = worktree.upgrade(cx) {
1150                    worktree.update(cx, |worktree, _| {
1151                        if let Some(worktree) = worktree.as_remote_mut() {
1152                            worktree.disconnected_from_host();
1153                        }
1154                    });
1155                }
1156            }
1157            cx.emit(Event::DisconnectedFromHost);
1158            cx.notify();
1159
1160            // Wake up all futures currently waiting on a buffer to get opened,
1161            // to give them a chance to fail now that we've disconnected.
1162            *self.opened_buffer.0.borrow_mut() = ();
1163        }
1164    }
1165
1166    pub fn is_read_only(&self) -> bool {
1167        match &self.client_state {
1168            Some(ProjectClientState::Remote {
1169                sharing_has_stopped,
1170                ..
1171            }) => *sharing_has_stopped,
1172            _ => false,
1173        }
1174    }
1175
1176    pub fn is_local(&self) -> bool {
1177        match &self.client_state {
1178            Some(ProjectClientState::Remote { .. }) => false,
1179            _ => true,
1180        }
1181    }
1182
1183    pub fn is_remote(&self) -> bool {
1184        !self.is_local()
1185    }
1186
1187    pub fn create_terminal(
1188        &mut self,
1189        working_directory: Option<PathBuf>,
1190        window_id: usize,
1191        cx: &mut ModelContext<Self>,
1192    ) -> Result<ModelHandle<Terminal>> {
1193        if self.is_remote() {
1194            return Err(anyhow!(
1195                "creating terminals as a guest is not supported yet"
1196            ));
1197        } else {
1198            let settings = cx.global::<Settings>();
1199            let shell = settings.terminal_shell();
1200            let envs = settings.terminal_env();
1201            let scroll = settings.terminal_scroll();
1202
1203            TerminalBuilder::new(
1204                working_directory.clone(),
1205                shell,
1206                envs,
1207                settings.terminal_overrides.blinking.clone(),
1208                scroll,
1209                window_id,
1210            )
1211            .map(|builder| cx.add_model(|cx| builder.subscribe(cx)))
1212        }
1213    }
1214
1215    pub fn create_buffer(
1216        &mut self,
1217        text: &str,
1218        language: Option<Arc<Language>>,
1219        cx: &mut ModelContext<Self>,
1220    ) -> Result<ModelHandle<Buffer>> {
1221        if self.is_remote() {
1222            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1223        }
1224
1225        let buffer = cx.add_model(|cx| {
1226            Buffer::new(self.replica_id(), text, cx)
1227                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1228        });
1229        self.register_buffer(&buffer, cx)?;
1230        Ok(buffer)
1231    }
1232
1233    pub fn open_path(
1234        &mut self,
1235        path: impl Into<ProjectPath>,
1236        cx: &mut ModelContext<Self>,
1237    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1238        let task = self.open_buffer(path, cx);
1239        cx.spawn_weak(|_, cx| async move {
1240            let buffer = task.await?;
1241            let project_entry_id = buffer
1242                .read_with(&cx, |buffer, cx| {
1243                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1244                })
1245                .ok_or_else(|| anyhow!("no project entry"))?;
1246            Ok((project_entry_id, buffer.into()))
1247        })
1248    }
1249
1250    pub fn open_local_buffer(
1251        &mut self,
1252        abs_path: impl AsRef<Path>,
1253        cx: &mut ModelContext<Self>,
1254    ) -> Task<Result<ModelHandle<Buffer>>> {
1255        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1256            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1257        } else {
1258            Task::ready(Err(anyhow!("no such path")))
1259        }
1260    }
1261
1262    pub fn open_buffer(
1263        &mut self,
1264        path: impl Into<ProjectPath>,
1265        cx: &mut ModelContext<Self>,
1266    ) -> Task<Result<ModelHandle<Buffer>>> {
1267        let project_path = path.into();
1268        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1269            worktree
1270        } else {
1271            return Task::ready(Err(anyhow!("no such worktree")));
1272        };
1273
1274        // If there is already a buffer for the given path, then return it.
1275        let existing_buffer = self.get_open_buffer(&project_path, cx);
1276        if let Some(existing_buffer) = existing_buffer {
1277            return Task::ready(Ok(existing_buffer));
1278        }
1279
1280        let mut loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1281            // If the given path is already being loaded, then wait for that existing
1282            // task to complete and return the same buffer.
1283            hash_map::Entry::Occupied(e) => e.get().clone(),
1284
1285            // Otherwise, record the fact that this path is now being loaded.
1286            hash_map::Entry::Vacant(entry) => {
1287                let (mut tx, rx) = postage::watch::channel();
1288                entry.insert(rx.clone());
1289
1290                let load_buffer = if worktree.read(cx).is_local() {
1291                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1292                } else {
1293                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1294                };
1295
1296                cx.spawn(move |this, mut cx| async move {
1297                    let load_result = load_buffer.await;
1298                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1299                        // Record the fact that the buffer is no longer loading.
1300                        this.loading_buffers_by_path.remove(&project_path);
1301                        let buffer = load_result.map_err(Arc::new)?;
1302                        Ok(buffer)
1303                    }));
1304                })
1305                .detach();
1306                rx
1307            }
1308        };
1309
1310        cx.foreground().spawn(async move {
1311            loop {
1312                if let Some(result) = loading_watch.borrow().as_ref() {
1313                    match result {
1314                        Ok(buffer) => return Ok(buffer.clone()),
1315                        Err(error) => return Err(anyhow!("{}", error)),
1316                    }
1317                }
1318                loading_watch.next().await;
1319            }
1320        })
1321    }
1322
1323    fn open_local_buffer_internal(
1324        &mut self,
1325        path: &Arc<Path>,
1326        worktree: &ModelHandle<Worktree>,
1327        cx: &mut ModelContext<Self>,
1328    ) -> Task<Result<ModelHandle<Buffer>>> {
1329        let load_buffer = worktree.update(cx, |worktree, cx| {
1330            let worktree = worktree.as_local_mut().unwrap();
1331            worktree.load_buffer(path, cx)
1332        });
1333        cx.spawn(|this, mut cx| async move {
1334            let buffer = load_buffer.await?;
1335            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1336            Ok(buffer)
1337        })
1338    }
1339
1340    fn open_remote_buffer_internal(
1341        &mut self,
1342        path: &Arc<Path>,
1343        worktree: &ModelHandle<Worktree>,
1344        cx: &mut ModelContext<Self>,
1345    ) -> Task<Result<ModelHandle<Buffer>>> {
1346        let rpc = self.client.clone();
1347        let project_id = self.remote_id().unwrap();
1348        let remote_worktree_id = worktree.read(cx).id();
1349        let path = path.clone();
1350        let path_string = path.to_string_lossy().to_string();
1351        cx.spawn(|this, mut cx| async move {
1352            let response = rpc
1353                .request(proto::OpenBufferByPath {
1354                    project_id,
1355                    worktree_id: remote_worktree_id.to_proto(),
1356                    path: path_string,
1357                })
1358                .await?;
1359            this.update(&mut cx, |this, cx| {
1360                this.wait_for_remote_buffer(response.buffer_id, cx)
1361            })
1362            .await
1363        })
1364    }
1365
1366    /// LanguageServerName is owned, because it is inserted into a map
1367    fn open_local_buffer_via_lsp(
1368        &mut self,
1369        abs_path: lsp::Url,
1370        language_server_id: usize,
1371        language_server_name: LanguageServerName,
1372        cx: &mut ModelContext<Self>,
1373    ) -> Task<Result<ModelHandle<Buffer>>> {
1374        cx.spawn(|this, mut cx| async move {
1375            let abs_path = abs_path
1376                .to_file_path()
1377                .map_err(|_| anyhow!("can't convert URI to path"))?;
1378            let (worktree, relative_path) = if let Some(result) =
1379                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1380            {
1381                result
1382            } else {
1383                let worktree = this
1384                    .update(&mut cx, |this, cx| {
1385                        this.create_local_worktree(&abs_path, false, cx)
1386                    })
1387                    .await?;
1388                this.update(&mut cx, |this, cx| {
1389                    this.language_server_ids.insert(
1390                        (worktree.read(cx).id(), language_server_name),
1391                        language_server_id,
1392                    );
1393                });
1394                (worktree, PathBuf::new())
1395            };
1396
1397            let project_path = ProjectPath {
1398                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1399                path: relative_path.into(),
1400            };
1401            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1402                .await
1403        })
1404    }
1405
1406    pub fn open_buffer_by_id(
1407        &mut self,
1408        id: u64,
1409        cx: &mut ModelContext<Self>,
1410    ) -> Task<Result<ModelHandle<Buffer>>> {
1411        if let Some(buffer) = self.buffer_for_id(id, cx) {
1412            Task::ready(Ok(buffer))
1413        } else if self.is_local() {
1414            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1415        } else if let Some(project_id) = self.remote_id() {
1416            let request = self
1417                .client
1418                .request(proto::OpenBufferById { project_id, id });
1419            cx.spawn(|this, mut cx| async move {
1420                let buffer_id = request.await?.buffer_id;
1421                this.update(&mut cx, |this, cx| {
1422                    this.wait_for_remote_buffer(buffer_id, cx)
1423                })
1424                .await
1425            })
1426        } else {
1427            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1428        }
1429    }
1430
1431    pub fn save_buffers(
1432        &mut self,
1433        buffers: HashSet<ModelHandle<Buffer>>,
1434        cx: &mut ModelContext<Self>,
1435    ) -> Task<(Option<ProjectTransaction>, Task<Result<()>>)> {
1436        const FORMAT_TIMEOUT: Duration = Duration::from_secs(2);
1437
1438        let mut timeout = cx.background().timer(FORMAT_TIMEOUT).fuse();
1439        let format = self.format(buffers.clone(), true, FormatTrigger::Save, cx);
1440        cx.spawn(|_, cx| async move {
1441            let transaction = futures::select_biased! {
1442                _ = timeout => {
1443                    log::warn!("timed out waiting for formatting");
1444                    None
1445                }
1446                transaction = format.log_err().fuse() => transaction,
1447            };
1448
1449            (
1450                transaction,
1451                cx.spawn(|mut cx| async move {
1452                    let save_tasks = buffers
1453                        .iter()
1454                        .map(|buffer| buffer.update(&mut cx, |buffer, cx| buffer.save(cx)));
1455                    try_join_all(save_tasks).await?;
1456                    Ok(())
1457                }),
1458            )
1459        })
1460    }
1461
1462    pub fn save_buffer_as(
1463        &mut self,
1464        buffer: ModelHandle<Buffer>,
1465        abs_path: PathBuf,
1466        cx: &mut ModelContext<Project>,
1467    ) -> Task<Result<()>> {
1468        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1469        let old_path =
1470            File::from_dyn(buffer.read(cx).file()).and_then(|f| Some(f.as_local()?.abs_path(cx)));
1471        cx.spawn(|this, mut cx| async move {
1472            if let Some(old_path) = old_path {
1473                this.update(&mut cx, |this, cx| {
1474                    this.unregister_buffer_from_language_server(&buffer, old_path, cx);
1475                });
1476            }
1477            let (worktree, path) = worktree_task.await?;
1478            worktree
1479                .update(&mut cx, |worktree, cx| {
1480                    worktree
1481                        .as_local_mut()
1482                        .unwrap()
1483                        .save_buffer_as(buffer.clone(), path, cx)
1484                })
1485                .await?;
1486            this.update(&mut cx, |this, cx| {
1487                this.assign_language_to_buffer(&buffer, cx);
1488                this.register_buffer_with_language_server(&buffer, cx);
1489            });
1490            Ok(())
1491        })
1492    }
1493
1494    pub fn get_open_buffer(
1495        &mut self,
1496        path: &ProjectPath,
1497        cx: &mut ModelContext<Self>,
1498    ) -> Option<ModelHandle<Buffer>> {
1499        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1500        self.opened_buffers.values().find_map(|buffer| {
1501            let buffer = buffer.upgrade(cx)?;
1502            let file = File::from_dyn(buffer.read(cx).file())?;
1503            if file.worktree == worktree && file.path() == &path.path {
1504                Some(buffer)
1505            } else {
1506                None
1507            }
1508        })
1509    }
1510
1511    fn register_buffer(
1512        &mut self,
1513        buffer: &ModelHandle<Buffer>,
1514        cx: &mut ModelContext<Self>,
1515    ) -> Result<()> {
1516        buffer.update(cx, |buffer, _| {
1517            buffer.set_language_registry(self.languages.clone())
1518        });
1519
1520        let remote_id = buffer.read(cx).remote_id();
1521        let open_buffer = if self.is_remote() || self.is_shared() {
1522            OpenBuffer::Strong(buffer.clone())
1523        } else {
1524            OpenBuffer::Weak(buffer.downgrade())
1525        };
1526
1527        match self.opened_buffers.insert(remote_id, open_buffer) {
1528            None => {}
1529            Some(OpenBuffer::Operations(operations)) => {
1530                buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?
1531            }
1532            Some(OpenBuffer::Weak(existing_handle)) => {
1533                if existing_handle.upgrade(cx).is_some() {
1534                    debug_panic!("already registered buffer with remote id {}", remote_id);
1535                    Err(anyhow!(
1536                        "already registered buffer with remote id {}",
1537                        remote_id
1538                    ))?
1539                }
1540            }
1541            Some(OpenBuffer::Strong(_)) => {
1542                debug_panic!("already registered buffer with remote id {}", remote_id);
1543                Err(anyhow!(
1544                    "already registered buffer with remote id {}",
1545                    remote_id
1546                ))?
1547            }
1548        }
1549        cx.subscribe(buffer, |this, buffer, event, cx| {
1550            this.on_buffer_event(buffer, event, cx);
1551        })
1552        .detach();
1553
1554        self.assign_language_to_buffer(buffer, cx);
1555        self.register_buffer_with_language_server(buffer, cx);
1556        cx.observe_release(buffer, |this, buffer, cx| {
1557            if let Some(file) = File::from_dyn(buffer.file()) {
1558                if file.is_local() {
1559                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1560                    if let Some((_, server)) = this.language_server_for_buffer(buffer, cx) {
1561                        server
1562                            .notify::<lsp::notification::DidCloseTextDocument>(
1563                                lsp::DidCloseTextDocumentParams {
1564                                    text_document: lsp::TextDocumentIdentifier::new(uri),
1565                                },
1566                            )
1567                            .log_err();
1568                    }
1569                }
1570            }
1571        })
1572        .detach();
1573
1574        *self.opened_buffer.0.borrow_mut() = ();
1575        Ok(())
1576    }
1577
1578    fn register_buffer_with_language_server(
1579        &mut self,
1580        buffer_handle: &ModelHandle<Buffer>,
1581        cx: &mut ModelContext<Self>,
1582    ) {
1583        let buffer = buffer_handle.read(cx);
1584        let buffer_id = buffer.remote_id();
1585        if let Some(file) = File::from_dyn(buffer.file()) {
1586            if file.is_local() {
1587                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1588                let initial_snapshot = buffer.text_snapshot();
1589
1590                let mut language_server = None;
1591                let mut language_id = None;
1592                if let Some(language) = buffer.language() {
1593                    let worktree_id = file.worktree_id(cx);
1594                    if let Some(adapter) = language.lsp_adapter() {
1595                        language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
1596                        language_server = self
1597                            .language_server_ids
1598                            .get(&(worktree_id, adapter.name.clone()))
1599                            .and_then(|id| self.language_servers.get(id))
1600                            .and_then(|server_state| {
1601                                if let LanguageServerState::Running { server, .. } = server_state {
1602                                    Some(server.clone())
1603                                } else {
1604                                    None
1605                                }
1606                            });
1607                    }
1608                }
1609
1610                if let Some(local_worktree) = file.worktree.read(cx).as_local() {
1611                    if let Some(diagnostics) = local_worktree.diagnostics_for_path(file.path()) {
1612                        self.update_buffer_diagnostics(buffer_handle, diagnostics, None, cx)
1613                            .log_err();
1614                    }
1615                }
1616
1617                if let Some(server) = language_server {
1618                    server
1619                        .notify::<lsp::notification::DidOpenTextDocument>(
1620                            lsp::DidOpenTextDocumentParams {
1621                                text_document: lsp::TextDocumentItem::new(
1622                                    uri,
1623                                    language_id.unwrap_or_default(),
1624                                    0,
1625                                    initial_snapshot.text(),
1626                                ),
1627                            },
1628                        )
1629                        .log_err();
1630                    buffer_handle.update(cx, |buffer, cx| {
1631                        buffer.set_completion_triggers(
1632                            server
1633                                .capabilities()
1634                                .completion_provider
1635                                .as_ref()
1636                                .and_then(|provider| provider.trigger_characters.clone())
1637                                .unwrap_or_default(),
1638                            cx,
1639                        )
1640                    });
1641                    self.buffer_snapshots
1642                        .insert(buffer_id, vec![(0, initial_snapshot)]);
1643                }
1644            }
1645        }
1646    }
1647
1648    fn unregister_buffer_from_language_server(
1649        &mut self,
1650        buffer: &ModelHandle<Buffer>,
1651        old_path: PathBuf,
1652        cx: &mut ModelContext<Self>,
1653    ) {
1654        buffer.update(cx, |buffer, cx| {
1655            buffer.update_diagnostics(Default::default(), cx);
1656            self.buffer_snapshots.remove(&buffer.remote_id());
1657            if let Some((_, language_server)) = self.language_server_for_buffer(buffer, cx) {
1658                language_server
1659                    .notify::<lsp::notification::DidCloseTextDocument>(
1660                        lsp::DidCloseTextDocumentParams {
1661                            text_document: lsp::TextDocumentIdentifier::new(
1662                                lsp::Url::from_file_path(old_path).unwrap(),
1663                            ),
1664                        },
1665                    )
1666                    .log_err();
1667            }
1668        });
1669    }
1670
1671    fn on_buffer_event(
1672        &mut self,
1673        buffer: ModelHandle<Buffer>,
1674        event: &BufferEvent,
1675        cx: &mut ModelContext<Self>,
1676    ) -> Option<()> {
1677        match event {
1678            BufferEvent::Operation(operation) => {
1679                if let Some(project_id) = self.remote_id() {
1680                    let request = self.client.request(proto::UpdateBuffer {
1681                        project_id,
1682                        buffer_id: buffer.read(cx).remote_id(),
1683                        operations: vec![language::proto::serialize_operation(operation)],
1684                    });
1685                    cx.background().spawn(request).detach_and_log_err(cx);
1686                }
1687            }
1688            BufferEvent::Edited { .. } => {
1689                let language_server = self
1690                    .language_server_for_buffer(buffer.read(cx), cx)
1691                    .map(|(_, server)| server.clone())?;
1692                let buffer = buffer.read(cx);
1693                let file = File::from_dyn(buffer.file())?;
1694                let abs_path = file.as_local()?.abs_path(cx);
1695                let uri = lsp::Url::from_file_path(abs_path).unwrap();
1696                let buffer_snapshots = self.buffer_snapshots.get_mut(&buffer.remote_id())?;
1697                let (version, prev_snapshot) = buffer_snapshots.last()?;
1698                let next_snapshot = buffer.text_snapshot();
1699                let next_version = version + 1;
1700
1701                let content_changes = buffer
1702                    .edits_since::<(PointUtf16, usize)>(prev_snapshot.version())
1703                    .map(|edit| {
1704                        let edit_start = edit.new.start.0;
1705                        let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
1706                        let new_text = next_snapshot
1707                            .text_for_range(edit.new.start.1..edit.new.end.1)
1708                            .collect();
1709                        lsp::TextDocumentContentChangeEvent {
1710                            range: Some(lsp::Range::new(
1711                                point_to_lsp(edit_start),
1712                                point_to_lsp(edit_end),
1713                            )),
1714                            range_length: None,
1715                            text: new_text,
1716                        }
1717                    })
1718                    .collect();
1719
1720                buffer_snapshots.push((next_version, next_snapshot));
1721
1722                language_server
1723                    .notify::<lsp::notification::DidChangeTextDocument>(
1724                        lsp::DidChangeTextDocumentParams {
1725                            text_document: lsp::VersionedTextDocumentIdentifier::new(
1726                                uri,
1727                                next_version,
1728                            ),
1729                            content_changes,
1730                        },
1731                    )
1732                    .log_err();
1733            }
1734            BufferEvent::Saved => {
1735                let file = File::from_dyn(buffer.read(cx).file())?;
1736                let worktree_id = file.worktree_id(cx);
1737                let abs_path = file.as_local()?.abs_path(cx);
1738                let text_document = lsp::TextDocumentIdentifier {
1739                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
1740                };
1741
1742                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
1743                    server
1744                        .notify::<lsp::notification::DidSaveTextDocument>(
1745                            lsp::DidSaveTextDocumentParams {
1746                                text_document: text_document.clone(),
1747                                text: None,
1748                            },
1749                        )
1750                        .log_err();
1751                }
1752
1753                let language_server_id = self.language_server_id_for_buffer(buffer.read(cx), cx)?;
1754                if let Some(LanguageServerState::Running {
1755                    adapter,
1756                    simulate_disk_based_diagnostics_completion,
1757                    ..
1758                }) = self.language_servers.get_mut(&language_server_id)
1759                {
1760                    // After saving a buffer using a language server that doesn't provide
1761                    // a disk-based progress token, kick off a timer that will reset every
1762                    // time the buffer is saved. If the timer eventually fires, simulate
1763                    // disk-based diagnostics being finished so that other pieces of UI
1764                    // (e.g., project diagnostics view, diagnostic status bar) can update.
1765                    // We don't emit an event right away because the language server might take
1766                    // some time to publish diagnostics.
1767                    if adapter.disk_based_diagnostics_progress_token.is_none() {
1768                        const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration = Duration::from_secs(1);
1769
1770                        let task = cx.spawn_weak(|this, mut cx| async move {
1771                            cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
1772                            if let Some(this) = this.upgrade(&cx) {
1773                                this.update(&mut cx, |this, cx | {
1774                                    this.disk_based_diagnostics_finished(language_server_id, cx);
1775                                    this.broadcast_language_server_update(
1776                                        language_server_id,
1777                                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
1778                                            proto::LspDiskBasedDiagnosticsUpdated {},
1779                                        ),
1780                                    );
1781                                });
1782                            }
1783                        });
1784                        *simulate_disk_based_diagnostics_completion = Some(task);
1785                    }
1786                }
1787            }
1788            _ => {}
1789        }
1790
1791        None
1792    }
1793
1794    fn language_servers_for_worktree(
1795        &self,
1796        worktree_id: WorktreeId,
1797    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
1798        self.language_server_ids
1799            .iter()
1800            .filter_map(move |((language_server_worktree_id, _), id)| {
1801                if *language_server_worktree_id == worktree_id {
1802                    if let Some(LanguageServerState::Running {
1803                        adapter,
1804                        language,
1805                        server,
1806                        ..
1807                    }) = self.language_servers.get(id)
1808                    {
1809                        return Some((adapter, language, server));
1810                    }
1811                }
1812                None
1813            })
1814    }
1815
1816    fn maintain_buffer_languages(
1817        languages: &LanguageRegistry,
1818        cx: &mut ModelContext<Project>,
1819    ) -> Task<()> {
1820        let mut subscription = languages.subscribe();
1821        cx.spawn_weak(|project, mut cx| async move {
1822            while let Some(()) = subscription.next().await {
1823                if let Some(project) = project.upgrade(&cx) {
1824                    project.update(&mut cx, |project, cx| {
1825                        let mut plain_text_buffers = Vec::new();
1826                        let mut buffers_with_unknown_injections = Vec::new();
1827                        for buffer in project.opened_buffers.values() {
1828                            if let Some(handle) = buffer.upgrade(cx) {
1829                                let buffer = &handle.read(cx);
1830                                if buffer.language().is_none()
1831                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
1832                                {
1833                                    plain_text_buffers.push(handle);
1834                                } else if buffer.contains_unknown_injections() {
1835                                    buffers_with_unknown_injections.push(handle);
1836                                }
1837                            }
1838                        }
1839
1840                        for buffer in plain_text_buffers {
1841                            project.assign_language_to_buffer(&buffer, cx);
1842                            project.register_buffer_with_language_server(&buffer, cx);
1843                        }
1844
1845                        for buffer in buffers_with_unknown_injections {
1846                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
1847                        }
1848                    });
1849                }
1850            }
1851        })
1852    }
1853
1854    fn assign_language_to_buffer(
1855        &mut self,
1856        buffer: &ModelHandle<Buffer>,
1857        cx: &mut ModelContext<Self>,
1858    ) -> Option<()> {
1859        // If the buffer has a language, set it and start the language server if we haven't already.
1860        let full_path = buffer.read(cx).file()?.full_path(cx);
1861        let new_language = self.languages.language_for_path(&full_path)?;
1862        buffer.update(cx, |buffer, cx| {
1863            if buffer.language().map_or(true, |old_language| {
1864                !Arc::ptr_eq(old_language, &new_language)
1865            }) {
1866                buffer.set_language(Some(new_language.clone()), cx);
1867            }
1868        });
1869
1870        let file = File::from_dyn(buffer.read(cx).file())?;
1871        let worktree = file.worktree.read(cx).as_local()?;
1872        let worktree_id = worktree.id();
1873        let worktree_abs_path = worktree.abs_path().clone();
1874        self.start_language_server(worktree_id, worktree_abs_path, new_language, cx);
1875
1876        None
1877    }
1878
1879    fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) {
1880        use serde_json::Value;
1881
1882        match (source, target) {
1883            (Value::Object(source), Value::Object(target)) => {
1884                for (key, value) in source {
1885                    if let Some(target) = target.get_mut(&key) {
1886                        Self::merge_json_value_into(value, target);
1887                    } else {
1888                        target.insert(key.clone(), value);
1889                    }
1890                }
1891            }
1892
1893            (source, target) => *target = source,
1894        }
1895    }
1896
1897    fn start_language_server(
1898        &mut self,
1899        worktree_id: WorktreeId,
1900        worktree_path: Arc<Path>,
1901        language: Arc<Language>,
1902        cx: &mut ModelContext<Self>,
1903    ) {
1904        if !cx
1905            .global::<Settings>()
1906            .enable_language_server(Some(&language.name()))
1907        {
1908            return;
1909        }
1910
1911        let adapter = if let Some(adapter) = language.lsp_adapter() {
1912            adapter
1913        } else {
1914            return;
1915        };
1916        let key = (worktree_id, adapter.name.clone());
1917
1918        let mut initialization_options = adapter.initialization_options.clone();
1919
1920        let lsp = &cx.global::<Settings>().lsp.get(&adapter.name.0);
1921        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
1922        match (&mut initialization_options, override_options) {
1923            (Some(initialization_options), Some(override_options)) => {
1924                Self::merge_json_value_into(override_options, initialization_options);
1925            }
1926
1927            (None, override_options) => initialization_options = override_options,
1928
1929            _ => {}
1930        }
1931
1932        self.language_server_ids
1933            .entry(key.clone())
1934            .or_insert_with(|| {
1935                let server_id = post_inc(&mut self.next_language_server_id);
1936                let language_server = self.languages.start_language_server(
1937                    server_id,
1938                    language.clone(),
1939                    worktree_path,
1940                    self.client.http_client(),
1941                    cx,
1942                );
1943                self.language_servers.insert(
1944                    server_id,
1945                    LanguageServerState::Starting(cx.spawn_weak(|this, mut cx| async move {
1946                        let language_server = language_server?.await.log_err()?;
1947                        let language_server = language_server
1948                            .initialize(initialization_options)
1949                            .await
1950                            .log_err()?;
1951                        let this = this.upgrade(&cx)?;
1952
1953                        language_server
1954                            .on_notification::<lsp::notification::PublishDiagnostics, _>({
1955                                let this = this.downgrade();
1956                                let adapter = adapter.clone();
1957                                move |mut params, cx| {
1958                                    let this = this;
1959                                    let adapter = adapter.clone();
1960                                    cx.spawn(|mut cx| async move {
1961                                        adapter.process_diagnostics(&mut params).await;
1962                                        if let Some(this) = this.upgrade(&cx) {
1963                                            this.update(&mut cx, |this, cx| {
1964                                                this.update_diagnostics(
1965                                                    server_id,
1966                                                    params,
1967                                                    &adapter.disk_based_diagnostic_sources,
1968                                                    cx,
1969                                                )
1970                                                .log_err();
1971                                            });
1972                                        }
1973                                    })
1974                                    .detach();
1975                                }
1976                            })
1977                            .detach();
1978
1979                        language_server
1980                            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
1981                                let settings = this.read_with(&cx, |this, _| {
1982                                    this.language_server_settings.clone()
1983                                });
1984                                move |params, _| {
1985                                    let settings = settings.lock().clone();
1986                                    async move {
1987                                        Ok(params
1988                                            .items
1989                                            .into_iter()
1990                                            .map(|item| {
1991                                                if let Some(section) = &item.section {
1992                                                    settings
1993                                                        .get(section)
1994                                                        .cloned()
1995                                                        .unwrap_or(serde_json::Value::Null)
1996                                                } else {
1997                                                    settings.clone()
1998                                                }
1999                                            })
2000                                            .collect())
2001                                    }
2002                                }
2003                            })
2004                            .detach();
2005
2006                        // Even though we don't have handling for these requests, respond to them to
2007                        // avoid stalling any language server like `gopls` which waits for a response
2008                        // to these requests when initializing.
2009                        language_server
2010                            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>({
2011                                let this = this.downgrade();
2012                                move |params, mut cx| async move {
2013                                    if let Some(this) = this.upgrade(&cx) {
2014                                        this.update(&mut cx, |this, _| {
2015                                            if let Some(status) =
2016                                                this.language_server_statuses.get_mut(&server_id)
2017                                            {
2018                                                if let lsp::NumberOrString::String(token) =
2019                                                    params.token
2020                                                {
2021                                                    status.progress_tokens.insert(token);
2022                                                }
2023                                            }
2024                                        });
2025                                    }
2026                                    Ok(())
2027                                }
2028                            })
2029                            .detach();
2030                        language_server
2031                            .on_request::<lsp::request::RegisterCapability, _, _>(|_, _| async {
2032                                Ok(())
2033                            })
2034                            .detach();
2035
2036                        language_server
2037                            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
2038                                let this = this.downgrade();
2039                                let adapter = adapter.clone();
2040                                let language_server = language_server.clone();
2041                                move |params, cx| {
2042                                    Self::on_lsp_workspace_edit(
2043                                        this,
2044                                        params,
2045                                        server_id,
2046                                        adapter.clone(),
2047                                        language_server.clone(),
2048                                        cx,
2049                                    )
2050                                }
2051                            })
2052                            .detach();
2053
2054                        let disk_based_diagnostics_progress_token =
2055                            adapter.disk_based_diagnostics_progress_token.clone();
2056
2057                        language_server
2058                            .on_notification::<lsp::notification::Progress, _>({
2059                                let this = this.downgrade();
2060                                move |params, mut cx| {
2061                                    if let Some(this) = this.upgrade(&cx) {
2062                                        this.update(&mut cx, |this, cx| {
2063                                            this.on_lsp_progress(
2064                                                params,
2065                                                server_id,
2066                                                disk_based_diagnostics_progress_token.clone(),
2067                                                cx,
2068                                            );
2069                                        });
2070                                    }
2071                                }
2072                            })
2073                            .detach();
2074
2075                        this.update(&mut cx, |this, cx| {
2076                            // If the language server for this key doesn't match the server id, don't store the
2077                            // server. Which will cause it to be dropped, killing the process
2078                            if this
2079                                .language_server_ids
2080                                .get(&key)
2081                                .map(|id| id != &server_id)
2082                                .unwrap_or(false)
2083                            {
2084                                return None;
2085                            }
2086
2087                            // Update language_servers collection with Running variant of LanguageServerState
2088                            // indicating that the server is up and running and ready
2089                            this.language_servers.insert(
2090                                server_id,
2091                                LanguageServerState::Running {
2092                                    adapter: adapter.clone(),
2093                                    language,
2094                                    server: language_server.clone(),
2095                                    simulate_disk_based_diagnostics_completion: None,
2096                                },
2097                            );
2098                            this.language_server_statuses.insert(
2099                                server_id,
2100                                LanguageServerStatus {
2101                                    name: language_server.name().to_string(),
2102                                    pending_work: Default::default(),
2103                                    has_pending_diagnostic_updates: false,
2104                                    progress_tokens: Default::default(),
2105                                },
2106                            );
2107                            language_server
2108                                .notify::<lsp::notification::DidChangeConfiguration>(
2109                                    lsp::DidChangeConfigurationParams {
2110                                        settings: this.language_server_settings.lock().clone(),
2111                                    },
2112                                )
2113                                .ok();
2114
2115                            if let Some(project_id) = this.remote_id() {
2116                                this.client
2117                                    .send(proto::StartLanguageServer {
2118                                        project_id,
2119                                        server: Some(proto::LanguageServer {
2120                                            id: server_id as u64,
2121                                            name: language_server.name().to_string(),
2122                                        }),
2123                                    })
2124                                    .log_err();
2125                            }
2126
2127                            // Tell the language server about every open buffer in the worktree that matches the language.
2128                            for buffer in this.opened_buffers.values() {
2129                                if let Some(buffer_handle) = buffer.upgrade(cx) {
2130                                    let buffer = buffer_handle.read(cx);
2131                                    let file = if let Some(file) = File::from_dyn(buffer.file()) {
2132                                        file
2133                                    } else {
2134                                        continue;
2135                                    };
2136                                    let language = if let Some(language) = buffer.language() {
2137                                        language
2138                                    } else {
2139                                        continue;
2140                                    };
2141                                    if file.worktree.read(cx).id() != key.0
2142                                        || language.lsp_adapter().map(|a| a.name.clone())
2143                                            != Some(key.1.clone())
2144                                    {
2145                                        continue;
2146                                    }
2147
2148                                    let file = file.as_local()?;
2149                                    let versions = this
2150                                        .buffer_snapshots
2151                                        .entry(buffer.remote_id())
2152                                        .or_insert_with(|| vec![(0, buffer.text_snapshot())]);
2153
2154                                    let (version, initial_snapshot) = versions.last().unwrap();
2155                                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
2156                                    language_server
2157                                        .notify::<lsp::notification::DidOpenTextDocument>(
2158                                            lsp::DidOpenTextDocumentParams {
2159                                                text_document: lsp::TextDocumentItem::new(
2160                                                    uri,
2161                                                    adapter
2162                                                        .language_ids
2163                                                        .get(language.name().as_ref())
2164                                                        .cloned()
2165                                                        .unwrap_or_default(),
2166                                                    *version,
2167                                                    initial_snapshot.text(),
2168                                                ),
2169                                            },
2170                                        )
2171                                        .log_err()?;
2172                                    buffer_handle.update(cx, |buffer, cx| {
2173                                        buffer.set_completion_triggers(
2174                                            language_server
2175                                                .capabilities()
2176                                                .completion_provider
2177                                                .as_ref()
2178                                                .and_then(|provider| {
2179                                                    provider.trigger_characters.clone()
2180                                                })
2181                                                .unwrap_or_default(),
2182                                            cx,
2183                                        )
2184                                    });
2185                                }
2186                            }
2187
2188                            cx.notify();
2189                            Some(language_server)
2190                        })
2191                    })),
2192                );
2193
2194                server_id
2195            });
2196    }
2197
2198    // Returns a list of all of the worktrees which no longer have a language server and the root path
2199    // for the stopped server
2200    fn stop_language_server(
2201        &mut self,
2202        worktree_id: WorktreeId,
2203        adapter_name: LanguageServerName,
2204        cx: &mut ModelContext<Self>,
2205    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
2206        let key = (worktree_id, adapter_name);
2207        if let Some(server_id) = self.language_server_ids.remove(&key) {
2208            // Remove other entries for this language server as well
2209            let mut orphaned_worktrees = vec![worktree_id];
2210            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
2211            for other_key in other_keys {
2212                if self.language_server_ids.get(&other_key) == Some(&server_id) {
2213                    self.language_server_ids.remove(&other_key);
2214                    orphaned_worktrees.push(other_key.0);
2215                }
2216            }
2217
2218            self.language_server_statuses.remove(&server_id);
2219            cx.notify();
2220
2221            let server_state = self.language_servers.remove(&server_id);
2222            cx.spawn_weak(|this, mut cx| async move {
2223                let mut root_path = None;
2224
2225                let server = match server_state {
2226                    Some(LanguageServerState::Starting(started_language_server)) => {
2227                        started_language_server.await
2228                    }
2229                    Some(LanguageServerState::Running { server, .. }) => Some(server),
2230                    None => None,
2231                };
2232
2233                if let Some(server) = server {
2234                    root_path = Some(server.root_path().clone());
2235                    if let Some(shutdown) = server.shutdown() {
2236                        shutdown.await;
2237                    }
2238                }
2239
2240                if let Some(this) = this.upgrade(&cx) {
2241                    this.update(&mut cx, |this, cx| {
2242                        this.language_server_statuses.remove(&server_id);
2243                        cx.notify();
2244                    });
2245                }
2246
2247                (root_path, orphaned_worktrees)
2248            })
2249        } else {
2250            Task::ready((None, Vec::new()))
2251        }
2252    }
2253
2254    pub fn restart_language_servers_for_buffers(
2255        &mut self,
2256        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
2257        cx: &mut ModelContext<Self>,
2258    ) -> Option<()> {
2259        let language_server_lookup_info: HashSet<(WorktreeId, Arc<Path>, PathBuf)> = buffers
2260            .into_iter()
2261            .filter_map(|buffer| {
2262                let file = File::from_dyn(buffer.read(cx).file())?;
2263                let worktree = file.worktree.read(cx).as_local()?;
2264                let worktree_id = worktree.id();
2265                let worktree_abs_path = worktree.abs_path().clone();
2266                let full_path = file.full_path(cx);
2267                Some((worktree_id, worktree_abs_path, full_path))
2268            })
2269            .collect();
2270        for (worktree_id, worktree_abs_path, full_path) in language_server_lookup_info {
2271            let language = self.languages.language_for_path(&full_path)?;
2272            self.restart_language_server(worktree_id, worktree_abs_path, language, cx);
2273        }
2274
2275        None
2276    }
2277
2278    fn restart_language_server(
2279        &mut self,
2280        worktree_id: WorktreeId,
2281        fallback_path: Arc<Path>,
2282        language: Arc<Language>,
2283        cx: &mut ModelContext<Self>,
2284    ) {
2285        let adapter = if let Some(adapter) = language.lsp_adapter() {
2286            adapter
2287        } else {
2288            return;
2289        };
2290
2291        let server_name = adapter.name.clone();
2292        let stop = self.stop_language_server(worktree_id, server_name.clone(), cx);
2293        cx.spawn_weak(|this, mut cx| async move {
2294            let (original_root_path, orphaned_worktrees) = stop.await;
2295            if let Some(this) = this.upgrade(&cx) {
2296                this.update(&mut cx, |this, cx| {
2297                    // Attempt to restart using original server path. Fallback to passed in
2298                    // path if we could not retrieve the root path
2299                    let root_path = original_root_path
2300                        .map(|path_buf| Arc::from(path_buf.as_path()))
2301                        .unwrap_or(fallback_path);
2302
2303                    this.start_language_server(worktree_id, root_path, language, cx);
2304
2305                    // Lookup new server id and set it for each of the orphaned worktrees
2306                    if let Some(new_server_id) = this
2307                        .language_server_ids
2308                        .get(&(worktree_id, server_name.clone()))
2309                        .cloned()
2310                    {
2311                        for orphaned_worktree in orphaned_worktrees {
2312                            this.language_server_ids
2313                                .insert((orphaned_worktree, server_name.clone()), new_server_id);
2314                        }
2315                    }
2316                });
2317            }
2318        })
2319        .detach();
2320    }
2321
2322    fn on_lsp_progress(
2323        &mut self,
2324        progress: lsp::ProgressParams,
2325        server_id: usize,
2326        disk_based_diagnostics_progress_token: Option<String>,
2327        cx: &mut ModelContext<Self>,
2328    ) {
2329        let token = match progress.token {
2330            lsp::NumberOrString::String(token) => token,
2331            lsp::NumberOrString::Number(token) => {
2332                log::info!("skipping numeric progress token {}", token);
2333                return;
2334            }
2335        };
2336        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
2337        let language_server_status =
2338            if let Some(status) = self.language_server_statuses.get_mut(&server_id) {
2339                status
2340            } else {
2341                return;
2342            };
2343
2344        if !language_server_status.progress_tokens.contains(&token) {
2345            return;
2346        }
2347
2348        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
2349            .as_ref()
2350            .map_or(false, |disk_based_token| {
2351                token.starts_with(disk_based_token)
2352            });
2353
2354        match progress {
2355            lsp::WorkDoneProgress::Begin(report) => {
2356                if is_disk_based_diagnostics_progress {
2357                    language_server_status.has_pending_diagnostic_updates = true;
2358                    self.disk_based_diagnostics_started(server_id, cx);
2359                    self.broadcast_language_server_update(
2360                        server_id,
2361                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(
2362                            proto::LspDiskBasedDiagnosticsUpdating {},
2363                        ),
2364                    );
2365                } else {
2366                    self.on_lsp_work_start(
2367                        server_id,
2368                        token.clone(),
2369                        LanguageServerProgress {
2370                            message: report.message.clone(),
2371                            percentage: report.percentage.map(|p| p as usize),
2372                            last_update_at: Instant::now(),
2373                        },
2374                        cx,
2375                    );
2376                    self.broadcast_language_server_update(
2377                        server_id,
2378                        proto::update_language_server::Variant::WorkStart(proto::LspWorkStart {
2379                            token,
2380                            message: report.message,
2381                            percentage: report.percentage.map(|p| p as u32),
2382                        }),
2383                    );
2384                }
2385            }
2386            lsp::WorkDoneProgress::Report(report) => {
2387                if !is_disk_based_diagnostics_progress {
2388                    self.on_lsp_work_progress(
2389                        server_id,
2390                        token.clone(),
2391                        LanguageServerProgress {
2392                            message: report.message.clone(),
2393                            percentage: report.percentage.map(|p| p as usize),
2394                            last_update_at: Instant::now(),
2395                        },
2396                        cx,
2397                    );
2398                    self.broadcast_language_server_update(
2399                        server_id,
2400                        proto::update_language_server::Variant::WorkProgress(
2401                            proto::LspWorkProgress {
2402                                token,
2403                                message: report.message,
2404                                percentage: report.percentage.map(|p| p as u32),
2405                            },
2406                        ),
2407                    );
2408                }
2409            }
2410            lsp::WorkDoneProgress::End(_) => {
2411                language_server_status.progress_tokens.remove(&token);
2412
2413                if is_disk_based_diagnostics_progress {
2414                    language_server_status.has_pending_diagnostic_updates = false;
2415                    self.disk_based_diagnostics_finished(server_id, cx);
2416                    self.broadcast_language_server_update(
2417                        server_id,
2418                        proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
2419                            proto::LspDiskBasedDiagnosticsUpdated {},
2420                        ),
2421                    );
2422                } else {
2423                    self.on_lsp_work_end(server_id, token.clone(), cx);
2424                    self.broadcast_language_server_update(
2425                        server_id,
2426                        proto::update_language_server::Variant::WorkEnd(proto::LspWorkEnd {
2427                            token,
2428                        }),
2429                    );
2430                }
2431            }
2432        }
2433    }
2434
2435    fn on_lsp_work_start(
2436        &mut self,
2437        language_server_id: usize,
2438        token: String,
2439        progress: LanguageServerProgress,
2440        cx: &mut ModelContext<Self>,
2441    ) {
2442        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2443            status.pending_work.insert(token, progress);
2444            cx.notify();
2445        }
2446    }
2447
2448    fn on_lsp_work_progress(
2449        &mut self,
2450        language_server_id: usize,
2451        token: String,
2452        progress: LanguageServerProgress,
2453        cx: &mut ModelContext<Self>,
2454    ) {
2455        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2456            let entry = status
2457                .pending_work
2458                .entry(token)
2459                .or_insert(LanguageServerProgress {
2460                    message: Default::default(),
2461                    percentage: Default::default(),
2462                    last_update_at: progress.last_update_at,
2463                });
2464            if progress.message.is_some() {
2465                entry.message = progress.message;
2466            }
2467            if progress.percentage.is_some() {
2468                entry.percentage = progress.percentage;
2469            }
2470            entry.last_update_at = progress.last_update_at;
2471            cx.notify();
2472        }
2473    }
2474
2475    fn on_lsp_work_end(
2476        &mut self,
2477        language_server_id: usize,
2478        token: String,
2479        cx: &mut ModelContext<Self>,
2480    ) {
2481        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
2482            status.pending_work.remove(&token);
2483            cx.notify();
2484        }
2485    }
2486
2487    async fn on_lsp_workspace_edit(
2488        this: WeakModelHandle<Self>,
2489        params: lsp::ApplyWorkspaceEditParams,
2490        server_id: usize,
2491        adapter: Arc<CachedLspAdapter>,
2492        language_server: Arc<LanguageServer>,
2493        mut cx: AsyncAppContext,
2494    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
2495        let this = this
2496            .upgrade(&cx)
2497            .ok_or_else(|| anyhow!("project project closed"))?;
2498        let transaction = Self::deserialize_workspace_edit(
2499            this.clone(),
2500            params.edit,
2501            true,
2502            adapter.clone(),
2503            language_server.clone(),
2504            &mut cx,
2505        )
2506        .await
2507        .log_err();
2508        this.update(&mut cx, |this, _| {
2509            if let Some(transaction) = transaction {
2510                this.last_workspace_edits_by_language_server
2511                    .insert(server_id, transaction);
2512            }
2513        });
2514        Ok(lsp::ApplyWorkspaceEditResponse {
2515            applied: true,
2516            failed_change: None,
2517            failure_reason: None,
2518        })
2519    }
2520
2521    fn broadcast_language_server_update(
2522        &self,
2523        language_server_id: usize,
2524        event: proto::update_language_server::Variant,
2525    ) {
2526        if let Some(project_id) = self.remote_id() {
2527            self.client
2528                .send(proto::UpdateLanguageServer {
2529                    project_id,
2530                    language_server_id: language_server_id as u64,
2531                    variant: Some(event),
2532                })
2533                .log_err();
2534        }
2535    }
2536
2537    pub fn set_language_server_settings(&mut self, settings: serde_json::Value) {
2538        for server_state in self.language_servers.values() {
2539            if let LanguageServerState::Running { server, .. } = server_state {
2540                server
2541                    .notify::<lsp::notification::DidChangeConfiguration>(
2542                        lsp::DidChangeConfigurationParams {
2543                            settings: settings.clone(),
2544                        },
2545                    )
2546                    .ok();
2547            }
2548        }
2549        *self.language_server_settings.lock() = settings;
2550    }
2551
2552    pub fn language_server_statuses(
2553        &self,
2554    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
2555        self.language_server_statuses.values()
2556    }
2557
2558    pub fn update_diagnostics(
2559        &mut self,
2560        language_server_id: usize,
2561        params: lsp::PublishDiagnosticsParams,
2562        disk_based_sources: &[String],
2563        cx: &mut ModelContext<Self>,
2564    ) -> Result<()> {
2565        let abs_path = params
2566            .uri
2567            .to_file_path()
2568            .map_err(|_| anyhow!("URI is not a file"))?;
2569        let mut diagnostics = Vec::default();
2570        let mut primary_diagnostic_group_ids = HashMap::default();
2571        let mut sources_by_group_id = HashMap::default();
2572        let mut supporting_diagnostics = HashMap::default();
2573        for diagnostic in &params.diagnostics {
2574            let source = diagnostic.source.as_ref();
2575            let code = diagnostic.code.as_ref().map(|code| match code {
2576                lsp::NumberOrString::Number(code) => code.to_string(),
2577                lsp::NumberOrString::String(code) => code.clone(),
2578            });
2579            let range = range_from_lsp(diagnostic.range);
2580            let is_supporting = diagnostic
2581                .related_information
2582                .as_ref()
2583                .map_or(false, |infos| {
2584                    infos.iter().any(|info| {
2585                        primary_diagnostic_group_ids.contains_key(&(
2586                            source,
2587                            code.clone(),
2588                            range_from_lsp(info.location.range),
2589                        ))
2590                    })
2591                });
2592
2593            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
2594                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
2595            });
2596
2597            if is_supporting {
2598                supporting_diagnostics.insert(
2599                    (source, code.clone(), range),
2600                    (diagnostic.severity, is_unnecessary),
2601                );
2602            } else {
2603                let group_id = post_inc(&mut self.next_diagnostic_group_id);
2604                let is_disk_based =
2605                    source.map_or(false, |source| disk_based_sources.contains(source));
2606
2607                sources_by_group_id.insert(group_id, source);
2608                primary_diagnostic_group_ids
2609                    .insert((source, code.clone(), range.clone()), group_id);
2610
2611                diagnostics.push(DiagnosticEntry {
2612                    range,
2613                    diagnostic: Diagnostic {
2614                        code: code.clone(),
2615                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
2616                        message: diagnostic.message.clone(),
2617                        group_id,
2618                        is_primary: true,
2619                        is_valid: true,
2620                        is_disk_based,
2621                        is_unnecessary,
2622                    },
2623                });
2624                if let Some(infos) = &diagnostic.related_information {
2625                    for info in infos {
2626                        if info.location.uri == params.uri && !info.message.is_empty() {
2627                            let range = range_from_lsp(info.location.range);
2628                            diagnostics.push(DiagnosticEntry {
2629                                range,
2630                                diagnostic: Diagnostic {
2631                                    code: code.clone(),
2632                                    severity: DiagnosticSeverity::INFORMATION,
2633                                    message: info.message.clone(),
2634                                    group_id,
2635                                    is_primary: false,
2636                                    is_valid: true,
2637                                    is_disk_based,
2638                                    is_unnecessary: false,
2639                                },
2640                            });
2641                        }
2642                    }
2643                }
2644            }
2645        }
2646
2647        for entry in &mut diagnostics {
2648            let diagnostic = &mut entry.diagnostic;
2649            if !diagnostic.is_primary {
2650                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
2651                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
2652                    source,
2653                    diagnostic.code.clone(),
2654                    entry.range.clone(),
2655                )) {
2656                    if let Some(severity) = severity {
2657                        diagnostic.severity = severity;
2658                    }
2659                    diagnostic.is_unnecessary = is_unnecessary;
2660                }
2661            }
2662        }
2663
2664        self.update_diagnostic_entries(
2665            language_server_id,
2666            abs_path,
2667            params.version,
2668            diagnostics,
2669            cx,
2670        )?;
2671        Ok(())
2672    }
2673
2674    pub fn update_diagnostic_entries(
2675        &mut self,
2676        language_server_id: usize,
2677        abs_path: PathBuf,
2678        version: Option<i32>,
2679        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2680        cx: &mut ModelContext<Project>,
2681    ) -> Result<(), anyhow::Error> {
2682        let (worktree, relative_path) = self
2683            .find_local_worktree(&abs_path, cx)
2684            .ok_or_else(|| anyhow!("no worktree found for diagnostics"))?;
2685
2686        let project_path = ProjectPath {
2687            worktree_id: worktree.read(cx).id(),
2688            path: relative_path.into(),
2689        };
2690
2691        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
2692            self.update_buffer_diagnostics(&buffer, diagnostics.clone(), version, cx)?;
2693        }
2694
2695        let updated = worktree.update(cx, |worktree, cx| {
2696            worktree
2697                .as_local_mut()
2698                .ok_or_else(|| anyhow!("not a local worktree"))?
2699                .update_diagnostics(
2700                    language_server_id,
2701                    project_path.path.clone(),
2702                    diagnostics,
2703                    cx,
2704                )
2705        })?;
2706        if updated {
2707            cx.emit(Event::DiagnosticsUpdated {
2708                language_server_id,
2709                path: project_path,
2710            });
2711        }
2712        Ok(())
2713    }
2714
2715    fn update_buffer_diagnostics(
2716        &mut self,
2717        buffer: &ModelHandle<Buffer>,
2718        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
2719        version: Option<i32>,
2720        cx: &mut ModelContext<Self>,
2721    ) -> Result<()> {
2722        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
2723            Ordering::Equal
2724                .then_with(|| b.is_primary.cmp(&a.is_primary))
2725                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
2726                .then_with(|| a.severity.cmp(&b.severity))
2727                .then_with(|| a.message.cmp(&b.message))
2728        }
2729
2730        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, version, cx)?;
2731
2732        diagnostics.sort_unstable_by(|a, b| {
2733            Ordering::Equal
2734                .then_with(|| a.range.start.cmp(&b.range.start))
2735                .then_with(|| b.range.end.cmp(&a.range.end))
2736                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
2737        });
2738
2739        let mut sanitized_diagnostics = Vec::new();
2740        let edits_since_save = Patch::new(
2741            snapshot
2742                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
2743                .collect(),
2744        );
2745        for entry in diagnostics {
2746            let start;
2747            let end;
2748            if entry.diagnostic.is_disk_based {
2749                // Some diagnostics are based on files on disk instead of buffers'
2750                // current contents. Adjust these diagnostics' ranges to reflect
2751                // any unsaved edits.
2752                start = edits_since_save.old_to_new(entry.range.start);
2753                end = edits_since_save.old_to_new(entry.range.end);
2754            } else {
2755                start = entry.range.start;
2756                end = entry.range.end;
2757            }
2758
2759            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
2760                ..snapshot.clip_point_utf16(end, Bias::Right);
2761
2762            // Expand empty ranges by one codepoint
2763            if range.start == range.end {
2764                // This will be go to the next boundary when being clipped
2765                range.end.column += 1;
2766                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
2767                if range.start == range.end && range.end.column > 0 {
2768                    range.start.column -= 1;
2769                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
2770                }
2771            }
2772
2773            sanitized_diagnostics.push(DiagnosticEntry {
2774                range,
2775                diagnostic: entry.diagnostic,
2776            });
2777        }
2778        drop(edits_since_save);
2779
2780        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
2781        buffer.update(cx, |buffer, cx| buffer.update_diagnostics(set, cx));
2782        Ok(())
2783    }
2784
2785    pub fn reload_buffers(
2786        &self,
2787        buffers: HashSet<ModelHandle<Buffer>>,
2788        push_to_history: bool,
2789        cx: &mut ModelContext<Self>,
2790    ) -> Task<Result<ProjectTransaction>> {
2791        let mut local_buffers = Vec::new();
2792        let mut remote_buffers = None;
2793        for buffer_handle in buffers {
2794            let buffer = buffer_handle.read(cx);
2795            if buffer.is_dirty() {
2796                if let Some(file) = File::from_dyn(buffer.file()) {
2797                    if file.is_local() {
2798                        local_buffers.push(buffer_handle);
2799                    } else {
2800                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
2801                    }
2802                }
2803            }
2804        }
2805
2806        let remote_buffers = self.remote_id().zip(remote_buffers);
2807        let client = self.client.clone();
2808
2809        cx.spawn(|this, mut cx| async move {
2810            let mut project_transaction = ProjectTransaction::default();
2811
2812            if let Some((project_id, remote_buffers)) = remote_buffers {
2813                let response = client
2814                    .request(proto::ReloadBuffers {
2815                        project_id,
2816                        buffer_ids: remote_buffers
2817                            .iter()
2818                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2819                            .collect(),
2820                    })
2821                    .await?
2822                    .transaction
2823                    .ok_or_else(|| anyhow!("missing transaction"))?;
2824                project_transaction = this
2825                    .update(&mut cx, |this, cx| {
2826                        this.deserialize_project_transaction(response, push_to_history, cx)
2827                    })
2828                    .await?;
2829            }
2830
2831            for buffer in local_buffers {
2832                let transaction = buffer
2833                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
2834                    .await?;
2835                buffer.update(&mut cx, |buffer, cx| {
2836                    if let Some(transaction) = transaction {
2837                        if !push_to_history {
2838                            buffer.forget_transaction(transaction.id);
2839                        }
2840                        project_transaction.0.insert(cx.handle(), transaction);
2841                    }
2842                });
2843            }
2844
2845            Ok(project_transaction)
2846        })
2847    }
2848
2849    pub fn format(
2850        &self,
2851        buffers: HashSet<ModelHandle<Buffer>>,
2852        push_to_history: bool,
2853        trigger: FormatTrigger,
2854        cx: &mut ModelContext<Project>,
2855    ) -> Task<Result<ProjectTransaction>> {
2856        if self.is_local() {
2857            let mut buffers_with_paths_and_servers = buffers
2858                .into_iter()
2859                .filter_map(|buffer_handle| {
2860                    let buffer = buffer_handle.read(cx);
2861                    let file = File::from_dyn(buffer.file())?;
2862                    let buffer_abs_path = file.as_local()?.abs_path(cx);
2863                    let (_, server) = self.language_server_for_buffer(buffer, cx)?;
2864                    Some((buffer_handle, buffer_abs_path, server.clone()))
2865                })
2866                .collect::<Vec<_>>();
2867
2868            cx.spawn(|this, mut cx| async move {
2869                // Do not allow multiple concurrent formatting requests for the
2870                // same buffer.
2871                this.update(&mut cx, |this, _| {
2872                    buffers_with_paths_and_servers
2873                        .retain(|(buffer, _, _)| this.buffers_being_formatted.insert(buffer.id()));
2874                });
2875
2876                let _cleanup = defer({
2877                    let this = this.clone();
2878                    let mut cx = cx.clone();
2879                    let local_buffers = &buffers_with_paths_and_servers;
2880                    move || {
2881                        this.update(&mut cx, |this, _| {
2882                            for (buffer, _, _) in local_buffers {
2883                                this.buffers_being_formatted.remove(&buffer.id());
2884                            }
2885                        });
2886                    }
2887                });
2888
2889                let mut project_transaction = ProjectTransaction::default();
2890                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
2891                    let (format_on_save, formatter, tab_size) =
2892                        buffer.read_with(&cx, |buffer, cx| {
2893                            let settings = cx.global::<Settings>();
2894                            let language_name = buffer.language().map(|language| language.name());
2895                            (
2896                                settings.format_on_save(language_name.as_deref()),
2897                                settings.formatter(language_name.as_deref()),
2898                                settings.tab_size(language_name.as_deref()),
2899                            )
2900                        });
2901
2902                    let transaction = match (formatter, format_on_save) {
2903                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => continue,
2904
2905                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
2906                        | (_, FormatOnSave::LanguageServer) => Self::format_via_lsp(
2907                            &this,
2908                            &buffer,
2909                            &buffer_abs_path,
2910                            &language_server,
2911                            tab_size,
2912                            &mut cx,
2913                        )
2914                        .await
2915                        .context("failed to format via language server")?,
2916
2917                        (
2918                            Formatter::External { command, arguments },
2919                            FormatOnSave::On | FormatOnSave::Off,
2920                        )
2921                        | (_, FormatOnSave::External { command, arguments }) => {
2922                            Self::format_via_external_command(
2923                                &buffer,
2924                                &buffer_abs_path,
2925                                &command,
2926                                &arguments,
2927                                &mut cx,
2928                            )
2929                            .await
2930                            .context(format!(
2931                                "failed to format via external command {:?}",
2932                                command
2933                            ))?
2934                        }
2935                    };
2936
2937                    if let Some(transaction) = transaction {
2938                        if !push_to_history {
2939                            buffer.update(&mut cx, |buffer, _| {
2940                                buffer.forget_transaction(transaction.id)
2941                            });
2942                        }
2943                        project_transaction.0.insert(buffer.clone(), transaction);
2944                    }
2945                }
2946
2947                Ok(project_transaction)
2948            })
2949        } else {
2950            let remote_id = self.remote_id();
2951            let client = self.client.clone();
2952            cx.spawn(|this, mut cx| async move {
2953                let mut project_transaction = ProjectTransaction::default();
2954                if let Some(project_id) = remote_id {
2955                    let response = client
2956                        .request(proto::FormatBuffers {
2957                            project_id,
2958                            trigger: trigger as i32,
2959                            buffer_ids: buffers
2960                                .iter()
2961                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
2962                                .collect(),
2963                        })
2964                        .await?
2965                        .transaction
2966                        .ok_or_else(|| anyhow!("missing transaction"))?;
2967                    project_transaction = this
2968                        .update(&mut cx, |this, cx| {
2969                            this.deserialize_project_transaction(response, push_to_history, cx)
2970                        })
2971                        .await?;
2972                }
2973                Ok(project_transaction)
2974            })
2975        }
2976    }
2977
2978    async fn format_via_lsp(
2979        this: &ModelHandle<Self>,
2980        buffer: &ModelHandle<Buffer>,
2981        abs_path: &Path,
2982        language_server: &Arc<LanguageServer>,
2983        tab_size: NonZeroU32,
2984        cx: &mut AsyncAppContext,
2985    ) -> Result<Option<Transaction>> {
2986        let text_document =
2987            lsp::TextDocumentIdentifier::new(lsp::Url::from_file_path(abs_path).unwrap());
2988        let capabilities = &language_server.capabilities();
2989        let lsp_edits = if capabilities
2990            .document_formatting_provider
2991            .as_ref()
2992            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
2993        {
2994            language_server
2995                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
2996                    text_document,
2997                    options: lsp::FormattingOptions {
2998                        tab_size: tab_size.into(),
2999                        insert_spaces: true,
3000                        insert_final_newline: Some(true),
3001                        ..Default::default()
3002                    },
3003                    work_done_progress_params: Default::default(),
3004                })
3005                .await?
3006        } else if capabilities
3007            .document_range_formatting_provider
3008            .as_ref()
3009            .map_or(false, |provider| *provider != lsp::OneOf::Left(false))
3010        {
3011            let buffer_start = lsp::Position::new(0, 0);
3012            let buffer_end =
3013                buffer.read_with(cx, |buffer, _| point_to_lsp(buffer.max_point_utf16()));
3014            language_server
3015                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
3016                    text_document,
3017                    range: lsp::Range::new(buffer_start, buffer_end),
3018                    options: lsp::FormattingOptions {
3019                        tab_size: tab_size.into(),
3020                        insert_spaces: true,
3021                        insert_final_newline: Some(true),
3022                        ..Default::default()
3023                    },
3024                    work_done_progress_params: Default::default(),
3025                })
3026                .await?
3027        } else {
3028            None
3029        };
3030
3031        if let Some(lsp_edits) = lsp_edits {
3032            let edits = this
3033                .update(cx, |this, cx| {
3034                    this.edits_from_lsp(buffer, lsp_edits, None, cx)
3035                })
3036                .await?;
3037            buffer.update(cx, |buffer, cx| {
3038                buffer.finalize_last_transaction();
3039                buffer.start_transaction();
3040                for (range, text) in edits {
3041                    buffer.edit([(range, text)], None, cx);
3042                }
3043                if buffer.end_transaction(cx).is_some() {
3044                    let transaction = buffer.finalize_last_transaction().unwrap().clone();
3045                    Ok(Some(transaction))
3046                } else {
3047                    Ok(None)
3048                }
3049            })
3050        } else {
3051            Ok(None)
3052        }
3053    }
3054
3055    async fn format_via_external_command(
3056        buffer: &ModelHandle<Buffer>,
3057        buffer_abs_path: &Path,
3058        command: &str,
3059        arguments: &[String],
3060        cx: &mut AsyncAppContext,
3061    ) -> Result<Option<Transaction>> {
3062        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
3063            let file = File::from_dyn(buffer.file())?;
3064            let worktree = file.worktree.read(cx).as_local()?;
3065            let mut worktree_path = worktree.abs_path().to_path_buf();
3066            if worktree.root_entry()?.is_file() {
3067                worktree_path.pop();
3068            }
3069            Some(worktree_path)
3070        });
3071
3072        if let Some(working_dir_path) = working_dir_path {
3073            let mut child =
3074                smol::process::Command::new(command)
3075                    .args(arguments.iter().map(|arg| {
3076                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
3077                    }))
3078                    .current_dir(&working_dir_path)
3079                    .stdin(smol::process::Stdio::piped())
3080                    .stdout(smol::process::Stdio::piped())
3081                    .stderr(smol::process::Stdio::piped())
3082                    .spawn()?;
3083            let stdin = child
3084                .stdin
3085                .as_mut()
3086                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
3087            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
3088            for chunk in text.chunks() {
3089                stdin.write_all(chunk.as_bytes()).await?;
3090            }
3091            stdin.flush().await?;
3092
3093            let output = child.output().await?;
3094            if !output.status.success() {
3095                return Err(anyhow!(
3096                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
3097                    output.status.code(),
3098                    String::from_utf8_lossy(&output.stdout),
3099                    String::from_utf8_lossy(&output.stderr),
3100                ));
3101            }
3102
3103            let stdout = String::from_utf8(output.stdout)?;
3104            let diff = buffer
3105                .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
3106                .await;
3107            Ok(buffer.update(cx, |buffer, cx| buffer.apply_diff(diff, cx).cloned()))
3108        } else {
3109            Ok(None)
3110        }
3111    }
3112
3113    pub fn definition<T: ToPointUtf16>(
3114        &self,
3115        buffer: &ModelHandle<Buffer>,
3116        position: T,
3117        cx: &mut ModelContext<Self>,
3118    ) -> Task<Result<Vec<LocationLink>>> {
3119        let position = position.to_point_utf16(buffer.read(cx));
3120        self.request_lsp(buffer.clone(), GetDefinition { position }, cx)
3121    }
3122
3123    pub fn type_definition<T: ToPointUtf16>(
3124        &self,
3125        buffer: &ModelHandle<Buffer>,
3126        position: T,
3127        cx: &mut ModelContext<Self>,
3128    ) -> Task<Result<Vec<LocationLink>>> {
3129        let position = position.to_point_utf16(buffer.read(cx));
3130        self.request_lsp(buffer.clone(), GetTypeDefinition { position }, cx)
3131    }
3132
3133    pub fn references<T: ToPointUtf16>(
3134        &self,
3135        buffer: &ModelHandle<Buffer>,
3136        position: T,
3137        cx: &mut ModelContext<Self>,
3138    ) -> Task<Result<Vec<Location>>> {
3139        let position = position.to_point_utf16(buffer.read(cx));
3140        self.request_lsp(buffer.clone(), GetReferences { position }, cx)
3141    }
3142
3143    pub fn document_highlights<T: ToPointUtf16>(
3144        &self,
3145        buffer: &ModelHandle<Buffer>,
3146        position: T,
3147        cx: &mut ModelContext<Self>,
3148    ) -> Task<Result<Vec<DocumentHighlight>>> {
3149        let position = position.to_point_utf16(buffer.read(cx));
3150        self.request_lsp(buffer.clone(), GetDocumentHighlights { position }, cx)
3151    }
3152
3153    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
3154        if self.is_local() {
3155            let mut requests = Vec::new();
3156            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
3157                let worktree_id = *worktree_id;
3158                if let Some(worktree) = self
3159                    .worktree_for_id(worktree_id, cx)
3160                    .and_then(|worktree| worktree.read(cx).as_local())
3161                {
3162                    if let Some(LanguageServerState::Running {
3163                        adapter,
3164                        language,
3165                        server,
3166                        ..
3167                    }) = self.language_servers.get(server_id)
3168                    {
3169                        let adapter = adapter.clone();
3170                        let language = language.clone();
3171                        let worktree_abs_path = worktree.abs_path().clone();
3172                        requests.push(
3173                            server
3174                                .request::<lsp::request::WorkspaceSymbol>(
3175                                    lsp::WorkspaceSymbolParams {
3176                                        query: query.to_string(),
3177                                        ..Default::default()
3178                                    },
3179                                )
3180                                .log_err()
3181                                .map(move |response| {
3182                                    (
3183                                        adapter,
3184                                        language,
3185                                        worktree_id,
3186                                        worktree_abs_path,
3187                                        response.unwrap_or_default(),
3188                                    )
3189                                }),
3190                        );
3191                    }
3192                }
3193            }
3194
3195            cx.spawn_weak(|this, cx| async move {
3196                let responses = futures::future::join_all(requests).await;
3197                let this = if let Some(this) = this.upgrade(&cx) {
3198                    this
3199                } else {
3200                    return Ok(Default::default());
3201                };
3202                let symbols = this.read_with(&cx, |this, cx| {
3203                    let mut symbols = Vec::new();
3204                    for (
3205                        adapter,
3206                        adapter_language,
3207                        source_worktree_id,
3208                        worktree_abs_path,
3209                        response,
3210                    ) in responses
3211                    {
3212                        symbols.extend(response.into_iter().flatten().filter_map(|lsp_symbol| {
3213                            let abs_path = lsp_symbol.location.uri.to_file_path().ok()?;
3214                            let mut worktree_id = source_worktree_id;
3215                            let path;
3216                            if let Some((worktree, rel_path)) =
3217                                this.find_local_worktree(&abs_path, cx)
3218                            {
3219                                worktree_id = worktree.read(cx).id();
3220                                path = rel_path;
3221                            } else {
3222                                path = relativize_path(&worktree_abs_path, &abs_path);
3223                            }
3224
3225                            let project_path = ProjectPath {
3226                                worktree_id,
3227                                path: path.into(),
3228                            };
3229                            let signature = this.symbol_signature(&project_path);
3230                            let language = this
3231                                .languages
3232                                .language_for_path(&project_path.path)
3233                                .unwrap_or(adapter_language.clone());
3234                            let language_server_name = adapter.name.clone();
3235                            Some(async move {
3236                                let label = language
3237                                    .label_for_symbol(&lsp_symbol.name, lsp_symbol.kind)
3238                                    .await;
3239
3240                                Symbol {
3241                                    language_server_name,
3242                                    source_worktree_id,
3243                                    path: project_path,
3244                                    label: label.unwrap_or_else(|| {
3245                                        CodeLabel::plain(lsp_symbol.name.clone(), None)
3246                                    }),
3247                                    kind: lsp_symbol.kind,
3248                                    name: lsp_symbol.name,
3249                                    range: range_from_lsp(lsp_symbol.location.range),
3250                                    signature,
3251                                }
3252                            })
3253                        }));
3254                    }
3255                    symbols
3256                });
3257                Ok(futures::future::join_all(symbols).await)
3258            })
3259        } else if let Some(project_id) = self.remote_id() {
3260            let request = self.client.request(proto::GetProjectSymbols {
3261                project_id,
3262                query: query.to_string(),
3263            });
3264            cx.spawn_weak(|this, cx| async move {
3265                let response = request.await?;
3266                let mut symbols = Vec::new();
3267                if let Some(this) = this.upgrade(&cx) {
3268                    let new_symbols = this.read_with(&cx, |this, _| {
3269                        response
3270                            .symbols
3271                            .into_iter()
3272                            .map(|symbol| this.deserialize_symbol(symbol))
3273                            .collect::<Vec<_>>()
3274                    });
3275                    symbols = futures::future::join_all(new_symbols)
3276                        .await
3277                        .into_iter()
3278                        .filter_map(|symbol| symbol.log_err())
3279                        .collect::<Vec<_>>();
3280                }
3281                Ok(symbols)
3282            })
3283        } else {
3284            Task::ready(Ok(Default::default()))
3285        }
3286    }
3287
3288    pub fn open_buffer_for_symbol(
3289        &mut self,
3290        symbol: &Symbol,
3291        cx: &mut ModelContext<Self>,
3292    ) -> Task<Result<ModelHandle<Buffer>>> {
3293        if self.is_local() {
3294            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
3295                symbol.source_worktree_id,
3296                symbol.language_server_name.clone(),
3297            )) {
3298                *id
3299            } else {
3300                return Task::ready(Err(anyhow!(
3301                    "language server for worktree and language not found"
3302                )));
3303            };
3304
3305            let worktree_abs_path = if let Some(worktree_abs_path) = self
3306                .worktree_for_id(symbol.path.worktree_id, cx)
3307                .and_then(|worktree| worktree.read(cx).as_local())
3308                .map(|local_worktree| local_worktree.abs_path())
3309            {
3310                worktree_abs_path
3311            } else {
3312                return Task::ready(Err(anyhow!("worktree not found for symbol")));
3313            };
3314            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
3315            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
3316                uri
3317            } else {
3318                return Task::ready(Err(anyhow!("invalid symbol path")));
3319            };
3320
3321            self.open_local_buffer_via_lsp(
3322                symbol_uri,
3323                language_server_id,
3324                symbol.language_server_name.clone(),
3325                cx,
3326            )
3327        } else if let Some(project_id) = self.remote_id() {
3328            let request = self.client.request(proto::OpenBufferForSymbol {
3329                project_id,
3330                symbol: Some(serialize_symbol(symbol)),
3331            });
3332            cx.spawn(|this, mut cx| async move {
3333                let response = request.await?;
3334                this.update(&mut cx, |this, cx| {
3335                    this.wait_for_remote_buffer(response.buffer_id, cx)
3336                })
3337                .await
3338            })
3339        } else {
3340            Task::ready(Err(anyhow!("project does not have a remote id")))
3341        }
3342    }
3343
3344    pub fn hover<T: ToPointUtf16>(
3345        &self,
3346        buffer: &ModelHandle<Buffer>,
3347        position: T,
3348        cx: &mut ModelContext<Self>,
3349    ) -> Task<Result<Option<Hover>>> {
3350        let position = position.to_point_utf16(buffer.read(cx));
3351        self.request_lsp(buffer.clone(), GetHover { position }, cx)
3352    }
3353
3354    pub fn completions<T: ToPointUtf16>(
3355        &self,
3356        source_buffer_handle: &ModelHandle<Buffer>,
3357        position: T,
3358        cx: &mut ModelContext<Self>,
3359    ) -> Task<Result<Vec<Completion>>> {
3360        let source_buffer_handle = source_buffer_handle.clone();
3361        let source_buffer = source_buffer_handle.read(cx);
3362        let buffer_id = source_buffer.remote_id();
3363        let language = source_buffer.language().cloned();
3364        let worktree;
3365        let buffer_abs_path;
3366        if let Some(file) = File::from_dyn(source_buffer.file()) {
3367            worktree = file.worktree.clone();
3368            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3369        } else {
3370            return Task::ready(Ok(Default::default()));
3371        };
3372
3373        let position = Unclipped(position.to_point_utf16(source_buffer));
3374        let anchor = source_buffer.anchor_after(position);
3375
3376        if worktree.read(cx).as_local().is_some() {
3377            let buffer_abs_path = buffer_abs_path.unwrap();
3378            let lang_server =
3379                if let Some((_, server)) = self.language_server_for_buffer(source_buffer, cx) {
3380                    server.clone()
3381                } else {
3382                    return Task::ready(Ok(Default::default()));
3383                };
3384
3385            cx.spawn(|_, cx| async move {
3386                let completions = lang_server
3387                    .request::<lsp::request::Completion>(lsp::CompletionParams {
3388                        text_document_position: lsp::TextDocumentPositionParams::new(
3389                            lsp::TextDocumentIdentifier::new(
3390                                lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3391                            ),
3392                            point_to_lsp(position.0),
3393                        ),
3394                        context: Default::default(),
3395                        work_done_progress_params: Default::default(),
3396                        partial_result_params: Default::default(),
3397                    })
3398                    .await
3399                    .context("lsp completion request failed")?;
3400
3401                let completions = if let Some(completions) = completions {
3402                    match completions {
3403                        lsp::CompletionResponse::Array(completions) => completions,
3404                        lsp::CompletionResponse::List(list) => list.items,
3405                    }
3406                } else {
3407                    Default::default()
3408                };
3409
3410                let completions = source_buffer_handle.read_with(&cx, |this, _| {
3411                    let snapshot = this.snapshot();
3412                    let clipped_position = this.clip_point_utf16(position, Bias::Left);
3413                    let mut range_for_token = None;
3414                    completions
3415                        .into_iter()
3416                        .filter_map(move |mut lsp_completion| {
3417                            // For now, we can only handle additional edits if they are returned
3418                            // when resolving the completion, not if they are present initially.
3419                            if lsp_completion
3420                                .additional_text_edits
3421                                .as_ref()
3422                                .map_or(false, |edits| !edits.is_empty())
3423                            {
3424                                return None;
3425                            }
3426
3427                            let (old_range, mut new_text) = match lsp_completion.text_edit.as_ref()
3428                            {
3429                                // If the language server provides a range to overwrite, then
3430                                // check that the range is valid.
3431                                Some(lsp::CompletionTextEdit::Edit(edit)) => {
3432                                    let range = range_from_lsp(edit.range);
3433                                    let start = snapshot.clip_point_utf16(range.start, Bias::Left);
3434                                    let end = snapshot.clip_point_utf16(range.end, Bias::Left);
3435                                    if start != range.start.0 || end != range.end.0 {
3436                                        log::info!("completion out of expected range");
3437                                        return None;
3438                                    }
3439                                    (
3440                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3441                                        edit.new_text.clone(),
3442                                    )
3443                                }
3444                                // If the language server does not provide a range, then infer
3445                                // the range based on the syntax tree.
3446                                None => {
3447                                    if position.0 != clipped_position {
3448                                        log::info!("completion out of expected range");
3449                                        return None;
3450                                    }
3451                                    let Range { start, end } = range_for_token
3452                                        .get_or_insert_with(|| {
3453                                            let offset = position.to_offset(&snapshot);
3454                                            let (range, kind) = snapshot.surrounding_word(offset);
3455                                            if kind == Some(CharKind::Word) {
3456                                                range
3457                                            } else {
3458                                                offset..offset
3459                                            }
3460                                        })
3461                                        .clone();
3462                                    let text = lsp_completion
3463                                        .insert_text
3464                                        .as_ref()
3465                                        .unwrap_or(&lsp_completion.label)
3466                                        .clone();
3467                                    (
3468                                        snapshot.anchor_before(start)..snapshot.anchor_after(end),
3469                                        text,
3470                                    )
3471                                }
3472                                Some(lsp::CompletionTextEdit::InsertAndReplace(_)) => {
3473                                    log::info!("unsupported insert/replace completion");
3474                                    return None;
3475                                }
3476                            };
3477
3478                            LineEnding::normalize(&mut new_text);
3479                            let language = language.clone();
3480                            Some(async move {
3481                                let mut label = None;
3482                                if let Some(language) = language {
3483                                    language.process_completion(&mut lsp_completion).await;
3484                                    label = language.label_for_completion(&lsp_completion).await;
3485                                }
3486                                Completion {
3487                                    old_range,
3488                                    new_text,
3489                                    label: label.unwrap_or_else(|| {
3490                                        CodeLabel::plain(
3491                                            lsp_completion.label.clone(),
3492                                            lsp_completion.filter_text.as_deref(),
3493                                        )
3494                                    }),
3495                                    lsp_completion,
3496                                }
3497                            })
3498                        })
3499                });
3500
3501                Ok(futures::future::join_all(completions).await)
3502            })
3503        } else if let Some(project_id) = self.remote_id() {
3504            let rpc = self.client.clone();
3505            let message = proto::GetCompletions {
3506                project_id,
3507                buffer_id,
3508                position: Some(language::proto::serialize_anchor(&anchor)),
3509                version: serialize_version(&source_buffer.version()),
3510            };
3511            cx.spawn_weak(|this, mut cx| async move {
3512                let response = rpc.request(message).await?;
3513
3514                if this
3515                    .upgrade(&cx)
3516                    .ok_or_else(|| anyhow!("project was dropped"))?
3517                    .read_with(&cx, |this, _| this.is_read_only())
3518                {
3519                    return Err(anyhow!(
3520                        "failed to get completions: project was disconnected"
3521                    ));
3522                } else {
3523                    source_buffer_handle
3524                        .update(&mut cx, |buffer, _| {
3525                            buffer.wait_for_version(deserialize_version(response.version))
3526                        })
3527                        .await;
3528
3529                    let completions = response.completions.into_iter().map(|completion| {
3530                        language::proto::deserialize_completion(completion, language.clone())
3531                    });
3532                    futures::future::try_join_all(completions).await
3533                }
3534            })
3535        } else {
3536            Task::ready(Ok(Default::default()))
3537        }
3538    }
3539
3540    pub fn apply_additional_edits_for_completion(
3541        &self,
3542        buffer_handle: ModelHandle<Buffer>,
3543        completion: Completion,
3544        push_to_history: bool,
3545        cx: &mut ModelContext<Self>,
3546    ) -> Task<Result<Option<Transaction>>> {
3547        let buffer = buffer_handle.read(cx);
3548        let buffer_id = buffer.remote_id();
3549
3550        if self.is_local() {
3551            let lang_server = match self.language_server_for_buffer(buffer, cx) {
3552                Some((_, server)) => server.clone(),
3553                _ => return Task::ready(Ok(Default::default())),
3554            };
3555
3556            cx.spawn(|this, mut cx| async move {
3557                let resolved_completion = lang_server
3558                    .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
3559                    .await?;
3560
3561                if let Some(edits) = resolved_completion.additional_text_edits {
3562                    let edits = this
3563                        .update(&mut cx, |this, cx| {
3564                            this.edits_from_lsp(&buffer_handle, edits, None, cx)
3565                        })
3566                        .await?;
3567
3568                    buffer_handle.update(&mut cx, |buffer, cx| {
3569                        buffer.finalize_last_transaction();
3570                        buffer.start_transaction();
3571
3572                        for (range, text) in edits {
3573                            let primary = &completion.old_range;
3574                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
3575                                && primary.end.cmp(&range.start, buffer).is_ge();
3576                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
3577                                && range.end.cmp(&primary.end, buffer).is_ge();
3578
3579                            //Skip addtional edits which overlap with the primary completion edit
3580                            //https://github.com/zed-industries/zed/pull/1871
3581                            if !start_within && !end_within {
3582                                buffer.edit([(range, text)], None, cx);
3583                            }
3584                        }
3585
3586                        let transaction = if buffer.end_transaction(cx).is_some() {
3587                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3588                            if !push_to_history {
3589                                buffer.forget_transaction(transaction.id);
3590                            }
3591                            Some(transaction)
3592                        } else {
3593                            None
3594                        };
3595                        Ok(transaction)
3596                    })
3597                } else {
3598                    Ok(None)
3599                }
3600            })
3601        } else if let Some(project_id) = self.remote_id() {
3602            let client = self.client.clone();
3603            cx.spawn(|_, mut cx| async move {
3604                let response = client
3605                    .request(proto::ApplyCompletionAdditionalEdits {
3606                        project_id,
3607                        buffer_id,
3608                        completion: Some(language::proto::serialize_completion(&completion)),
3609                    })
3610                    .await?;
3611
3612                if let Some(transaction) = response.transaction {
3613                    let transaction = language::proto::deserialize_transaction(transaction)?;
3614                    buffer_handle
3615                        .update(&mut cx, |buffer, _| {
3616                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
3617                        })
3618                        .await;
3619                    if push_to_history {
3620                        buffer_handle.update(&mut cx, |buffer, _| {
3621                            buffer.push_transaction(transaction.clone(), Instant::now());
3622                        });
3623                    }
3624                    Ok(Some(transaction))
3625                } else {
3626                    Ok(None)
3627                }
3628            })
3629        } else {
3630            Task::ready(Err(anyhow!("project does not have a remote id")))
3631        }
3632    }
3633
3634    pub fn code_actions<T: Clone + ToOffset>(
3635        &self,
3636        buffer_handle: &ModelHandle<Buffer>,
3637        range: Range<T>,
3638        cx: &mut ModelContext<Self>,
3639    ) -> Task<Result<Vec<CodeAction>>> {
3640        let buffer_handle = buffer_handle.clone();
3641        let buffer = buffer_handle.read(cx);
3642        let snapshot = buffer.snapshot();
3643        let relevant_diagnostics = snapshot
3644            .diagnostics_in_range::<usize, usize>(range.to_offset(&snapshot), false)
3645            .map(|entry| entry.to_lsp_diagnostic_stub())
3646            .collect();
3647        let buffer_id = buffer.remote_id();
3648        let worktree;
3649        let buffer_abs_path;
3650        if let Some(file) = File::from_dyn(buffer.file()) {
3651            worktree = file.worktree.clone();
3652            buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
3653        } else {
3654            return Task::ready(Ok(Default::default()));
3655        };
3656        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3657
3658        if worktree.read(cx).as_local().is_some() {
3659            let buffer_abs_path = buffer_abs_path.unwrap();
3660            let lang_server = if let Some((_, server)) = self.language_server_for_buffer(buffer, cx)
3661            {
3662                server.clone()
3663            } else {
3664                return Task::ready(Ok(Default::default()));
3665            };
3666
3667            let lsp_range = range_to_lsp(range.to_point_utf16(buffer));
3668            cx.foreground().spawn(async move {
3669                if lang_server.capabilities().code_action_provider.is_none() {
3670                    return Ok(Default::default());
3671                }
3672
3673                Ok(lang_server
3674                    .request::<lsp::request::CodeActionRequest>(lsp::CodeActionParams {
3675                        text_document: lsp::TextDocumentIdentifier::new(
3676                            lsp::Url::from_file_path(buffer_abs_path).unwrap(),
3677                        ),
3678                        range: lsp_range,
3679                        work_done_progress_params: Default::default(),
3680                        partial_result_params: Default::default(),
3681                        context: lsp::CodeActionContext {
3682                            diagnostics: relevant_diagnostics,
3683                            only: Some(vec![
3684                                lsp::CodeActionKind::EMPTY,
3685                                lsp::CodeActionKind::QUICKFIX,
3686                                lsp::CodeActionKind::REFACTOR,
3687                                lsp::CodeActionKind::REFACTOR_EXTRACT,
3688                                lsp::CodeActionKind::SOURCE,
3689                            ]),
3690                        },
3691                    })
3692                    .await?
3693                    .unwrap_or_default()
3694                    .into_iter()
3695                    .filter_map(|entry| {
3696                        if let lsp::CodeActionOrCommand::CodeAction(lsp_action) = entry {
3697                            Some(CodeAction {
3698                                range: range.clone(),
3699                                lsp_action,
3700                            })
3701                        } else {
3702                            None
3703                        }
3704                    })
3705                    .collect())
3706            })
3707        } else if let Some(project_id) = self.remote_id() {
3708            let rpc = self.client.clone();
3709            let version = buffer.version();
3710            cx.spawn_weak(|this, mut cx| async move {
3711                let response = rpc
3712                    .request(proto::GetCodeActions {
3713                        project_id,
3714                        buffer_id,
3715                        start: Some(language::proto::serialize_anchor(&range.start)),
3716                        end: Some(language::proto::serialize_anchor(&range.end)),
3717                        version: serialize_version(&version),
3718                    })
3719                    .await?;
3720
3721                if this
3722                    .upgrade(&cx)
3723                    .ok_or_else(|| anyhow!("project was dropped"))?
3724                    .read_with(&cx, |this, _| this.is_read_only())
3725                {
3726                    return Err(anyhow!(
3727                        "failed to get code actions: project was disconnected"
3728                    ));
3729                } else {
3730                    buffer_handle
3731                        .update(&mut cx, |buffer, _| {
3732                            buffer.wait_for_version(deserialize_version(response.version))
3733                        })
3734                        .await;
3735
3736                    response
3737                        .actions
3738                        .into_iter()
3739                        .map(language::proto::deserialize_code_action)
3740                        .collect()
3741                }
3742            })
3743        } else {
3744            Task::ready(Ok(Default::default()))
3745        }
3746    }
3747
3748    pub fn apply_code_action(
3749        &self,
3750        buffer_handle: ModelHandle<Buffer>,
3751        mut action: CodeAction,
3752        push_to_history: bool,
3753        cx: &mut ModelContext<Self>,
3754    ) -> Task<Result<ProjectTransaction>> {
3755        if self.is_local() {
3756            let buffer = buffer_handle.read(cx);
3757            let (lsp_adapter, lang_server) =
3758                if let Some((adapter, server)) = self.language_server_for_buffer(buffer, cx) {
3759                    (adapter.clone(), server.clone())
3760                } else {
3761                    return Task::ready(Ok(Default::default()));
3762                };
3763            let range = action.range.to_point_utf16(buffer);
3764
3765            cx.spawn(|this, mut cx| async move {
3766                if let Some(lsp_range) = action
3767                    .lsp_action
3768                    .data
3769                    .as_mut()
3770                    .and_then(|d| d.get_mut("codeActionParams"))
3771                    .and_then(|d| d.get_mut("range"))
3772                {
3773                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
3774                    action.lsp_action = lang_server
3775                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
3776                        .await?;
3777                } else {
3778                    let actions = this
3779                        .update(&mut cx, |this, cx| {
3780                            this.code_actions(&buffer_handle, action.range, cx)
3781                        })
3782                        .await?;
3783                    action.lsp_action = actions
3784                        .into_iter()
3785                        .find(|a| a.lsp_action.title == action.lsp_action.title)
3786                        .ok_or_else(|| anyhow!("code action is outdated"))?
3787                        .lsp_action;
3788                }
3789
3790                if let Some(edit) = action.lsp_action.edit {
3791                    if edit.changes.is_some() || edit.document_changes.is_some() {
3792                        return Self::deserialize_workspace_edit(
3793                            this,
3794                            edit,
3795                            push_to_history,
3796                            lsp_adapter.clone(),
3797                            lang_server.clone(),
3798                            &mut cx,
3799                        )
3800                        .await;
3801                    }
3802                }
3803
3804                if let Some(command) = action.lsp_action.command {
3805                    this.update(&mut cx, |this, _| {
3806                        this.last_workspace_edits_by_language_server
3807                            .remove(&lang_server.server_id());
3808                    });
3809                    lang_server
3810                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
3811                            command: command.command,
3812                            arguments: command.arguments.unwrap_or_default(),
3813                            ..Default::default()
3814                        })
3815                        .await?;
3816                    return Ok(this.update(&mut cx, |this, _| {
3817                        this.last_workspace_edits_by_language_server
3818                            .remove(&lang_server.server_id())
3819                            .unwrap_or_default()
3820                    }));
3821                }
3822
3823                Ok(ProjectTransaction::default())
3824            })
3825        } else if let Some(project_id) = self.remote_id() {
3826            let client = self.client.clone();
3827            let request = proto::ApplyCodeAction {
3828                project_id,
3829                buffer_id: buffer_handle.read(cx).remote_id(),
3830                action: Some(language::proto::serialize_code_action(&action)),
3831            };
3832            cx.spawn(|this, mut cx| async move {
3833                let response = client
3834                    .request(request)
3835                    .await?
3836                    .transaction
3837                    .ok_or_else(|| anyhow!("missing transaction"))?;
3838                this.update(&mut cx, |this, cx| {
3839                    this.deserialize_project_transaction(response, push_to_history, cx)
3840                })
3841                .await
3842            })
3843        } else {
3844            Task::ready(Err(anyhow!("project does not have a remote id")))
3845        }
3846    }
3847
3848    async fn deserialize_workspace_edit(
3849        this: ModelHandle<Self>,
3850        edit: lsp::WorkspaceEdit,
3851        push_to_history: bool,
3852        lsp_adapter: Arc<CachedLspAdapter>,
3853        language_server: Arc<LanguageServer>,
3854        cx: &mut AsyncAppContext,
3855    ) -> Result<ProjectTransaction> {
3856        let fs = this.read_with(cx, |this, _| this.fs.clone());
3857        let mut operations = Vec::new();
3858        if let Some(document_changes) = edit.document_changes {
3859            match document_changes {
3860                lsp::DocumentChanges::Edits(edits) => {
3861                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
3862                }
3863                lsp::DocumentChanges::Operations(ops) => operations = ops,
3864            }
3865        } else if let Some(changes) = edit.changes {
3866            operations.extend(changes.into_iter().map(|(uri, edits)| {
3867                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
3868                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
3869                        uri,
3870                        version: None,
3871                    },
3872                    edits: edits.into_iter().map(lsp::OneOf::Left).collect(),
3873                })
3874            }));
3875        }
3876
3877        let mut project_transaction = ProjectTransaction::default();
3878        for operation in operations {
3879            match operation {
3880                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
3881                    let abs_path = op
3882                        .uri
3883                        .to_file_path()
3884                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3885
3886                    if let Some(parent_path) = abs_path.parent() {
3887                        fs.create_dir(parent_path).await?;
3888                    }
3889                    if abs_path.ends_with("/") {
3890                        fs.create_dir(&abs_path).await?;
3891                    } else {
3892                        fs.create_file(&abs_path, op.options.map(Into::into).unwrap_or_default())
3893                            .await?;
3894                    }
3895                }
3896                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
3897                    let source_abs_path = op
3898                        .old_uri
3899                        .to_file_path()
3900                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3901                    let target_abs_path = op
3902                        .new_uri
3903                        .to_file_path()
3904                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3905                    fs.rename(
3906                        &source_abs_path,
3907                        &target_abs_path,
3908                        op.options.map(Into::into).unwrap_or_default(),
3909                    )
3910                    .await?;
3911                }
3912                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
3913                    let abs_path = op
3914                        .uri
3915                        .to_file_path()
3916                        .map_err(|_| anyhow!("can't convert URI to path"))?;
3917                    let options = op.options.map(Into::into).unwrap_or_default();
3918                    if abs_path.ends_with("/") {
3919                        fs.remove_dir(&abs_path, options).await?;
3920                    } else {
3921                        fs.remove_file(&abs_path, options).await?;
3922                    }
3923                }
3924                lsp::DocumentChangeOperation::Edit(op) => {
3925                    let buffer_to_edit = this
3926                        .update(cx, |this, cx| {
3927                            this.open_local_buffer_via_lsp(
3928                                op.text_document.uri,
3929                                language_server.server_id(),
3930                                lsp_adapter.name.clone(),
3931                                cx,
3932                            )
3933                        })
3934                        .await?;
3935
3936                    let edits = this
3937                        .update(cx, |this, cx| {
3938                            let edits = op.edits.into_iter().map(|edit| match edit {
3939                                lsp::OneOf::Left(edit) => edit,
3940                                lsp::OneOf::Right(edit) => edit.text_edit,
3941                            });
3942                            this.edits_from_lsp(
3943                                &buffer_to_edit,
3944                                edits,
3945                                op.text_document.version,
3946                                cx,
3947                            )
3948                        })
3949                        .await?;
3950
3951                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
3952                        buffer.finalize_last_transaction();
3953                        buffer.start_transaction();
3954                        for (range, text) in edits {
3955                            buffer.edit([(range, text)], None, cx);
3956                        }
3957                        let transaction = if buffer.end_transaction(cx).is_some() {
3958                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
3959                            if !push_to_history {
3960                                buffer.forget_transaction(transaction.id);
3961                            }
3962                            Some(transaction)
3963                        } else {
3964                            None
3965                        };
3966
3967                        transaction
3968                    });
3969                    if let Some(transaction) = transaction {
3970                        project_transaction.0.insert(buffer_to_edit, transaction);
3971                    }
3972                }
3973            }
3974        }
3975
3976        Ok(project_transaction)
3977    }
3978
3979    pub fn prepare_rename<T: ToPointUtf16>(
3980        &self,
3981        buffer: ModelHandle<Buffer>,
3982        position: T,
3983        cx: &mut ModelContext<Self>,
3984    ) -> Task<Result<Option<Range<Anchor>>>> {
3985        let position = position.to_point_utf16(buffer.read(cx));
3986        self.request_lsp(buffer, PrepareRename { position }, cx)
3987    }
3988
3989    pub fn perform_rename<T: ToPointUtf16>(
3990        &self,
3991        buffer: ModelHandle<Buffer>,
3992        position: T,
3993        new_name: String,
3994        push_to_history: bool,
3995        cx: &mut ModelContext<Self>,
3996    ) -> Task<Result<ProjectTransaction>> {
3997        let position = position.to_point_utf16(buffer.read(cx));
3998        self.request_lsp(
3999            buffer,
4000            PerformRename {
4001                position,
4002                new_name,
4003                push_to_history,
4004            },
4005            cx,
4006        )
4007    }
4008
4009    #[allow(clippy::type_complexity)]
4010    pub fn search(
4011        &self,
4012        query: SearchQuery,
4013        cx: &mut ModelContext<Self>,
4014    ) -> Task<Result<HashMap<ModelHandle<Buffer>, Vec<Range<Anchor>>>>> {
4015        if self.is_local() {
4016            let snapshots = self
4017                .visible_worktrees(cx)
4018                .filter_map(|tree| {
4019                    let tree = tree.read(cx).as_local()?;
4020                    Some(tree.snapshot())
4021                })
4022                .collect::<Vec<_>>();
4023
4024            let background = cx.background().clone();
4025            let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
4026            if path_count == 0 {
4027                return Task::ready(Ok(Default::default()));
4028            }
4029            let workers = background.num_cpus().min(path_count);
4030            let (matching_paths_tx, mut matching_paths_rx) = smol::channel::bounded(1024);
4031            cx.background()
4032                .spawn({
4033                    let fs = self.fs.clone();
4034                    let background = cx.background().clone();
4035                    let query = query.clone();
4036                    async move {
4037                        let fs = &fs;
4038                        let query = &query;
4039                        let matching_paths_tx = &matching_paths_tx;
4040                        let paths_per_worker = (path_count + workers - 1) / workers;
4041                        let snapshots = &snapshots;
4042                        background
4043                            .scoped(|scope| {
4044                                for worker_ix in 0..workers {
4045                                    let worker_start_ix = worker_ix * paths_per_worker;
4046                                    let worker_end_ix = worker_start_ix + paths_per_worker;
4047                                    scope.spawn(async move {
4048                                        let mut snapshot_start_ix = 0;
4049                                        let mut abs_path = PathBuf::new();
4050                                        for snapshot in snapshots {
4051                                            let snapshot_end_ix =
4052                                                snapshot_start_ix + snapshot.visible_file_count();
4053                                            if worker_end_ix <= snapshot_start_ix {
4054                                                break;
4055                                            } else if worker_start_ix > snapshot_end_ix {
4056                                                snapshot_start_ix = snapshot_end_ix;
4057                                                continue;
4058                                            } else {
4059                                                let start_in_snapshot = worker_start_ix
4060                                                    .saturating_sub(snapshot_start_ix);
4061                                                let end_in_snapshot =
4062                                                    cmp::min(worker_end_ix, snapshot_end_ix)
4063                                                        - snapshot_start_ix;
4064
4065                                                for entry in snapshot
4066                                                    .files(false, start_in_snapshot)
4067                                                    .take(end_in_snapshot - start_in_snapshot)
4068                                                {
4069                                                    if matching_paths_tx.is_closed() {
4070                                                        break;
4071                                                    }
4072
4073                                                    abs_path.clear();
4074                                                    abs_path.push(&snapshot.abs_path());
4075                                                    abs_path.push(&entry.path);
4076                                                    let matches = if let Some(file) =
4077                                                        fs.open_sync(&abs_path).await.log_err()
4078                                                    {
4079                                                        query.detect(file).unwrap_or(false)
4080                                                    } else {
4081                                                        false
4082                                                    };
4083
4084                                                    if matches {
4085                                                        let project_path =
4086                                                            (snapshot.id(), entry.path.clone());
4087                                                        if matching_paths_tx
4088                                                            .send(project_path)
4089                                                            .await
4090                                                            .is_err()
4091                                                        {
4092                                                            break;
4093                                                        }
4094                                                    }
4095                                                }
4096
4097                                                snapshot_start_ix = snapshot_end_ix;
4098                                            }
4099                                        }
4100                                    });
4101                                }
4102                            })
4103                            .await;
4104                    }
4105                })
4106                .detach();
4107
4108            let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
4109            let open_buffers = self
4110                .opened_buffers
4111                .values()
4112                .filter_map(|b| b.upgrade(cx))
4113                .collect::<HashSet<_>>();
4114            cx.spawn(|this, cx| async move {
4115                for buffer in &open_buffers {
4116                    let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4117                    buffers_tx.send((buffer.clone(), snapshot)).await?;
4118                }
4119
4120                let open_buffers = Rc::new(RefCell::new(open_buffers));
4121                while let Some(project_path) = matching_paths_rx.next().await {
4122                    if buffers_tx.is_closed() {
4123                        break;
4124                    }
4125
4126                    let this = this.clone();
4127                    let open_buffers = open_buffers.clone();
4128                    let buffers_tx = buffers_tx.clone();
4129                    cx.spawn(|mut cx| async move {
4130                        if let Some(buffer) = this
4131                            .update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
4132                            .await
4133                            .log_err()
4134                        {
4135                            if open_buffers.borrow_mut().insert(buffer.clone()) {
4136                                let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
4137                                buffers_tx.send((buffer, snapshot)).await?;
4138                            }
4139                        }
4140
4141                        Ok::<_, anyhow::Error>(())
4142                    })
4143                    .detach();
4144                }
4145
4146                Ok::<_, anyhow::Error>(())
4147            })
4148            .detach_and_log_err(cx);
4149
4150            let background = cx.background().clone();
4151            cx.background().spawn(async move {
4152                let query = &query;
4153                let mut matched_buffers = Vec::new();
4154                for _ in 0..workers {
4155                    matched_buffers.push(HashMap::default());
4156                }
4157                background
4158                    .scoped(|scope| {
4159                        for worker_matched_buffers in matched_buffers.iter_mut() {
4160                            let mut buffers_rx = buffers_rx.clone();
4161                            scope.spawn(async move {
4162                                while let Some((buffer, snapshot)) = buffers_rx.next().await {
4163                                    let buffer_matches = query
4164                                        .search(snapshot.as_rope())
4165                                        .await
4166                                        .iter()
4167                                        .map(|range| {
4168                                            snapshot.anchor_before(range.start)
4169                                                ..snapshot.anchor_after(range.end)
4170                                        })
4171                                        .collect::<Vec<_>>();
4172                                    if !buffer_matches.is_empty() {
4173                                        worker_matched_buffers
4174                                            .insert(buffer.clone(), buffer_matches);
4175                                    }
4176                                }
4177                            });
4178                        }
4179                    })
4180                    .await;
4181                Ok(matched_buffers.into_iter().flatten().collect())
4182            })
4183        } else if let Some(project_id) = self.remote_id() {
4184            let request = self.client.request(query.to_proto(project_id));
4185            cx.spawn(|this, mut cx| async move {
4186                let response = request.await?;
4187                let mut result = HashMap::default();
4188                for location in response.locations {
4189                    let target_buffer = this
4190                        .update(&mut cx, |this, cx| {
4191                            this.wait_for_remote_buffer(location.buffer_id, cx)
4192                        })
4193                        .await?;
4194                    let start = location
4195                        .start
4196                        .and_then(deserialize_anchor)
4197                        .ok_or_else(|| anyhow!("missing target start"))?;
4198                    let end = location
4199                        .end
4200                        .and_then(deserialize_anchor)
4201                        .ok_or_else(|| anyhow!("missing target end"))?;
4202                    result
4203                        .entry(target_buffer)
4204                        .or_insert(Vec::new())
4205                        .push(start..end)
4206                }
4207                Ok(result)
4208            })
4209        } else {
4210            Task::ready(Ok(Default::default()))
4211        }
4212    }
4213
4214    fn request_lsp<R: LspCommand>(
4215        &self,
4216        buffer_handle: ModelHandle<Buffer>,
4217        request: R,
4218        cx: &mut ModelContext<Self>,
4219    ) -> Task<Result<R::Response>>
4220    where
4221        <R::LspRequest as lsp::request::Request>::Result: Send,
4222    {
4223        let buffer = buffer_handle.read(cx);
4224        if self.is_local() {
4225            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
4226            if let Some((file, language_server)) = file.zip(
4227                self.language_server_for_buffer(buffer, cx)
4228                    .map(|(_, server)| server.clone()),
4229            ) {
4230                let lsp_params = request.to_lsp(&file.abs_path(cx), cx);
4231                return cx.spawn(|this, cx| async move {
4232                    if !request.check_capabilities(language_server.capabilities()) {
4233                        return Ok(Default::default());
4234                    }
4235
4236                    let response = language_server
4237                        .request::<R::LspRequest>(lsp_params)
4238                        .await
4239                        .context("lsp request failed")?;
4240                    request
4241                        .response_from_lsp(response, this, buffer_handle, cx)
4242                        .await
4243                });
4244            }
4245        } else if let Some(project_id) = self.remote_id() {
4246            let rpc = self.client.clone();
4247            let message = request.to_proto(project_id, buffer);
4248            return cx.spawn_weak(|this, cx| async move {
4249                let response = rpc.request(message).await?;
4250                let this = this
4251                    .upgrade(&cx)
4252                    .ok_or_else(|| anyhow!("project dropped"))?;
4253                if this.read_with(&cx, |this, _| this.is_read_only()) {
4254                    Err(anyhow!("disconnected before completing request"))
4255                } else {
4256                    request
4257                        .response_from_proto(response, this, buffer_handle, cx)
4258                        .await
4259                }
4260            });
4261        }
4262        Task::ready(Ok(Default::default()))
4263    }
4264
4265    pub fn find_or_create_local_worktree(
4266        &mut self,
4267        abs_path: impl AsRef<Path>,
4268        visible: bool,
4269        cx: &mut ModelContext<Self>,
4270    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
4271        let abs_path = abs_path.as_ref();
4272        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
4273            Task::ready(Ok((tree, relative_path)))
4274        } else {
4275            let worktree = self.create_local_worktree(abs_path, visible, cx);
4276            cx.foreground()
4277                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
4278        }
4279    }
4280
4281    pub fn find_local_worktree(
4282        &self,
4283        abs_path: &Path,
4284        cx: &AppContext,
4285    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
4286        for tree in &self.worktrees {
4287            if let Some(tree) = tree.upgrade(cx) {
4288                if let Some(relative_path) = tree
4289                    .read(cx)
4290                    .as_local()
4291                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
4292                {
4293                    return Some((tree.clone(), relative_path.into()));
4294                }
4295            }
4296        }
4297        None
4298    }
4299
4300    pub fn is_shared(&self) -> bool {
4301        match &self.client_state {
4302            Some(ProjectClientState::Local { .. }) => true,
4303            _ => false,
4304        }
4305    }
4306
4307    fn create_local_worktree(
4308        &mut self,
4309        abs_path: impl AsRef<Path>,
4310        visible: bool,
4311        cx: &mut ModelContext<Self>,
4312    ) -> Task<Result<ModelHandle<Worktree>>> {
4313        let fs = self.fs.clone();
4314        let client = self.client.clone();
4315        let next_entry_id = self.next_entry_id.clone();
4316        let path: Arc<Path> = abs_path.as_ref().into();
4317        let task = self
4318            .loading_local_worktrees
4319            .entry(path.clone())
4320            .or_insert_with(|| {
4321                cx.spawn(|project, mut cx| {
4322                    async move {
4323                        let worktree = Worktree::local(
4324                            client.clone(),
4325                            path.clone(),
4326                            visible,
4327                            fs,
4328                            next_entry_id,
4329                            &mut cx,
4330                        )
4331                        .await;
4332                        project.update(&mut cx, |project, _| {
4333                            project.loading_local_worktrees.remove(&path);
4334                        });
4335                        let worktree = worktree?;
4336
4337                        project
4338                            .update(&mut cx, |project, cx| project.add_worktree(&worktree, cx))
4339                            .await;
4340
4341                        Ok(worktree)
4342                    }
4343                    .map_err(Arc::new)
4344                })
4345                .shared()
4346            })
4347            .clone();
4348        cx.foreground().spawn(async move {
4349            match task.await {
4350                Ok(worktree) => Ok(worktree),
4351                Err(err) => Err(anyhow!("{}", err)),
4352            }
4353        })
4354    }
4355
4356    pub fn remove_worktree(
4357        &mut self,
4358        id_to_remove: WorktreeId,
4359        cx: &mut ModelContext<Self>,
4360    ) -> impl Future<Output = ()> {
4361        self.worktrees.retain(|worktree| {
4362            if let Some(worktree) = worktree.upgrade(cx) {
4363                let id = worktree.read(cx).id();
4364                if id == id_to_remove {
4365                    cx.emit(Event::WorktreeRemoved(id));
4366                    false
4367                } else {
4368                    true
4369                }
4370            } else {
4371                false
4372            }
4373        });
4374        self.metadata_changed(cx)
4375    }
4376
4377    fn add_worktree(
4378        &mut self,
4379        worktree: &ModelHandle<Worktree>,
4380        cx: &mut ModelContext<Self>,
4381    ) -> impl Future<Output = ()> {
4382        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
4383        if worktree.read(cx).is_local() {
4384            cx.subscribe(worktree, |this, worktree, event, cx| match event {
4385                worktree::Event::UpdatedEntries => this.update_local_worktree_buffers(worktree, cx),
4386                worktree::Event::UpdatedGitRepositories(updated_repos) => {
4387                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
4388                }
4389            })
4390            .detach();
4391        }
4392
4393        let push_strong_handle = {
4394            let worktree = worktree.read(cx);
4395            self.is_shared() || worktree.is_visible() || worktree.is_remote()
4396        };
4397        if push_strong_handle {
4398            self.worktrees
4399                .push(WorktreeHandle::Strong(worktree.clone()));
4400        } else {
4401            self.worktrees
4402                .push(WorktreeHandle::Weak(worktree.downgrade()));
4403        }
4404
4405        cx.observe_release(worktree, |this, worktree, cx| {
4406            let _ = this.remove_worktree(worktree.id(), cx);
4407        })
4408        .detach();
4409
4410        cx.emit(Event::WorktreeAdded);
4411        self.metadata_changed(cx)
4412    }
4413
4414    fn update_local_worktree_buffers(
4415        &mut self,
4416        worktree_handle: ModelHandle<Worktree>,
4417        cx: &mut ModelContext<Self>,
4418    ) {
4419        let snapshot = worktree_handle.read(cx).snapshot();
4420        let mut buffers_to_delete = Vec::new();
4421        let mut renamed_buffers = Vec::new();
4422        for (buffer_id, buffer) in &self.opened_buffers {
4423            if let Some(buffer) = buffer.upgrade(cx) {
4424                buffer.update(cx, |buffer, cx| {
4425                    if let Some(old_file) = File::from_dyn(buffer.file()) {
4426                        if old_file.worktree != worktree_handle {
4427                            return;
4428                        }
4429
4430                        let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id)
4431                        {
4432                            File {
4433                                is_local: true,
4434                                entry_id: entry.id,
4435                                mtime: entry.mtime,
4436                                path: entry.path.clone(),
4437                                worktree: worktree_handle.clone(),
4438                                is_deleted: false,
4439                            }
4440                        } else if let Some(entry) =
4441                            snapshot.entry_for_path(old_file.path().as_ref())
4442                        {
4443                            File {
4444                                is_local: true,
4445                                entry_id: entry.id,
4446                                mtime: entry.mtime,
4447                                path: entry.path.clone(),
4448                                worktree: worktree_handle.clone(),
4449                                is_deleted: false,
4450                            }
4451                        } else {
4452                            File {
4453                                is_local: true,
4454                                entry_id: old_file.entry_id,
4455                                path: old_file.path().clone(),
4456                                mtime: old_file.mtime(),
4457                                worktree: worktree_handle.clone(),
4458                                is_deleted: true,
4459                            }
4460                        };
4461
4462                        let old_path = old_file.abs_path(cx);
4463                        if new_file.abs_path(cx) != old_path {
4464                            renamed_buffers.push((cx.handle(), old_path));
4465                        }
4466
4467                        if let Some(project_id) = self.remote_id() {
4468                            self.client
4469                                .send(proto::UpdateBufferFile {
4470                                    project_id,
4471                                    buffer_id: *buffer_id as u64,
4472                                    file: Some(new_file.to_proto()),
4473                                })
4474                                .log_err();
4475                        }
4476                        buffer.file_updated(Arc::new(new_file), cx).detach();
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            buffer.update(&mut cx, |buffer, cx| buffer.save(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, None, 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}