project.rs

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