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