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