project.rs

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