project.rs

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