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