project.rs

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