project.rs

   1pub mod buffer_store;
   2mod color_extractor;
   3pub mod connection_manager;
   4pub mod debounced_delay;
   5pub mod debugger;
   6pub mod git_store;
   7pub mod image_store;
   8pub mod lsp_command;
   9pub mod lsp_store;
  10mod manifest_tree;
  11pub mod prettier_store;
  12pub mod project_settings;
  13pub mod search;
  14mod task_inventory;
  15pub mod task_store;
  16pub mod terminals;
  17pub mod toolchain_store;
  18pub mod worktree_store;
  19
  20#[cfg(test)]
  21mod project_tests;
  22
  23mod direnv;
  24mod environment;
  25use buffer_diff::BufferDiff;
  26pub use environment::{EnvironmentErrorMessage, ProjectEnvironmentEvent};
  27use git_store::{Repository, RepositoryId};
  28pub mod search_history;
  29mod yarn;
  30
  31use crate::git_store::GitStore;
  32pub use git_store::{
  33    ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate,
  34    git_traversal::{ChildEntriesGitIter, GitEntry, GitEntryRef, GitTraversal},
  35};
  36
  37use anyhow::{Context as _, Result, anyhow};
  38use buffer_store::{BufferStore, BufferStoreEvent};
  39use client::{
  40    Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore, proto,
  41};
  42use clock::ReplicaId;
  43
  44use dap::client::DebugAdapterClient;
  45
  46use collections::{BTreeSet, HashMap, HashSet};
  47use debounced_delay::DebouncedDelay;
  48use debugger::{
  49    breakpoint_store::BreakpointStore,
  50    dap_store::{DapStore, DapStoreEvent},
  51};
  52pub use environment::ProjectEnvironment;
  53#[cfg(test)]
  54use futures::future::join_all;
  55use futures::{
  56    StreamExt,
  57    channel::mpsc::{self, UnboundedReceiver},
  58    future::try_join_all,
  59};
  60pub use image_store::{ImageItem, ImageStore};
  61use image_store::{ImageItemEvent, ImageStoreEvent};
  62
  63use ::git::{blame::Blame, status::FileStatus};
  64use gpui::{
  65    AnyEntity, App, AppContext, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter, Hsla,
  66    SharedString, Task, WeakEntity, Window,
  67};
  68use itertools::Itertools;
  69use language::{
  70    Buffer, BufferEvent, Capability, CodeLabel, Language, LanguageName, LanguageRegistry,
  71    PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainList, Transaction, Unclipped,
  72    language_settings::InlayHintKind, proto::split_operations,
  73};
  74use lsp::{
  75    CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, InsertTextMode,
  76    LanguageServerId, LanguageServerName, MessageActionItem,
  77};
  78use lsp_command::*;
  79use lsp_store::{CompletionDocumentation, LspFormatTarget, OpenLspBufferHandle};
  80pub use manifest_tree::ManifestProviders;
  81use node_runtime::NodeRuntime;
  82use parking_lot::Mutex;
  83pub use prettier_store::PrettierStore;
  84use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
  85use remote::{SshConnectionOptions, SshRemoteClient};
  86use rpc::{
  87    AnyProtoClient, ErrorCode,
  88    proto::{FromProto, LanguageServerPromptResponse, SSH_PROJECT_ID, ToProto},
  89};
  90use search::{SearchInputKind, SearchQuery, SearchResult};
  91use search_history::SearchHistory;
  92use settings::{InvalidSettingsError, Settings, SettingsLocation, SettingsStore};
  93use smol::channel::Receiver;
  94use snippet::Snippet;
  95use snippet_provider::SnippetProvider;
  96use std::{
  97    borrow::Cow,
  98    ops::Range,
  99    path::{Component, Path, PathBuf},
 100    pin::pin,
 101    str,
 102    sync::Arc,
 103    time::Duration,
 104};
 105
 106use task_store::TaskStore;
 107use terminals::Terminals;
 108use text::{Anchor, BufferId};
 109use toolchain_store::EmptyToolchainStore;
 110use util::{
 111    ResultExt as _,
 112    paths::{SanitizedPath, compare_paths},
 113};
 114use worktree::{CreatedEntry, Snapshot, Traversal};
 115pub use worktree::{
 116    Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
 117    UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
 118};
 119use worktree_store::{WorktreeStore, WorktreeStoreEvent};
 120
 121pub use fs::*;
 122pub use language::Location;
 123#[cfg(any(test, feature = "test-support"))]
 124pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
 125pub use task_inventory::{
 126    BasicContextProvider, ContextProviderWithTasks, Inventory, TaskContexts, TaskSourceKind,
 127};
 128
 129pub use buffer_store::ProjectTransaction;
 130pub use lsp_store::{
 131    DiagnosticSummary, LanguageServerLogType, LanguageServerProgress, LanguageServerPromptRequest,
 132    LanguageServerStatus, LanguageServerToQuery, LspStore, LspStoreEvent,
 133    SERVER_PROGRESS_THROTTLE_TIMEOUT,
 134};
 135pub use toolchain_store::ToolchainStore;
 136const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
 137const MAX_SEARCH_RESULT_FILES: usize = 5_000;
 138const MAX_SEARCH_RESULT_RANGES: usize = 10_000;
 139
 140pub trait ProjectItem {
 141    fn try_open(
 142        project: &Entity<Project>,
 143        path: &ProjectPath,
 144        cx: &mut App,
 145    ) -> Option<Task<Result<Entity<Self>>>>
 146    where
 147        Self: Sized;
 148    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
 149    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 150    fn is_dirty(&self) -> bool;
 151}
 152
 153#[derive(Clone)]
 154pub enum OpenedBufferEvent {
 155    Disconnected,
 156    Ok(BufferId),
 157    Err(BufferId, Arc<anyhow::Error>),
 158}
 159
 160/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
 161/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
 162/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
 163///
 164/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
 165pub struct Project {
 166    active_entry: Option<ProjectEntryId>,
 167    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 168    languages: Arc<LanguageRegistry>,
 169    dap_store: Entity<DapStore>,
 170
 171    breakpoint_store: Entity<BreakpointStore>,
 172    client: Arc<client::Client>,
 173    join_project_response_message_id: u32,
 174    task_store: Entity<TaskStore>,
 175    user_store: Entity<UserStore>,
 176    fs: Arc<dyn Fs>,
 177    ssh_client: Option<Entity<SshRemoteClient>>,
 178    client_state: ProjectClientState,
 179    git_store: Entity<GitStore>,
 180    collaborators: HashMap<proto::PeerId, Collaborator>,
 181    client_subscriptions: Vec<client::Subscription>,
 182    worktree_store: Entity<WorktreeStore>,
 183    buffer_store: Entity<BufferStore>,
 184    image_store: Entity<ImageStore>,
 185    lsp_store: Entity<LspStore>,
 186    _subscriptions: Vec<gpui::Subscription>,
 187    buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
 188    git_diff_debouncer: DebouncedDelay<Self>,
 189    remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
 190    terminals: Terminals,
 191    node: Option<NodeRuntime>,
 192    search_history: SearchHistory,
 193    search_included_history: SearchHistory,
 194    search_excluded_history: SearchHistory,
 195    snippets: Entity<SnippetProvider>,
 196    environment: Entity<ProjectEnvironment>,
 197    settings_observer: Entity<SettingsObserver>,
 198    toolchain_store: Option<Entity<ToolchainStore>>,
 199}
 200
 201#[derive(Default)]
 202struct RemotelyCreatedModels {
 203    worktrees: Vec<Entity<Worktree>>,
 204    buffers: Vec<Entity<Buffer>>,
 205    retain_count: usize,
 206}
 207
 208struct RemotelyCreatedModelGuard {
 209    remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
 210}
 211
 212impl Drop for RemotelyCreatedModelGuard {
 213    fn drop(&mut self) {
 214        if let Some(remote_models) = self.remote_models.upgrade() {
 215            let mut remote_models = remote_models.lock();
 216            assert!(
 217                remote_models.retain_count > 0,
 218                "RemotelyCreatedModelGuard dropped too many times"
 219            );
 220            remote_models.retain_count -= 1;
 221            if remote_models.retain_count == 0 {
 222                remote_models.buffers.clear();
 223                remote_models.worktrees.clear();
 224            }
 225        }
 226    }
 227}
 228/// Message ordered with respect to buffer operations
 229#[derive(Debug)]
 230enum BufferOrderedMessage {
 231    Operation {
 232        buffer_id: BufferId,
 233        operation: proto::Operation,
 234    },
 235    LanguageServerUpdate {
 236        language_server_id: LanguageServerId,
 237        message: proto::update_language_server::Variant,
 238    },
 239    Resync,
 240}
 241
 242#[derive(Debug)]
 243enum ProjectClientState {
 244    /// Single-player mode.
 245    Local,
 246    /// Multi-player mode but still a local project.
 247    Shared { remote_id: u64 },
 248    /// Multi-player mode but working on a remote project.
 249    Remote {
 250        sharing_has_stopped: bool,
 251        capability: Capability,
 252        remote_id: u64,
 253        replica_id: ReplicaId,
 254    },
 255}
 256
 257#[derive(Clone, Debug, PartialEq)]
 258pub enum Event {
 259    LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
 260    LanguageServerRemoved(LanguageServerId),
 261    LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
 262    Toast {
 263        notification_id: SharedString,
 264        message: String,
 265    },
 266    HideToast {
 267        notification_id: SharedString,
 268    },
 269    LanguageServerPrompt(LanguageServerPromptRequest),
 270    LanguageNotFound(Entity<Buffer>),
 271    ActiveEntryChanged(Option<ProjectEntryId>),
 272    ActivateProjectPanel,
 273    WorktreeAdded(WorktreeId),
 274    WorktreeOrderChanged,
 275    WorktreeRemoved(WorktreeId),
 276    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 277    DiskBasedDiagnosticsStarted {
 278        language_server_id: LanguageServerId,
 279    },
 280    DiskBasedDiagnosticsFinished {
 281        language_server_id: LanguageServerId,
 282    },
 283    DiagnosticsUpdated {
 284        path: ProjectPath,
 285        language_server_id: LanguageServerId,
 286    },
 287    RemoteIdChanged(Option<u64>),
 288    DisconnectedFromHost,
 289    DisconnectedFromSshRemote,
 290    Closed,
 291    DeletedEntry(WorktreeId, ProjectEntryId),
 292    CollaboratorUpdated {
 293        old_peer_id: proto::PeerId,
 294        new_peer_id: proto::PeerId,
 295    },
 296    CollaboratorJoined(proto::PeerId),
 297    CollaboratorLeft(proto::PeerId),
 298    HostReshared,
 299    Reshared,
 300    Rejoined,
 301    RefreshInlayHints,
 302    RefreshCodeLens,
 303    RevealInProjectPanel(ProjectEntryId),
 304    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
 305    ExpandedAllForEntry(WorktreeId, ProjectEntryId),
 306}
 307
 308pub enum DebugAdapterClientState {
 309    Starting(Task<Option<Arc<DebugAdapterClient>>>),
 310    Running(Arc<DebugAdapterClient>),
 311}
 312
 313#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 314pub struct ProjectPath {
 315    pub worktree_id: WorktreeId,
 316    pub path: Arc<Path>,
 317}
 318
 319impl ProjectPath {
 320    pub fn from_proto(p: proto::ProjectPath) -> Self {
 321        Self {
 322            worktree_id: WorktreeId::from_proto(p.worktree_id),
 323            path: Arc::<Path>::from_proto(p.path),
 324        }
 325    }
 326
 327    pub fn to_proto(&self) -> proto::ProjectPath {
 328        proto::ProjectPath {
 329            worktree_id: self.worktree_id.to_proto(),
 330            path: self.path.as_ref().to_proto(),
 331        }
 332    }
 333
 334    pub fn root_path(worktree_id: WorktreeId) -> Self {
 335        Self {
 336            worktree_id,
 337            path: Path::new("").into(),
 338        }
 339    }
 340
 341    pub fn starts_with(&self, other: &ProjectPath) -> bool {
 342        self.worktree_id == other.worktree_id && self.path.starts_with(&other.path)
 343    }
 344}
 345
 346#[derive(Debug, Default)]
 347pub enum PrepareRenameResponse {
 348    Success(Range<Anchor>),
 349    OnlyUnpreparedRenameSupported,
 350    #[default]
 351    InvalidPosition,
 352}
 353
 354#[derive(Debug, Clone, PartialEq, Eq)]
 355pub struct InlayHint {
 356    pub position: language::Anchor,
 357    pub label: InlayHintLabel,
 358    pub kind: Option<InlayHintKind>,
 359    pub padding_left: bool,
 360    pub padding_right: bool,
 361    pub tooltip: Option<InlayHintTooltip>,
 362    pub resolve_state: ResolveState,
 363}
 364
 365/// The user's intent behind a given completion confirmation
 366#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
 367pub enum CompletionIntent {
 368    /// The user intends to 'commit' this result, if possible
 369    /// completion confirmations should run side effects.
 370    ///
 371    /// For LSP completions, will respect the setting `completions.lsp_insert_mode`.
 372    Complete,
 373    /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `insert`.
 374    CompleteWithInsert,
 375    /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `replace`.
 376    CompleteWithReplace,
 377    /// The user intends to continue 'composing' this completion
 378    /// completion confirmations should not run side effects and
 379    /// let the user continue composing their action
 380    Compose,
 381}
 382
 383impl CompletionIntent {
 384    pub fn is_complete(&self) -> bool {
 385        self == &Self::Complete
 386    }
 387
 388    pub fn is_compose(&self) -> bool {
 389        self == &Self::Compose
 390    }
 391}
 392
 393/// Similar to `CoreCompletion`, but with extra metadata attached.
 394#[derive(Clone)]
 395pub struct Completion {
 396    /// The range of text that will be replaced by this completion.
 397    pub replace_range: Range<Anchor>,
 398    /// The new text that will be inserted.
 399    pub new_text: String,
 400    /// A label for this completion that is shown in the menu.
 401    pub label: CodeLabel,
 402    /// The documentation for this completion.
 403    pub documentation: Option<CompletionDocumentation>,
 404    /// Completion data source which it was constructed from.
 405    pub source: CompletionSource,
 406    /// A path to an icon for this completion that is shown in the menu.
 407    pub icon_path: Option<SharedString>,
 408    /// Whether to adjust indentation (the default) or not.
 409    pub insert_text_mode: Option<InsertTextMode>,
 410    /// An optional callback to invoke when this completion is confirmed.
 411    /// Returns, whether new completions should be retriggered after the current one.
 412    /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
 413    /// if no confirmation is provided or `false` is returned, the completion will be committed.
 414    pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
 415}
 416
 417#[derive(Debug, Clone)]
 418pub enum CompletionSource {
 419    Lsp {
 420        /// The alternate `insert` range, if provided by the LSP server.
 421        insert_range: Option<Range<Anchor>>,
 422        /// The id of the language server that produced this completion.
 423        server_id: LanguageServerId,
 424        /// The raw completion provided by the language server.
 425        lsp_completion: Box<lsp::CompletionItem>,
 426        /// A set of defaults for this completion item.
 427        lsp_defaults: Option<Arc<lsp::CompletionListItemDefaults>>,
 428        /// Whether this completion has been resolved, to ensure it happens once per completion.
 429        resolved: bool,
 430    },
 431    Custom,
 432    BufferWord {
 433        word_range: Range<Anchor>,
 434        resolved: bool,
 435    },
 436}
 437
 438impl CompletionSource {
 439    pub fn server_id(&self) -> Option<LanguageServerId> {
 440        if let CompletionSource::Lsp { server_id, .. } = self {
 441            Some(*server_id)
 442        } else {
 443            None
 444        }
 445    }
 446
 447    pub fn lsp_completion(&self, apply_defaults: bool) -> Option<Cow<lsp::CompletionItem>> {
 448        if let Self::Lsp {
 449            lsp_completion,
 450            lsp_defaults,
 451            ..
 452        } = self
 453        {
 454            if apply_defaults {
 455                if let Some(lsp_defaults) = lsp_defaults {
 456                    let mut completion_with_defaults = *lsp_completion.clone();
 457                    let default_commit_characters = lsp_defaults.commit_characters.as_ref();
 458                    let default_edit_range = lsp_defaults.edit_range.as_ref();
 459                    let default_insert_text_format = lsp_defaults.insert_text_format.as_ref();
 460                    let default_insert_text_mode = lsp_defaults.insert_text_mode.as_ref();
 461
 462                    if default_commit_characters.is_some()
 463                        || default_edit_range.is_some()
 464                        || default_insert_text_format.is_some()
 465                        || default_insert_text_mode.is_some()
 466                    {
 467                        if completion_with_defaults.commit_characters.is_none()
 468                            && default_commit_characters.is_some()
 469                        {
 470                            completion_with_defaults.commit_characters =
 471                                default_commit_characters.cloned()
 472                        }
 473                        if completion_with_defaults.text_edit.is_none() {
 474                            match default_edit_range {
 475                                Some(lsp::CompletionListItemDefaultsEditRange::Range(range)) => {
 476                                    completion_with_defaults.text_edit =
 477                                        Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
 478                                            range: *range,
 479                                            new_text: completion_with_defaults.label.clone(),
 480                                        }))
 481                                }
 482                                Some(
 483                                    lsp::CompletionListItemDefaultsEditRange::InsertAndReplace {
 484                                        insert,
 485                                        replace,
 486                                    },
 487                                ) => {
 488                                    completion_with_defaults.text_edit =
 489                                        Some(lsp::CompletionTextEdit::InsertAndReplace(
 490                                            lsp::InsertReplaceEdit {
 491                                                new_text: completion_with_defaults.label.clone(),
 492                                                insert: *insert,
 493                                                replace: *replace,
 494                                            },
 495                                        ))
 496                                }
 497                                None => {}
 498                            }
 499                        }
 500                        if completion_with_defaults.insert_text_format.is_none()
 501                            && default_insert_text_format.is_some()
 502                        {
 503                            completion_with_defaults.insert_text_format =
 504                                default_insert_text_format.cloned()
 505                        }
 506                        if completion_with_defaults.insert_text_mode.is_none()
 507                            && default_insert_text_mode.is_some()
 508                        {
 509                            completion_with_defaults.insert_text_mode =
 510                                default_insert_text_mode.cloned()
 511                        }
 512                    }
 513                    return Some(Cow::Owned(completion_with_defaults));
 514                }
 515            }
 516            Some(Cow::Borrowed(lsp_completion))
 517        } else {
 518            None
 519        }
 520    }
 521}
 522
 523impl std::fmt::Debug for Completion {
 524    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 525        f.debug_struct("Completion")
 526            .field("replace_range", &self.replace_range)
 527            .field("new_text", &self.new_text)
 528            .field("label", &self.label)
 529            .field("documentation", &self.documentation)
 530            .field("source", &self.source)
 531            .finish()
 532    }
 533}
 534
 535/// A generic completion that can come from different sources.
 536#[derive(Clone, Debug)]
 537pub(crate) struct CoreCompletion {
 538    replace_range: Range<Anchor>,
 539    new_text: String,
 540    source: CompletionSource,
 541}
 542
 543/// A code action provided by a language server.
 544#[derive(Clone, Debug)]
 545pub struct CodeAction {
 546    /// The id of the language server that produced this code action.
 547    pub server_id: LanguageServerId,
 548    /// The range of the buffer where this code action is applicable.
 549    pub range: Range<Anchor>,
 550    /// The raw code action provided by the language server.
 551    /// Can be either an action or a command.
 552    pub lsp_action: LspAction,
 553    /// Whether the action needs to be resolved using the language server.
 554    pub resolved: bool,
 555}
 556
 557/// An action sent back by a language server.
 558#[derive(Clone, Debug)]
 559pub enum LspAction {
 560    /// An action with the full data, may have a command or may not.
 561    /// May require resolving.
 562    Action(Box<lsp::CodeAction>),
 563    /// A command data to run as an action.
 564    Command(lsp::Command),
 565    /// A code lens data to run as an action.
 566    CodeLens(lsp::CodeLens),
 567}
 568
 569impl LspAction {
 570    pub fn title(&self) -> &str {
 571        match self {
 572            Self::Action(action) => &action.title,
 573            Self::Command(command) => &command.title,
 574            Self::CodeLens(lens) => lens
 575                .command
 576                .as_ref()
 577                .map(|command| command.title.as_str())
 578                .unwrap_or("Unknown command"),
 579        }
 580    }
 581
 582    fn action_kind(&self) -> Option<lsp::CodeActionKind> {
 583        match self {
 584            Self::Action(action) => action.kind.clone(),
 585            Self::Command(_) => Some(lsp::CodeActionKind::new("command")),
 586            Self::CodeLens(_) => Some(lsp::CodeActionKind::new("code lens")),
 587        }
 588    }
 589
 590    fn edit(&self) -> Option<&lsp::WorkspaceEdit> {
 591        match self {
 592            Self::Action(action) => action.edit.as_ref(),
 593            Self::Command(_) => None,
 594            Self::CodeLens(_) => None,
 595        }
 596    }
 597
 598    fn command(&self) -> Option<&lsp::Command> {
 599        match self {
 600            Self::Action(action) => action.command.as_ref(),
 601            Self::Command(command) => Some(command),
 602            Self::CodeLens(lens) => lens.command.as_ref(),
 603        }
 604    }
 605}
 606
 607#[derive(Debug, Clone, PartialEq, Eq)]
 608pub enum ResolveState {
 609    Resolved,
 610    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 611    Resolving,
 612}
 613
 614impl InlayHint {
 615    pub fn text(&self) -> String {
 616        match &self.label {
 617            InlayHintLabel::String(s) => s.to_owned(),
 618            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 619        }
 620    }
 621}
 622
 623#[derive(Debug, Clone, PartialEq, Eq)]
 624pub enum InlayHintLabel {
 625    String(String),
 626    LabelParts(Vec<InlayHintLabelPart>),
 627}
 628
 629#[derive(Debug, Clone, PartialEq, Eq)]
 630pub struct InlayHintLabelPart {
 631    pub value: String,
 632    pub tooltip: Option<InlayHintLabelPartTooltip>,
 633    pub location: Option<(LanguageServerId, lsp::Location)>,
 634}
 635
 636#[derive(Debug, Clone, PartialEq, Eq)]
 637pub enum InlayHintTooltip {
 638    String(String),
 639    MarkupContent(MarkupContent),
 640}
 641
 642#[derive(Debug, Clone, PartialEq, Eq)]
 643pub enum InlayHintLabelPartTooltip {
 644    String(String),
 645    MarkupContent(MarkupContent),
 646}
 647
 648#[derive(Debug, Clone, PartialEq, Eq)]
 649pub struct MarkupContent {
 650    pub kind: HoverBlockKind,
 651    pub value: String,
 652}
 653
 654#[derive(Debug, Clone)]
 655pub struct LocationLink {
 656    pub origin: Option<Location>,
 657    pub target: Location,
 658}
 659
 660#[derive(Debug)]
 661pub struct DocumentHighlight {
 662    pub range: Range<language::Anchor>,
 663    pub kind: DocumentHighlightKind,
 664}
 665
 666#[derive(Clone, Debug)]
 667pub struct Symbol {
 668    pub language_server_name: LanguageServerName,
 669    pub source_worktree_id: WorktreeId,
 670    pub source_language_server_id: LanguageServerId,
 671    pub path: ProjectPath,
 672    pub label: CodeLabel,
 673    pub name: String,
 674    pub kind: lsp::SymbolKind,
 675    pub range: Range<Unclipped<PointUtf16>>,
 676    pub signature: [u8; 32],
 677}
 678
 679#[derive(Clone, Debug)]
 680pub struct DocumentSymbol {
 681    pub name: String,
 682    pub kind: lsp::SymbolKind,
 683    pub range: Range<Unclipped<PointUtf16>>,
 684    pub selection_range: Range<Unclipped<PointUtf16>>,
 685    pub children: Vec<DocumentSymbol>,
 686}
 687
 688#[derive(Clone, Debug, PartialEq)]
 689pub struct HoverBlock {
 690    pub text: String,
 691    pub kind: HoverBlockKind,
 692}
 693
 694#[derive(Clone, Debug, PartialEq, Eq)]
 695pub enum HoverBlockKind {
 696    PlainText,
 697    Markdown,
 698    Code { language: String },
 699}
 700
 701#[derive(Debug, Clone)]
 702pub struct Hover {
 703    pub contents: Vec<HoverBlock>,
 704    pub range: Option<Range<language::Anchor>>,
 705    pub language: Option<Arc<Language>>,
 706}
 707
 708impl Hover {
 709    pub fn is_empty(&self) -> bool {
 710        self.contents.iter().all(|block| block.text.is_empty())
 711    }
 712}
 713
 714enum EntitySubscription {
 715    Project(PendingEntitySubscription<Project>),
 716    BufferStore(PendingEntitySubscription<BufferStore>),
 717    GitStore(PendingEntitySubscription<GitStore>),
 718    WorktreeStore(PendingEntitySubscription<WorktreeStore>),
 719    LspStore(PendingEntitySubscription<LspStore>),
 720    SettingsObserver(PendingEntitySubscription<SettingsObserver>),
 721    DapStore(PendingEntitySubscription<DapStore>),
 722}
 723
 724#[derive(Debug, Clone)]
 725pub struct DirectoryItem {
 726    pub path: PathBuf,
 727    pub is_dir: bool,
 728}
 729
 730#[derive(Clone)]
 731pub enum DirectoryLister {
 732    Project(Entity<Project>),
 733    Local(Arc<dyn Fs>),
 734}
 735
 736impl DirectoryLister {
 737    pub fn is_local(&self, cx: &App) -> bool {
 738        match self {
 739            DirectoryLister::Local(_) => true,
 740            DirectoryLister::Project(project) => project.read(cx).is_local(),
 741        }
 742    }
 743
 744    pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
 745        if self.is_local(cx) {
 746            shellexpand::tilde(path)
 747        } else {
 748            Cow::from(path)
 749        }
 750    }
 751
 752    pub fn default_query(&self, cx: &mut App) -> String {
 753        if let DirectoryLister::Project(project) = self {
 754            if let Some(worktree) = project.read(cx).visible_worktrees(cx).next() {
 755                return worktree.read(cx).abs_path().to_string_lossy().to_string();
 756            }
 757        };
 758        format!("~{}", std::path::MAIN_SEPARATOR_STR)
 759    }
 760
 761    pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<DirectoryItem>>> {
 762        match self {
 763            DirectoryLister::Project(project) => {
 764                project.update(cx, |project, cx| project.list_directory(path, cx))
 765            }
 766            DirectoryLister::Local(fs) => {
 767                let fs = fs.clone();
 768                cx.background_spawn(async move {
 769                    let mut results = vec![];
 770                    let expanded = shellexpand::tilde(&path);
 771                    let query = Path::new(expanded.as_ref());
 772                    let mut response = fs.read_dir(query).await?;
 773                    while let Some(path) = response.next().await {
 774                        let path = path?;
 775                        if let Some(file_name) = path.file_name() {
 776                            results.push(DirectoryItem {
 777                                path: PathBuf::from(file_name.to_os_string()),
 778                                is_dir: fs.is_dir(&path).await,
 779                            });
 780                        }
 781                    }
 782                    Ok(results)
 783                })
 784            }
 785        }
 786    }
 787}
 788
 789#[cfg(any(test, feature = "test-support"))]
 790pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
 791    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
 792    trigger_character: None,
 793};
 794
 795impl Project {
 796    pub fn init_settings(cx: &mut App) {
 797        WorktreeSettings::register(cx);
 798        ProjectSettings::register(cx);
 799    }
 800
 801    pub fn init(client: &Arc<Client>, cx: &mut App) {
 802        connection_manager::init(client.clone(), cx);
 803        Self::init_settings(cx);
 804
 805        let client: AnyProtoClient = client.clone().into();
 806        client.add_entity_message_handler(Self::handle_add_collaborator);
 807        client.add_entity_message_handler(Self::handle_update_project_collaborator);
 808        client.add_entity_message_handler(Self::handle_remove_collaborator);
 809        client.add_entity_message_handler(Self::handle_update_project);
 810        client.add_entity_message_handler(Self::handle_unshare_project);
 811        client.add_entity_request_handler(Self::handle_update_buffer);
 812        client.add_entity_message_handler(Self::handle_update_worktree);
 813        client.add_entity_request_handler(Self::handle_synchronize_buffers);
 814
 815        client.add_entity_request_handler(Self::handle_search_candidate_buffers);
 816        client.add_entity_request_handler(Self::handle_open_buffer_by_id);
 817        client.add_entity_request_handler(Self::handle_open_buffer_by_path);
 818        client.add_entity_request_handler(Self::handle_open_new_buffer);
 819        client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
 820
 821        WorktreeStore::init(&client);
 822        BufferStore::init(&client);
 823        LspStore::init(&client);
 824        GitStore::init(&client);
 825        SettingsObserver::init(&client);
 826        TaskStore::init(Some(&client));
 827        ToolchainStore::init(&client);
 828        DapStore::init(&client);
 829        BreakpointStore::init(&client);
 830    }
 831
 832    pub fn local(
 833        client: Arc<Client>,
 834        node: NodeRuntime,
 835        user_store: Entity<UserStore>,
 836        languages: Arc<LanguageRegistry>,
 837        fs: Arc<dyn Fs>,
 838        env: Option<HashMap<String, String>>,
 839        cx: &mut App,
 840    ) -> Entity<Self> {
 841        cx.new(|cx: &mut Context<Self>| {
 842            let (tx, rx) = mpsc::unbounded();
 843            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
 844                .detach();
 845            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
 846            let worktree_store = cx.new(|_| WorktreeStore::local(false, fs.clone()));
 847            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
 848                .detach();
 849
 850            let environment = cx.new(|_| ProjectEnvironment::new(env));
 851            let toolchain_store = cx.new(|cx| {
 852                ToolchainStore::local(
 853                    languages.clone(),
 854                    worktree_store.clone(),
 855                    environment.clone(),
 856                    cx,
 857                )
 858            });
 859
 860            let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
 861            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
 862                .detach();
 863
 864            let breakpoint_store =
 865                cx.new(|_| BreakpointStore::local(worktree_store.clone(), buffer_store.clone()));
 866
 867            let dap_store = cx.new(|cx| {
 868                DapStore::new_local(
 869                    client.http_client(),
 870                    node.clone(),
 871                    fs.clone(),
 872                    languages.clone(),
 873                    environment.clone(),
 874                    toolchain_store.read(cx).as_language_toolchain_store(),
 875                    worktree_store.clone(),
 876                    breakpoint_store.clone(),
 877                    cx,
 878                )
 879            });
 880            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
 881
 882            let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
 883            cx.subscribe(&image_store, Self::on_image_store_event)
 884                .detach();
 885
 886            let prettier_store = cx.new(|cx| {
 887                PrettierStore::new(
 888                    node.clone(),
 889                    fs.clone(),
 890                    languages.clone(),
 891                    worktree_store.clone(),
 892                    cx,
 893                )
 894            });
 895
 896            let task_store = cx.new(|cx| {
 897                TaskStore::local(
 898                    buffer_store.downgrade(),
 899                    worktree_store.clone(),
 900                    toolchain_store.read(cx).as_language_toolchain_store(),
 901                    environment.clone(),
 902                    cx,
 903                )
 904            });
 905
 906            let settings_observer = cx.new(|cx| {
 907                SettingsObserver::new_local(
 908                    fs.clone(),
 909                    worktree_store.clone(),
 910                    task_store.clone(),
 911                    cx,
 912                )
 913            });
 914            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
 915                .detach();
 916
 917            let lsp_store = cx.new(|cx| {
 918                LspStore::new_local(
 919                    buffer_store.clone(),
 920                    worktree_store.clone(),
 921                    prettier_store.clone(),
 922                    toolchain_store.clone(),
 923                    environment.clone(),
 924                    languages.clone(),
 925                    client.http_client(),
 926                    fs.clone(),
 927                    cx,
 928                )
 929            });
 930
 931            let git_store = cx.new(|cx| {
 932                GitStore::local(
 933                    &worktree_store,
 934                    buffer_store.clone(),
 935                    environment.clone(),
 936                    fs.clone(),
 937                    cx,
 938                )
 939            });
 940
 941            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 942
 943            Self {
 944                buffer_ordered_messages_tx: tx,
 945                collaborators: Default::default(),
 946                worktree_store,
 947                buffer_store,
 948                image_store,
 949                lsp_store,
 950                join_project_response_message_id: 0,
 951                client_state: ProjectClientState::Local,
 952                git_store,
 953                client_subscriptions: Vec::new(),
 954                _subscriptions: vec![cx.on_release(Self::release)],
 955                active_entry: None,
 956                snippets,
 957                languages,
 958                client,
 959                task_store,
 960                user_store,
 961                settings_observer,
 962                fs,
 963                ssh_client: None,
 964                breakpoint_store,
 965                dap_store,
 966
 967                buffers_needing_diff: Default::default(),
 968                git_diff_debouncer: DebouncedDelay::new(),
 969                terminals: Terminals {
 970                    local_handles: Vec::new(),
 971                },
 972                node: Some(node),
 973                search_history: Self::new_search_history(),
 974                environment,
 975                remotely_created_models: Default::default(),
 976
 977                search_included_history: Self::new_search_history(),
 978                search_excluded_history: Self::new_search_history(),
 979
 980                toolchain_store: Some(toolchain_store),
 981            }
 982        })
 983    }
 984
 985    pub fn ssh(
 986        ssh: Entity<SshRemoteClient>,
 987        client: Arc<Client>,
 988        node: NodeRuntime,
 989        user_store: Entity<UserStore>,
 990        languages: Arc<LanguageRegistry>,
 991        fs: Arc<dyn Fs>,
 992        cx: &mut App,
 993    ) -> Entity<Self> {
 994        cx.new(|cx: &mut Context<Self>| {
 995            let (tx, rx) = mpsc::unbounded();
 996            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
 997                .detach();
 998            let global_snippets_dir = paths::config_dir().join("snippets");
 999            let snippets =
1000                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
1001
1002            let ssh_proto = ssh.read(cx).proto_client();
1003            let worktree_store =
1004                cx.new(|_| WorktreeStore::remote(false, ssh_proto.clone(), SSH_PROJECT_ID));
1005            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1006                .detach();
1007
1008            let buffer_store = cx.new(|cx| {
1009                BufferStore::remote(
1010                    worktree_store.clone(),
1011                    ssh.read(cx).proto_client(),
1012                    SSH_PROJECT_ID,
1013                    cx,
1014                )
1015            });
1016            let image_store = cx.new(|cx| {
1017                ImageStore::remote(
1018                    worktree_store.clone(),
1019                    ssh.read(cx).proto_client(),
1020                    SSH_PROJECT_ID,
1021                    cx,
1022                )
1023            });
1024            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1025                .detach();
1026            let toolchain_store = cx
1027                .new(|cx| ToolchainStore::remote(SSH_PROJECT_ID, ssh.read(cx).proto_client(), cx));
1028            let task_store = cx.new(|cx| {
1029                TaskStore::remote(
1030                    buffer_store.downgrade(),
1031                    worktree_store.clone(),
1032                    toolchain_store.read(cx).as_language_toolchain_store(),
1033                    ssh.read(cx).proto_client(),
1034                    SSH_PROJECT_ID,
1035                    cx,
1036                )
1037            });
1038
1039            let settings_observer = cx.new(|cx| {
1040                SettingsObserver::new_remote(
1041                    fs.clone(),
1042                    worktree_store.clone(),
1043                    task_store.clone(),
1044                    cx,
1045                )
1046            });
1047            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1048                .detach();
1049
1050            let environment = cx.new(|_| ProjectEnvironment::new(None));
1051
1052            let lsp_store = cx.new(|cx| {
1053                LspStore::new_remote(
1054                    buffer_store.clone(),
1055                    worktree_store.clone(),
1056                    Some(toolchain_store.clone()),
1057                    languages.clone(),
1058                    ssh_proto.clone(),
1059                    SSH_PROJECT_ID,
1060                    fs.clone(),
1061                    cx,
1062                )
1063            });
1064            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1065
1066            let breakpoint_store =
1067                cx.new(|_| BreakpointStore::remote(SSH_PROJECT_ID, ssh_proto.clone()));
1068
1069            let dap_store = cx.new(|cx| {
1070                DapStore::new_ssh(
1071                    SSH_PROJECT_ID,
1072                    ssh.clone(),
1073                    breakpoint_store.clone(),
1074                    worktree_store.clone(),
1075                    cx,
1076                )
1077            });
1078
1079            let git_store = cx.new(|cx| {
1080                GitStore::ssh(&worktree_store, buffer_store.clone(), ssh_proto.clone(), cx)
1081            });
1082
1083            cx.subscribe(&ssh, Self::on_ssh_event).detach();
1084
1085            let this = Self {
1086                buffer_ordered_messages_tx: tx,
1087                collaborators: Default::default(),
1088                worktree_store,
1089                buffer_store,
1090                image_store,
1091                lsp_store,
1092                breakpoint_store,
1093                dap_store,
1094                join_project_response_message_id: 0,
1095                client_state: ProjectClientState::Local,
1096                git_store,
1097                client_subscriptions: Vec::new(),
1098                _subscriptions: vec![
1099                    cx.on_release(Self::release),
1100                    cx.on_app_quit(|this, cx| {
1101                        let shutdown = this.ssh_client.take().and_then(|client| {
1102                            client
1103                                .read(cx)
1104                                .shutdown_processes(Some(proto::ShutdownRemoteServer {}))
1105                        });
1106
1107                        cx.background_executor().spawn(async move {
1108                            if let Some(shutdown) = shutdown {
1109                                shutdown.await;
1110                            }
1111                        })
1112                    }),
1113                ],
1114                active_entry: None,
1115                snippets,
1116                languages,
1117                client,
1118                task_store,
1119                user_store,
1120                settings_observer,
1121                fs,
1122                ssh_client: Some(ssh.clone()),
1123                buffers_needing_diff: Default::default(),
1124                git_diff_debouncer: DebouncedDelay::new(),
1125                terminals: Terminals {
1126                    local_handles: Vec::new(),
1127                },
1128                node: Some(node),
1129                search_history: Self::new_search_history(),
1130                environment,
1131                remotely_created_models: Default::default(),
1132
1133                search_included_history: Self::new_search_history(),
1134                search_excluded_history: Self::new_search_history(),
1135
1136                toolchain_store: Some(toolchain_store),
1137            };
1138
1139            // ssh -> local machine handlers
1140            let ssh = ssh.read(cx);
1141            ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.entity());
1142            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
1143            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
1144            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
1145            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.dap_store);
1146            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
1147            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.git_store);
1148
1149            ssh_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1150            ssh_proto.add_entity_message_handler(Self::handle_update_worktree);
1151            ssh_proto.add_entity_message_handler(Self::handle_update_project);
1152            ssh_proto.add_entity_message_handler(Self::handle_toast);
1153            ssh_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1154            ssh_proto.add_entity_message_handler(Self::handle_hide_toast);
1155            ssh_proto.add_entity_request_handler(Self::handle_update_buffer_from_ssh);
1156            BufferStore::init(&ssh_proto);
1157            LspStore::init(&ssh_proto);
1158            SettingsObserver::init(&ssh_proto);
1159            TaskStore::init(Some(&ssh_proto));
1160            ToolchainStore::init(&ssh_proto);
1161            DapStore::init(&ssh_proto);
1162            GitStore::init(&ssh_proto);
1163
1164            this
1165        })
1166    }
1167
1168    pub async fn remote(
1169        remote_id: u64,
1170        client: Arc<Client>,
1171        user_store: Entity<UserStore>,
1172        languages: Arc<LanguageRegistry>,
1173        fs: Arc<dyn Fs>,
1174        cx: AsyncApp,
1175    ) -> Result<Entity<Self>> {
1176        let project =
1177            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
1178        cx.update(|cx| {
1179            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
1180                manager.maintain_project_connection(&project, cx)
1181            })
1182        })?;
1183        Ok(project)
1184    }
1185
1186    pub async fn in_room(
1187        remote_id: u64,
1188        client: Arc<Client>,
1189        user_store: Entity<UserStore>,
1190        languages: Arc<LanguageRegistry>,
1191        fs: Arc<dyn Fs>,
1192        cx: AsyncApp,
1193    ) -> Result<Entity<Self>> {
1194        client.authenticate_and_connect(true, &cx).await?;
1195
1196        let subscriptions = [
1197            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1198            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1199            EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1200            EntitySubscription::WorktreeStore(
1201                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1202            ),
1203            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1204            EntitySubscription::SettingsObserver(
1205                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1206            ),
1207            EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1208        ];
1209        let response = client
1210            .request_envelope(proto::JoinProject {
1211                project_id: remote_id,
1212            })
1213            .await?;
1214        Self::from_join_project_response(
1215            response,
1216            subscriptions,
1217            client,
1218            false,
1219            user_store,
1220            languages,
1221            fs,
1222            cx,
1223        )
1224        .await
1225    }
1226
1227    async fn from_join_project_response(
1228        response: TypedEnvelope<proto::JoinProjectResponse>,
1229        subscriptions: [EntitySubscription; 7],
1230        client: Arc<Client>,
1231        run_tasks: bool,
1232        user_store: Entity<UserStore>,
1233        languages: Arc<LanguageRegistry>,
1234        fs: Arc<dyn Fs>,
1235        mut cx: AsyncApp,
1236    ) -> Result<Entity<Self>> {
1237        let remote_id = response.payload.project_id;
1238        let role = response.payload.role();
1239
1240        let worktree_store = cx.new(|_| {
1241            WorktreeStore::remote(true, client.clone().into(), response.payload.project_id)
1242        })?;
1243        let buffer_store = cx.new(|cx| {
1244            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1245        })?;
1246        let image_store = cx.new(|cx| {
1247            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1248        })?;
1249
1250        let environment = cx.new(|_| ProjectEnvironment::new(None))?;
1251
1252        let breakpoint_store =
1253            cx.new(|_| BreakpointStore::remote(remote_id, client.clone().into()))?;
1254        let dap_store = cx.new(|cx| {
1255            DapStore::new_collab(
1256                remote_id,
1257                client.clone().into(),
1258                breakpoint_store.clone(),
1259                worktree_store.clone(),
1260                cx,
1261            )
1262        })?;
1263
1264        let lsp_store = cx.new(|cx| {
1265            let mut lsp_store = LspStore::new_remote(
1266                buffer_store.clone(),
1267                worktree_store.clone(),
1268                None,
1269                languages.clone(),
1270                client.clone().into(),
1271                remote_id,
1272                fs.clone(),
1273                cx,
1274            );
1275            lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
1276            lsp_store
1277        })?;
1278
1279        let task_store = cx.new(|cx| {
1280            if run_tasks {
1281                TaskStore::remote(
1282                    buffer_store.downgrade(),
1283                    worktree_store.clone(),
1284                    Arc::new(EmptyToolchainStore),
1285                    client.clone().into(),
1286                    remote_id,
1287                    cx,
1288                )
1289            } else {
1290                TaskStore::Noop
1291            }
1292        })?;
1293
1294        let settings_observer = cx.new(|cx| {
1295            SettingsObserver::new_remote(fs.clone(), worktree_store.clone(), task_store.clone(), cx)
1296        })?;
1297
1298        let git_store = cx.new(|cx| {
1299            GitStore::remote(
1300                // In this remote case we pass None for the environment
1301                &worktree_store,
1302                buffer_store.clone(),
1303                client.clone().into(),
1304                ProjectId(remote_id),
1305                cx,
1306            )
1307        })?;
1308
1309        let this = cx.new(|cx| {
1310            let replica_id = response.payload.replica_id as ReplicaId;
1311
1312            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1313
1314            let mut worktrees = Vec::new();
1315            for worktree in response.payload.worktrees {
1316                let worktree =
1317                    Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
1318                worktrees.push(worktree);
1319            }
1320
1321            let (tx, rx) = mpsc::unbounded();
1322            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1323                .detach();
1324
1325            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1326                .detach();
1327
1328            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1329                .detach();
1330            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1331            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1332                .detach();
1333
1334            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1335
1336            let mut this = Self {
1337                buffer_ordered_messages_tx: tx,
1338                buffer_store: buffer_store.clone(),
1339                image_store,
1340                worktree_store: worktree_store.clone(),
1341                lsp_store: lsp_store.clone(),
1342                active_entry: None,
1343                collaborators: Default::default(),
1344                join_project_response_message_id: response.message_id,
1345                languages,
1346                user_store: user_store.clone(),
1347                task_store,
1348                snippets,
1349                fs,
1350                ssh_client: None,
1351                settings_observer: settings_observer.clone(),
1352                client_subscriptions: Default::default(),
1353                _subscriptions: vec![cx.on_release(Self::release)],
1354                client: client.clone(),
1355                client_state: ProjectClientState::Remote {
1356                    sharing_has_stopped: false,
1357                    capability: Capability::ReadWrite,
1358                    remote_id,
1359                    replica_id,
1360                },
1361                breakpoint_store,
1362                dap_store: dap_store.clone(),
1363                git_store: git_store.clone(),
1364                buffers_needing_diff: Default::default(),
1365                git_diff_debouncer: DebouncedDelay::new(),
1366                terminals: Terminals {
1367                    local_handles: Vec::new(),
1368                },
1369                node: None,
1370                search_history: Self::new_search_history(),
1371                search_included_history: Self::new_search_history(),
1372                search_excluded_history: Self::new_search_history(),
1373                environment,
1374                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1375                toolchain_store: None,
1376            };
1377            this.set_role(role, cx);
1378            for worktree in worktrees {
1379                this.add_worktree(&worktree, cx);
1380            }
1381            this
1382        })?;
1383
1384        let subscriptions = subscriptions
1385            .into_iter()
1386            .map(|s| match s {
1387                EntitySubscription::BufferStore(subscription) => {
1388                    subscription.set_entity(&buffer_store, &mut cx)
1389                }
1390                EntitySubscription::WorktreeStore(subscription) => {
1391                    subscription.set_entity(&worktree_store, &mut cx)
1392                }
1393                EntitySubscription::GitStore(subscription) => {
1394                    subscription.set_entity(&git_store, &mut cx)
1395                }
1396                EntitySubscription::SettingsObserver(subscription) => {
1397                    subscription.set_entity(&settings_observer, &mut cx)
1398                }
1399                EntitySubscription::Project(subscription) => {
1400                    subscription.set_entity(&this, &mut cx)
1401                }
1402                EntitySubscription::LspStore(subscription) => {
1403                    subscription.set_entity(&lsp_store, &mut cx)
1404                }
1405                EntitySubscription::DapStore(subscription) => {
1406                    subscription.set_entity(&dap_store, &mut cx)
1407                }
1408            })
1409            .collect::<Vec<_>>();
1410
1411        let user_ids = response
1412            .payload
1413            .collaborators
1414            .iter()
1415            .map(|peer| peer.user_id)
1416            .collect();
1417        user_store
1418            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1419            .await?;
1420
1421        this.update(&mut cx, |this, cx| {
1422            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1423            this.client_subscriptions.extend(subscriptions);
1424            anyhow::Ok(())
1425        })??;
1426
1427        Ok(this)
1428    }
1429
1430    fn new_search_history() -> SearchHistory {
1431        SearchHistory::new(
1432            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1433            search_history::QueryInsertionBehavior::AlwaysInsert,
1434        )
1435    }
1436
1437    fn release(&mut self, cx: &mut App) {
1438        if let Some(client) = self.ssh_client.take() {
1439            let shutdown = client
1440                .read(cx)
1441                .shutdown_processes(Some(proto::ShutdownRemoteServer {}));
1442
1443            cx.background_spawn(async move {
1444                if let Some(shutdown) = shutdown {
1445                    shutdown.await;
1446                }
1447            })
1448            .detach()
1449        }
1450
1451        match &self.client_state {
1452            ProjectClientState::Local => {}
1453            ProjectClientState::Shared { .. } => {
1454                let _ = self.unshare_internal(cx);
1455            }
1456            ProjectClientState::Remote { remote_id, .. } => {
1457                let _ = self.client.send(proto::LeaveProject {
1458                    project_id: *remote_id,
1459                });
1460                self.disconnected_from_host_internal(cx);
1461            }
1462        }
1463    }
1464
1465    #[cfg(any(test, feature = "test-support"))]
1466    pub async fn example(
1467        root_paths: impl IntoIterator<Item = &Path>,
1468        cx: &mut AsyncApp,
1469    ) -> Entity<Project> {
1470        use clock::FakeSystemClock;
1471
1472        let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1473        let languages = LanguageRegistry::test(cx.background_executor().clone());
1474        let clock = Arc::new(FakeSystemClock::new());
1475        let http_client = http_client::FakeHttpClient::with_404_response();
1476        let client = cx
1477            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1478            .unwrap();
1479        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1480        let project = cx
1481            .update(|cx| {
1482                Project::local(
1483                    client,
1484                    node_runtime::NodeRuntime::unavailable(),
1485                    user_store,
1486                    Arc::new(languages),
1487                    fs,
1488                    None,
1489                    cx,
1490                )
1491            })
1492            .unwrap();
1493        for path in root_paths {
1494            let (tree, _) = project
1495                .update(cx, |project, cx| {
1496                    project.find_or_create_worktree(path, true, cx)
1497                })
1498                .unwrap()
1499                .await
1500                .unwrap();
1501            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1502                .unwrap()
1503                .await;
1504        }
1505        project
1506    }
1507
1508    #[cfg(any(test, feature = "test-support"))]
1509    pub async fn test(
1510        fs: Arc<dyn Fs>,
1511        root_paths: impl IntoIterator<Item = &Path>,
1512        cx: &mut gpui::TestAppContext,
1513    ) -> Entity<Project> {
1514        use clock::FakeSystemClock;
1515
1516        let languages = LanguageRegistry::test(cx.executor());
1517        let clock = Arc::new(FakeSystemClock::new());
1518        let http_client = http_client::FakeHttpClient::with_404_response();
1519        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1520        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1521        let project = cx.update(|cx| {
1522            Project::local(
1523                client,
1524                node_runtime::NodeRuntime::unavailable(),
1525                user_store,
1526                Arc::new(languages),
1527                fs,
1528                None,
1529                cx,
1530            )
1531        });
1532        for path in root_paths {
1533            let (tree, _) = project
1534                .update(cx, |project, cx| {
1535                    project.find_or_create_worktree(path, true, cx)
1536                })
1537                .await
1538                .unwrap();
1539
1540            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1541                .await;
1542        }
1543        project
1544    }
1545
1546    pub fn dap_store(&self) -> Entity<DapStore> {
1547        self.dap_store.clone()
1548    }
1549
1550    pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1551        self.breakpoint_store.clone()
1552    }
1553
1554    pub fn lsp_store(&self) -> Entity<LspStore> {
1555        self.lsp_store.clone()
1556    }
1557
1558    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1559        self.worktree_store.clone()
1560    }
1561
1562    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1563        self.buffer_store.read(cx).get(remote_id)
1564    }
1565
1566    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1567        &self.languages
1568    }
1569
1570    pub fn client(&self) -> Arc<Client> {
1571        self.client.clone()
1572    }
1573
1574    pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1575        self.ssh_client.clone()
1576    }
1577
1578    pub fn user_store(&self) -> Entity<UserStore> {
1579        self.user_store.clone()
1580    }
1581
1582    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1583        self.node.as_ref()
1584    }
1585
1586    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1587        self.buffer_store.read(cx).buffers().collect()
1588    }
1589
1590    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1591        &self.environment
1592    }
1593
1594    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1595        self.environment.read(cx).get_cli_environment()
1596    }
1597
1598    pub fn shell_environment_errors<'a>(
1599        &'a self,
1600        cx: &'a App,
1601    ) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
1602        self.environment.read(cx).environment_errors()
1603    }
1604
1605    pub fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
1606        self.environment.update(cx, |environment, cx| {
1607            environment.remove_environment_error(abs_path, cx);
1608        });
1609    }
1610
1611    #[cfg(any(test, feature = "test-support"))]
1612    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1613        self.buffer_store
1614            .read(cx)
1615            .get_by_path(&path.into(), cx)
1616            .is_some()
1617    }
1618
1619    pub fn fs(&self) -> &Arc<dyn Fs> {
1620        &self.fs
1621    }
1622
1623    pub fn remote_id(&self) -> Option<u64> {
1624        match self.client_state {
1625            ProjectClientState::Local => None,
1626            ProjectClientState::Shared { remote_id, .. }
1627            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1628        }
1629    }
1630
1631    pub fn supports_terminal(&self, _cx: &App) -> bool {
1632        if self.is_local() {
1633            return true;
1634        }
1635        if self.is_via_ssh() {
1636            return true;
1637        }
1638
1639        return false;
1640    }
1641
1642    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1643        if let Some(ssh_state) = &self.ssh_client {
1644            return Some(ssh_state.read(cx).connection_string().into());
1645        }
1646
1647        return None;
1648    }
1649
1650    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1651        self.ssh_client
1652            .as_ref()
1653            .map(|ssh| ssh.read(cx).connection_state())
1654    }
1655
1656    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1657        self.ssh_client
1658            .as_ref()
1659            .map(|ssh| ssh.read(cx).connection_options())
1660    }
1661
1662    pub fn replica_id(&self) -> ReplicaId {
1663        match self.client_state {
1664            ProjectClientState::Remote { replica_id, .. } => replica_id,
1665            _ => {
1666                if self.ssh_client.is_some() {
1667                    1
1668                } else {
1669                    0
1670                }
1671            }
1672        }
1673    }
1674
1675    pub fn task_store(&self) -> &Entity<TaskStore> {
1676        &self.task_store
1677    }
1678
1679    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1680        &self.snippets
1681    }
1682
1683    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1684        match kind {
1685            SearchInputKind::Query => &self.search_history,
1686            SearchInputKind::Include => &self.search_included_history,
1687            SearchInputKind::Exclude => &self.search_excluded_history,
1688        }
1689    }
1690
1691    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1692        match kind {
1693            SearchInputKind::Query => &mut self.search_history,
1694            SearchInputKind::Include => &mut self.search_included_history,
1695            SearchInputKind::Exclude => &mut self.search_excluded_history,
1696        }
1697    }
1698
1699    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1700        &self.collaborators
1701    }
1702
1703    pub fn host(&self) -> Option<&Collaborator> {
1704        self.collaborators.values().find(|c| c.is_host)
1705    }
1706
1707    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1708        self.worktree_store.update(cx, |store, _| {
1709            store.set_worktrees_reordered(worktrees_reordered);
1710        });
1711    }
1712
1713    /// Collect all worktrees, including ones that don't appear in the project panel
1714    pub fn worktrees<'a>(
1715        &self,
1716        cx: &'a App,
1717    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1718        self.worktree_store.read(cx).worktrees()
1719    }
1720
1721    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1722    pub fn visible_worktrees<'a>(
1723        &'a self,
1724        cx: &'a App,
1725    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1726        self.worktree_store.read(cx).visible_worktrees(cx)
1727    }
1728
1729    pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
1730        self.visible_worktrees(cx)
1731            .find(|tree| tree.read(cx).root_name() == root_name)
1732    }
1733
1734    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1735        self.visible_worktrees(cx)
1736            .map(|tree| tree.read(cx).root_name())
1737    }
1738
1739    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1740        self.worktree_store.read(cx).worktree_for_id(id, cx)
1741    }
1742
1743    pub fn worktree_for_entry(
1744        &self,
1745        entry_id: ProjectEntryId,
1746        cx: &App,
1747    ) -> Option<Entity<Worktree>> {
1748        self.worktree_store
1749            .read(cx)
1750            .worktree_for_entry(entry_id, cx)
1751    }
1752
1753    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1754        self.worktree_for_entry(entry_id, cx)
1755            .map(|worktree| worktree.read(cx).id())
1756    }
1757
1758    /// Checks if the entry is the root of a worktree.
1759    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1760        self.worktree_for_entry(entry_id, cx)
1761            .map(|worktree| {
1762                worktree
1763                    .read(cx)
1764                    .root_entry()
1765                    .is_some_and(|e| e.id == entry_id)
1766            })
1767            .unwrap_or(false)
1768    }
1769
1770    pub fn project_path_git_status(
1771        &self,
1772        project_path: &ProjectPath,
1773        cx: &App,
1774    ) -> Option<FileStatus> {
1775        self.git_store
1776            .read(cx)
1777            .project_path_git_status(project_path, cx)
1778    }
1779
1780    pub fn visibility_for_paths(
1781        &self,
1782        paths: &[PathBuf],
1783        metadatas: &[Metadata],
1784        exclude_sub_dirs: bool,
1785        cx: &App,
1786    ) -> Option<bool> {
1787        paths
1788            .iter()
1789            .zip(metadatas)
1790            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1791            .max()
1792            .flatten()
1793    }
1794
1795    pub fn visibility_for_path(
1796        &self,
1797        path: &Path,
1798        metadata: &Metadata,
1799        exclude_sub_dirs: bool,
1800        cx: &App,
1801    ) -> Option<bool> {
1802        let sanitized_path = SanitizedPath::from(path);
1803        let path = sanitized_path.as_path();
1804        self.worktrees(cx)
1805            .filter_map(|worktree| {
1806                let worktree = worktree.read(cx);
1807                let abs_path = worktree.as_local()?.abs_path();
1808                let contains = path == abs_path
1809                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1810                contains.then(|| worktree.is_visible())
1811            })
1812            .max()
1813    }
1814
1815    pub fn create_entry(
1816        &mut self,
1817        project_path: impl Into<ProjectPath>,
1818        is_directory: bool,
1819        cx: &mut Context<Self>,
1820    ) -> Task<Result<CreatedEntry>> {
1821        let project_path = project_path.into();
1822        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1823            return Task::ready(Err(anyhow!(format!(
1824                "No worktree for path {project_path:?}"
1825            ))));
1826        };
1827        worktree.update(cx, |worktree, cx| {
1828            worktree.create_entry(project_path.path, is_directory, None, cx)
1829        })
1830    }
1831
1832    pub fn copy_entry(
1833        &mut self,
1834        entry_id: ProjectEntryId,
1835        relative_worktree_source_path: Option<PathBuf>,
1836        new_path: impl Into<Arc<Path>>,
1837        cx: &mut Context<Self>,
1838    ) -> Task<Result<Option<Entry>>> {
1839        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1840            return Task::ready(Ok(None));
1841        };
1842        worktree.update(cx, |worktree, cx| {
1843            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1844        })
1845    }
1846
1847    /// Renames the project entry with given `entry_id`.
1848    ///
1849    /// `new_path` is a relative path to worktree root.
1850    /// If root entry is renamed then its new root name is used instead.
1851    pub fn rename_entry(
1852        &mut self,
1853        entry_id: ProjectEntryId,
1854        new_path: impl Into<Arc<Path>>,
1855        cx: &mut Context<Self>,
1856    ) -> Task<Result<CreatedEntry>> {
1857        let worktree_store = self.worktree_store.read(cx);
1858        let new_path = new_path.into();
1859        let Some((worktree, old_path, is_dir)) = worktree_store
1860            .worktree_and_entry_for_id(entry_id, cx)
1861            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1862        else {
1863            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1864        };
1865
1866        let worktree_id = worktree.read(cx).id();
1867        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1868
1869        let lsp_store = self.lsp_store().downgrade();
1870        cx.spawn(async move |_, cx| {
1871            let (old_abs_path, new_abs_path) = {
1872                let root_path = worktree.update(cx, |this, _| this.abs_path())?;
1873                let new_abs_path = if is_root_entry {
1874                    root_path.parent().unwrap().join(&new_path)
1875                } else {
1876                    root_path.join(&new_path)
1877                };
1878                (root_path.join(&old_path), new_abs_path)
1879            };
1880            LspStore::will_rename_entry(
1881                lsp_store.clone(),
1882                worktree_id,
1883                &old_abs_path,
1884                &new_abs_path,
1885                is_dir,
1886                cx.clone(),
1887            )
1888            .await;
1889
1890            let entry = worktree
1891                .update(cx, |worktree, cx| {
1892                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1893                })?
1894                .await?;
1895
1896            lsp_store
1897                .update(cx, |this, _| {
1898                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1899                })
1900                .ok();
1901            Ok(entry)
1902        })
1903    }
1904
1905    pub fn delete_file(
1906        &mut self,
1907        path: ProjectPath,
1908        trash: bool,
1909        cx: &mut Context<Self>,
1910    ) -> Option<Task<Result<()>>> {
1911        let entry = self.entry_for_path(&path, cx)?;
1912        self.delete_entry(entry.id, trash, cx)
1913    }
1914
1915    pub fn delete_entry(
1916        &mut self,
1917        entry_id: ProjectEntryId,
1918        trash: bool,
1919        cx: &mut Context<Self>,
1920    ) -> Option<Task<Result<()>>> {
1921        let worktree = self.worktree_for_entry(entry_id, cx)?;
1922        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1923        worktree.update(cx, |worktree, cx| {
1924            worktree.delete_entry(entry_id, trash, cx)
1925        })
1926    }
1927
1928    pub fn expand_entry(
1929        &mut self,
1930        worktree_id: WorktreeId,
1931        entry_id: ProjectEntryId,
1932        cx: &mut Context<Self>,
1933    ) -> Option<Task<Result<()>>> {
1934        let worktree = self.worktree_for_id(worktree_id, cx)?;
1935        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1936    }
1937
1938    pub fn expand_all_for_entry(
1939        &mut self,
1940        worktree_id: WorktreeId,
1941        entry_id: ProjectEntryId,
1942        cx: &mut Context<Self>,
1943    ) -> Option<Task<Result<()>>> {
1944        let worktree = self.worktree_for_id(worktree_id, cx)?;
1945        let task = worktree.update(cx, |worktree, cx| {
1946            worktree.expand_all_for_entry(entry_id, cx)
1947        });
1948        Some(cx.spawn(async move |this, cx| {
1949            task.ok_or_else(|| anyhow!("no task"))?.await?;
1950            this.update(cx, |_, cx| {
1951                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
1952            })?;
1953            Ok(())
1954        }))
1955    }
1956
1957    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
1958        if !matches!(self.client_state, ProjectClientState::Local) {
1959            return Err(anyhow!("project was already shared"));
1960        }
1961
1962        self.client_subscriptions.extend([
1963            self.client
1964                .subscribe_to_entity(project_id)?
1965                .set_entity(&cx.entity(), &mut cx.to_async()),
1966            self.client
1967                .subscribe_to_entity(project_id)?
1968                .set_entity(&self.worktree_store, &mut cx.to_async()),
1969            self.client
1970                .subscribe_to_entity(project_id)?
1971                .set_entity(&self.buffer_store, &mut cx.to_async()),
1972            self.client
1973                .subscribe_to_entity(project_id)?
1974                .set_entity(&self.lsp_store, &mut cx.to_async()),
1975            self.client
1976                .subscribe_to_entity(project_id)?
1977                .set_entity(&self.settings_observer, &mut cx.to_async()),
1978            self.client
1979                .subscribe_to_entity(project_id)?
1980                .set_entity(&self.dap_store, &mut cx.to_async()),
1981            self.client
1982                .subscribe_to_entity(project_id)?
1983                .set_entity(&self.breakpoint_store, &mut cx.to_async()),
1984            self.client
1985                .subscribe_to_entity(project_id)?
1986                .set_entity(&self.git_store, &mut cx.to_async()),
1987        ]);
1988
1989        self.buffer_store.update(cx, |buffer_store, cx| {
1990            buffer_store.shared(project_id, self.client.clone().into(), cx)
1991        });
1992        self.worktree_store.update(cx, |worktree_store, cx| {
1993            worktree_store.shared(project_id, self.client.clone().into(), cx);
1994        });
1995        self.lsp_store.update(cx, |lsp_store, cx| {
1996            lsp_store.shared(project_id, self.client.clone().into(), cx)
1997        });
1998        self.breakpoint_store.update(cx, |breakpoint_store, _| {
1999            breakpoint_store.shared(project_id, self.client.clone().into())
2000        });
2001        self.dap_store.update(cx, |dap_store, cx| {
2002            dap_store.shared(project_id, self.client.clone().into(), cx);
2003        });
2004        self.task_store.update(cx, |task_store, cx| {
2005            task_store.shared(project_id, self.client.clone().into(), cx);
2006        });
2007        self.settings_observer.update(cx, |settings_observer, cx| {
2008            settings_observer.shared(project_id, self.client.clone().into(), cx)
2009        });
2010        self.git_store.update(cx, |git_store, cx| {
2011            git_store.shared(project_id, self.client.clone().into(), cx)
2012        });
2013
2014        self.client_state = ProjectClientState::Shared {
2015            remote_id: project_id,
2016        };
2017
2018        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2019        Ok(())
2020    }
2021
2022    pub fn reshared(
2023        &mut self,
2024        message: proto::ResharedProject,
2025        cx: &mut Context<Self>,
2026    ) -> Result<()> {
2027        self.buffer_store
2028            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2029        self.set_collaborators_from_proto(message.collaborators, cx)?;
2030
2031        self.worktree_store.update(cx, |worktree_store, cx| {
2032            worktree_store.send_project_updates(cx);
2033        });
2034        if let Some(remote_id) = self.remote_id() {
2035            self.git_store.update(cx, |git_store, cx| {
2036                git_store.shared(remote_id, self.client.clone().into(), cx)
2037            });
2038        }
2039        cx.emit(Event::Reshared);
2040        Ok(())
2041    }
2042
2043    pub fn rejoined(
2044        &mut self,
2045        message: proto::RejoinedProject,
2046        message_id: u32,
2047        cx: &mut Context<Self>,
2048    ) -> Result<()> {
2049        cx.update_global::<SettingsStore, _>(|store, cx| {
2050            self.worktree_store.update(cx, |worktree_store, cx| {
2051                for worktree in worktree_store.worktrees() {
2052                    store
2053                        .clear_local_settings(worktree.read(cx).id(), cx)
2054                        .log_err();
2055                }
2056            });
2057        });
2058
2059        self.join_project_response_message_id = message_id;
2060        self.set_worktrees_from_proto(message.worktrees, cx)?;
2061        self.set_collaborators_from_proto(message.collaborators, cx)?;
2062        self.lsp_store.update(cx, |lsp_store, _| {
2063            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
2064        });
2065        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2066            .unwrap();
2067        cx.emit(Event::Rejoined);
2068        Ok(())
2069    }
2070
2071    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2072        self.unshare_internal(cx)?;
2073        cx.emit(Event::RemoteIdChanged(None));
2074        Ok(())
2075    }
2076
2077    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2078        if self.is_via_collab() {
2079            return Err(anyhow!("attempted to unshare a remote project"));
2080        }
2081
2082        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2083            self.client_state = ProjectClientState::Local;
2084            self.collaborators.clear();
2085            self.client_subscriptions.clear();
2086            self.worktree_store.update(cx, |store, cx| {
2087                store.unshared(cx);
2088            });
2089            self.buffer_store.update(cx, |buffer_store, cx| {
2090                buffer_store.forget_shared_buffers();
2091                buffer_store.unshared(cx)
2092            });
2093            self.task_store.update(cx, |task_store, cx| {
2094                task_store.unshared(cx);
2095            });
2096            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2097                breakpoint_store.unshared(cx);
2098            });
2099            self.dap_store.update(cx, |dap_store, cx| {
2100                dap_store.unshared(cx);
2101            });
2102            self.settings_observer.update(cx, |settings_observer, cx| {
2103                settings_observer.unshared(cx);
2104            });
2105            self.git_store.update(cx, |git_store, cx| {
2106                git_store.unshared(cx);
2107            });
2108
2109            self.client
2110                .send(proto::UnshareProject {
2111                    project_id: remote_id,
2112                })
2113                .ok();
2114            Ok(())
2115        } else {
2116            Err(anyhow!("attempted to unshare an unshared project"))
2117        }
2118    }
2119
2120    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2121        if self.is_disconnected(cx) {
2122            return;
2123        }
2124        self.disconnected_from_host_internal(cx);
2125        cx.emit(Event::DisconnectedFromHost);
2126    }
2127
2128    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2129        let new_capability =
2130            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2131                Capability::ReadWrite
2132            } else {
2133                Capability::ReadOnly
2134            };
2135        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2136            if *capability == new_capability {
2137                return;
2138            }
2139
2140            *capability = new_capability;
2141            for buffer in self.opened_buffers(cx) {
2142                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2143            }
2144        }
2145    }
2146
2147    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2148        if let ProjectClientState::Remote {
2149            sharing_has_stopped,
2150            ..
2151        } = &mut self.client_state
2152        {
2153            *sharing_has_stopped = true;
2154            self.collaborators.clear();
2155            self.worktree_store.update(cx, |store, cx| {
2156                store.disconnected_from_host(cx);
2157            });
2158            self.buffer_store.update(cx, |buffer_store, cx| {
2159                buffer_store.disconnected_from_host(cx)
2160            });
2161            self.lsp_store
2162                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2163        }
2164    }
2165
2166    pub fn close(&mut self, cx: &mut Context<Self>) {
2167        cx.emit(Event::Closed);
2168    }
2169
2170    pub fn is_disconnected(&self, cx: &App) -> bool {
2171        match &self.client_state {
2172            ProjectClientState::Remote {
2173                sharing_has_stopped,
2174                ..
2175            } => *sharing_has_stopped,
2176            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
2177            _ => false,
2178        }
2179    }
2180
2181    fn ssh_is_disconnected(&self, cx: &App) -> bool {
2182        self.ssh_client
2183            .as_ref()
2184            .map(|ssh| ssh.read(cx).is_disconnected())
2185            .unwrap_or(false)
2186    }
2187
2188    pub fn capability(&self) -> Capability {
2189        match &self.client_state {
2190            ProjectClientState::Remote { capability, .. } => *capability,
2191            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2192        }
2193    }
2194
2195    pub fn is_read_only(&self, cx: &App) -> bool {
2196        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2197    }
2198
2199    pub fn is_local(&self) -> bool {
2200        match &self.client_state {
2201            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2202                self.ssh_client.is_none()
2203            }
2204            ProjectClientState::Remote { .. } => false,
2205        }
2206    }
2207
2208    pub fn is_via_ssh(&self) -> bool {
2209        match &self.client_state {
2210            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2211                self.ssh_client.is_some()
2212            }
2213            ProjectClientState::Remote { .. } => false,
2214        }
2215    }
2216
2217    pub fn is_via_collab(&self) -> bool {
2218        match &self.client_state {
2219            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2220            ProjectClientState::Remote { .. } => true,
2221        }
2222    }
2223
2224    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2225        self.buffer_store
2226            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
2227    }
2228
2229    pub fn create_local_buffer(
2230        &mut self,
2231        text: &str,
2232        language: Option<Arc<Language>>,
2233        cx: &mut Context<Self>,
2234    ) -> Entity<Buffer> {
2235        if self.is_via_collab() || self.is_via_ssh() {
2236            panic!("called create_local_buffer on a remote project")
2237        }
2238        self.buffer_store.update(cx, |buffer_store, cx| {
2239            buffer_store.create_local_buffer(text, language, cx)
2240        })
2241    }
2242
2243    pub fn open_path(
2244        &mut self,
2245        path: ProjectPath,
2246        cx: &mut Context<Self>,
2247    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
2248        let task = self.open_buffer(path.clone(), cx);
2249        cx.spawn(async move |_project, cx| {
2250            let buffer = task.await?;
2251            let project_entry_id = buffer.read_with(cx, |buffer, cx| {
2252                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
2253            })?;
2254
2255            let buffer: &AnyEntity = &buffer;
2256            Ok((project_entry_id, buffer.clone()))
2257        })
2258    }
2259
2260    pub fn open_local_buffer(
2261        &mut self,
2262        abs_path: impl AsRef<Path>,
2263        cx: &mut Context<Self>,
2264    ) -> Task<Result<Entity<Buffer>>> {
2265        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2266            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
2267        } else {
2268            Task::ready(Err(anyhow!("no such path")))
2269        }
2270    }
2271
2272    #[cfg(any(test, feature = "test-support"))]
2273    pub fn open_local_buffer_with_lsp(
2274        &mut self,
2275        abs_path: impl AsRef<Path>,
2276        cx: &mut Context<Self>,
2277    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2278        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2279            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2280        } else {
2281            Task::ready(Err(anyhow!("no such path")))
2282        }
2283    }
2284
2285    pub fn open_buffer(
2286        &mut self,
2287        path: impl Into<ProjectPath>,
2288        cx: &mut App,
2289    ) -> Task<Result<Entity<Buffer>>> {
2290        if self.is_disconnected(cx) {
2291            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2292        }
2293
2294        self.buffer_store.update(cx, |buffer_store, cx| {
2295            buffer_store.open_buffer(path.into(), cx)
2296        })
2297    }
2298
2299    #[cfg(any(test, feature = "test-support"))]
2300    pub fn open_buffer_with_lsp(
2301        &mut self,
2302        path: impl Into<ProjectPath>,
2303        cx: &mut Context<Self>,
2304    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2305        let buffer = self.open_buffer(path, cx);
2306        cx.spawn(async move |this, cx| {
2307            let buffer = buffer.await?;
2308            let handle = this.update(cx, |project, cx| {
2309                project.register_buffer_with_language_servers(&buffer, cx)
2310            })?;
2311            Ok((buffer, handle))
2312        })
2313    }
2314
2315    pub fn register_buffer_with_language_servers(
2316        &self,
2317        buffer: &Entity<Buffer>,
2318        cx: &mut App,
2319    ) -> OpenLspBufferHandle {
2320        self.lsp_store.update(cx, |lsp_store, cx| {
2321            lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2322        })
2323    }
2324
2325    pub fn open_unstaged_diff(
2326        &mut self,
2327        buffer: Entity<Buffer>,
2328        cx: &mut Context<Self>,
2329    ) -> Task<Result<Entity<BufferDiff>>> {
2330        if self.is_disconnected(cx) {
2331            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2332        }
2333        self.git_store
2334            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2335    }
2336
2337    pub fn open_uncommitted_diff(
2338        &mut self,
2339        buffer: Entity<Buffer>,
2340        cx: &mut Context<Self>,
2341    ) -> Task<Result<Entity<BufferDiff>>> {
2342        if self.is_disconnected(cx) {
2343            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2344        }
2345        self.git_store.update(cx, |git_store, cx| {
2346            git_store.open_uncommitted_diff(buffer, cx)
2347        })
2348    }
2349
2350    pub fn open_buffer_by_id(
2351        &mut self,
2352        id: BufferId,
2353        cx: &mut Context<Self>,
2354    ) -> Task<Result<Entity<Buffer>>> {
2355        if let Some(buffer) = self.buffer_for_id(id, cx) {
2356            Task::ready(Ok(buffer))
2357        } else if self.is_local() || self.is_via_ssh() {
2358            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2359        } else if let Some(project_id) = self.remote_id() {
2360            let request = self.client.request(proto::OpenBufferById {
2361                project_id,
2362                id: id.into(),
2363            });
2364            cx.spawn(async move |project, cx| {
2365                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2366                project
2367                    .update(cx, |project, cx| {
2368                        project.buffer_store.update(cx, |buffer_store, cx| {
2369                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2370                        })
2371                    })?
2372                    .await
2373            })
2374        } else {
2375            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2376        }
2377    }
2378
2379    pub fn save_buffers(
2380        &self,
2381        buffers: HashSet<Entity<Buffer>>,
2382        cx: &mut Context<Self>,
2383    ) -> Task<Result<()>> {
2384        cx.spawn(async move |this, cx| {
2385            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2386                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2387                    .ok()
2388            });
2389            try_join_all(save_tasks).await?;
2390            Ok(())
2391        })
2392    }
2393
2394    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2395        self.buffer_store
2396            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2397    }
2398
2399    pub fn save_buffer_as(
2400        &mut self,
2401        buffer: Entity<Buffer>,
2402        path: ProjectPath,
2403        cx: &mut Context<Self>,
2404    ) -> Task<Result<()>> {
2405        self.buffer_store.update(cx, |buffer_store, cx| {
2406            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2407        })
2408    }
2409
2410    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2411        self.buffer_store.read(cx).get_by_path(path, cx)
2412    }
2413
2414    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2415        {
2416            let mut remotely_created_models = self.remotely_created_models.lock();
2417            if remotely_created_models.retain_count > 0 {
2418                remotely_created_models.buffers.push(buffer.clone())
2419            }
2420        }
2421
2422        self.request_buffer_diff_recalculation(buffer, cx);
2423
2424        cx.subscribe(buffer, |this, buffer, event, cx| {
2425            this.on_buffer_event(buffer, event, cx);
2426        })
2427        .detach();
2428
2429        Ok(())
2430    }
2431
2432    pub fn open_image(
2433        &mut self,
2434        path: impl Into<ProjectPath>,
2435        cx: &mut Context<Self>,
2436    ) -> Task<Result<Entity<ImageItem>>> {
2437        if self.is_disconnected(cx) {
2438            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2439        }
2440
2441        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2442            image_store.open_image(path.into(), cx)
2443        });
2444
2445        let weak_project = cx.entity().downgrade();
2446        cx.spawn(async move |_, cx| {
2447            let image_item = open_image_task.await?;
2448            let project = weak_project
2449                .upgrade()
2450                .ok_or_else(|| anyhow!("Project dropped"))?;
2451
2452            let metadata = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2453            image_item.update(cx, |image_item, cx| {
2454                image_item.image_metadata = Some(metadata);
2455                cx.emit(ImageItemEvent::MetadataUpdated);
2456            })?;
2457
2458            Ok(image_item)
2459        })
2460    }
2461
2462    async fn send_buffer_ordered_messages(
2463        this: WeakEntity<Self>,
2464        rx: UnboundedReceiver<BufferOrderedMessage>,
2465        cx: &mut AsyncApp,
2466    ) -> Result<()> {
2467        const MAX_BATCH_SIZE: usize = 128;
2468
2469        let mut operations_by_buffer_id = HashMap::default();
2470        async fn flush_operations(
2471            this: &WeakEntity<Project>,
2472            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2473            needs_resync_with_host: &mut bool,
2474            is_local: bool,
2475            cx: &mut AsyncApp,
2476        ) -> Result<()> {
2477            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2478                let request = this.update(cx, |this, _| {
2479                    let project_id = this.remote_id()?;
2480                    Some(this.client.request(proto::UpdateBuffer {
2481                        buffer_id: buffer_id.into(),
2482                        project_id,
2483                        operations,
2484                    }))
2485                })?;
2486                if let Some(request) = request {
2487                    if request.await.is_err() && !is_local {
2488                        *needs_resync_with_host = true;
2489                        break;
2490                    }
2491                }
2492            }
2493            Ok(())
2494        }
2495
2496        let mut needs_resync_with_host = false;
2497        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2498
2499        while let Some(changes) = changes.next().await {
2500            let is_local = this.update(cx, |this, _| this.is_local())?;
2501
2502            for change in changes {
2503                match change {
2504                    BufferOrderedMessage::Operation {
2505                        buffer_id,
2506                        operation,
2507                    } => {
2508                        if needs_resync_with_host {
2509                            continue;
2510                        }
2511
2512                        operations_by_buffer_id
2513                            .entry(buffer_id)
2514                            .or_insert(Vec::new())
2515                            .push(operation);
2516                    }
2517
2518                    BufferOrderedMessage::Resync => {
2519                        operations_by_buffer_id.clear();
2520                        if this
2521                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2522                            .await
2523                            .is_ok()
2524                        {
2525                            needs_resync_with_host = false;
2526                        }
2527                    }
2528
2529                    BufferOrderedMessage::LanguageServerUpdate {
2530                        language_server_id,
2531                        message,
2532                    } => {
2533                        flush_operations(
2534                            &this,
2535                            &mut operations_by_buffer_id,
2536                            &mut needs_resync_with_host,
2537                            is_local,
2538                            cx,
2539                        )
2540                        .await?;
2541
2542                        this.update(cx, |this, _| {
2543                            if let Some(project_id) = this.remote_id() {
2544                                this.client
2545                                    .send(proto::UpdateLanguageServer {
2546                                        project_id,
2547                                        language_server_id: language_server_id.0 as u64,
2548                                        variant: Some(message),
2549                                    })
2550                                    .log_err();
2551                            }
2552                        })?;
2553                    }
2554                }
2555            }
2556
2557            flush_operations(
2558                &this,
2559                &mut operations_by_buffer_id,
2560                &mut needs_resync_with_host,
2561                is_local,
2562                cx,
2563            )
2564            .await?;
2565        }
2566
2567        Ok(())
2568    }
2569
2570    fn on_buffer_store_event(
2571        &mut self,
2572        _: Entity<BufferStore>,
2573        event: &BufferStoreEvent,
2574        cx: &mut Context<Self>,
2575    ) {
2576        match event {
2577            BufferStoreEvent::BufferAdded(buffer) => {
2578                self.register_buffer(buffer, cx).log_err();
2579            }
2580            BufferStoreEvent::BufferDropped(buffer_id) => {
2581                if let Some(ref ssh_client) = self.ssh_client {
2582                    ssh_client
2583                        .read(cx)
2584                        .proto_client()
2585                        .send(proto::CloseBuffer {
2586                            project_id: 0,
2587                            buffer_id: buffer_id.to_proto(),
2588                        })
2589                        .log_err();
2590                }
2591            }
2592            _ => {}
2593        }
2594    }
2595
2596    fn on_image_store_event(
2597        &mut self,
2598        _: Entity<ImageStore>,
2599        event: &ImageStoreEvent,
2600        cx: &mut Context<Self>,
2601    ) {
2602        match event {
2603            ImageStoreEvent::ImageAdded(image) => {
2604                cx.subscribe(image, |this, image, event, cx| {
2605                    this.on_image_event(image, event, cx);
2606                })
2607                .detach();
2608            }
2609        }
2610    }
2611
2612    fn on_dap_store_event(
2613        &mut self,
2614        _: Entity<DapStore>,
2615        event: &DapStoreEvent,
2616        cx: &mut Context<Self>,
2617    ) {
2618        match event {
2619            DapStoreEvent::Notification(message) => {
2620                cx.emit(Event::Toast {
2621                    notification_id: "dap".into(),
2622                    message: message.clone(),
2623                });
2624            }
2625            _ => {}
2626        }
2627    }
2628
2629    fn on_lsp_store_event(
2630        &mut self,
2631        _: Entity<LspStore>,
2632        event: &LspStoreEvent,
2633        cx: &mut Context<Self>,
2634    ) {
2635        match event {
2636            LspStoreEvent::DiagnosticsUpdated {
2637                language_server_id,
2638                path,
2639            } => cx.emit(Event::DiagnosticsUpdated {
2640                path: path.clone(),
2641                language_server_id: *language_server_id,
2642            }),
2643            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2644                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2645            ),
2646            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2647                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2648            }
2649            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2650                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2651            ),
2652            LspStoreEvent::LanguageDetected {
2653                buffer,
2654                new_language,
2655            } => {
2656                let Some(_) = new_language else {
2657                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2658                    return;
2659                };
2660            }
2661            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2662            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2663            LspStoreEvent::LanguageServerPrompt(prompt) => {
2664                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2665            }
2666            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2667                cx.emit(Event::DiskBasedDiagnosticsStarted {
2668                    language_server_id: *language_server_id,
2669                });
2670            }
2671            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2672                cx.emit(Event::DiskBasedDiagnosticsFinished {
2673                    language_server_id: *language_server_id,
2674                });
2675            }
2676            LspStoreEvent::LanguageServerUpdate {
2677                language_server_id,
2678                message,
2679            } => {
2680                if self.is_local() {
2681                    self.enqueue_buffer_ordered_message(
2682                        BufferOrderedMessage::LanguageServerUpdate {
2683                            language_server_id: *language_server_id,
2684                            message: message.clone(),
2685                        },
2686                    )
2687                    .ok();
2688                }
2689            }
2690            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2691                notification_id: "lsp".into(),
2692                message: message.clone(),
2693            }),
2694            LspStoreEvent::SnippetEdit {
2695                buffer_id,
2696                edits,
2697                most_recent_edit,
2698            } => {
2699                if most_recent_edit.replica_id == self.replica_id() {
2700                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2701                }
2702            }
2703        }
2704    }
2705
2706    fn on_ssh_event(
2707        &mut self,
2708        _: Entity<SshRemoteClient>,
2709        event: &remote::SshRemoteEvent,
2710        cx: &mut Context<Self>,
2711    ) {
2712        match event {
2713            remote::SshRemoteEvent::Disconnected => {
2714                // if self.is_via_ssh() {
2715                // self.collaborators.clear();
2716                self.worktree_store.update(cx, |store, cx| {
2717                    store.disconnected_from_host(cx);
2718                });
2719                self.buffer_store.update(cx, |buffer_store, cx| {
2720                    buffer_store.disconnected_from_host(cx)
2721                });
2722                self.lsp_store.update(cx, |lsp_store, _cx| {
2723                    lsp_store.disconnected_from_ssh_remote()
2724                });
2725                cx.emit(Event::DisconnectedFromSshRemote);
2726            }
2727        }
2728    }
2729
2730    fn on_settings_observer_event(
2731        &mut self,
2732        _: Entity<SettingsObserver>,
2733        event: &SettingsObserverEvent,
2734        cx: &mut Context<Self>,
2735    ) {
2736        match event {
2737            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2738                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2739                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
2740                    cx.emit(Event::Toast {
2741                        notification_id: format!("local-settings-{path:?}").into(),
2742                        message,
2743                    });
2744                }
2745                Ok(path) => cx.emit(Event::HideToast {
2746                    notification_id: format!("local-settings-{path:?}").into(),
2747                }),
2748                Err(_) => {}
2749            },
2750            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
2751                Err(InvalidSettingsError::Tasks { message, path }) => {
2752                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
2753                    cx.emit(Event::Toast {
2754                        notification_id: format!("local-tasks-{path:?}").into(),
2755                        message,
2756                    });
2757                }
2758                Ok(path) => cx.emit(Event::HideToast {
2759                    notification_id: format!("local-tasks-{path:?}").into(),
2760                }),
2761                Err(_) => {}
2762            },
2763        }
2764    }
2765
2766    fn on_worktree_store_event(
2767        &mut self,
2768        _: Entity<WorktreeStore>,
2769        event: &WorktreeStoreEvent,
2770        cx: &mut Context<Self>,
2771    ) {
2772        match event {
2773            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2774                self.on_worktree_added(worktree, cx);
2775                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2776            }
2777            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2778                cx.emit(Event::WorktreeRemoved(*id));
2779            }
2780            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2781                self.on_worktree_released(*id, cx);
2782            }
2783            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2784            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2785            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2786                self.client()
2787                    .telemetry()
2788                    .report_discovered_project_events(*worktree_id, changes);
2789                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2790            }
2791            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2792                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2793            }
2794            // Listen to the GitStore instead.
2795            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
2796        }
2797    }
2798
2799    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2800        let mut remotely_created_models = self.remotely_created_models.lock();
2801        if remotely_created_models.retain_count > 0 {
2802            remotely_created_models.worktrees.push(worktree.clone())
2803        }
2804    }
2805
2806    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2807        if let Some(ssh) = &self.ssh_client {
2808            ssh.read(cx)
2809                .proto_client()
2810                .send(proto::RemoveWorktree {
2811                    worktree_id: id_to_remove.to_proto(),
2812                })
2813                .log_err();
2814        }
2815    }
2816
2817    fn on_buffer_event(
2818        &mut self,
2819        buffer: Entity<Buffer>,
2820        event: &BufferEvent,
2821        cx: &mut Context<Self>,
2822    ) -> Option<()> {
2823        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2824            self.request_buffer_diff_recalculation(&buffer, cx);
2825        }
2826
2827        let buffer_id = buffer.read(cx).remote_id();
2828        match event {
2829            BufferEvent::ReloadNeeded => {
2830                if !self.is_via_collab() {
2831                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2832                        .detach_and_log_err(cx);
2833                }
2834            }
2835            BufferEvent::Operation {
2836                operation,
2837                is_local: true,
2838            } => {
2839                let operation = language::proto::serialize_operation(operation);
2840
2841                if let Some(ssh) = &self.ssh_client {
2842                    ssh.read(cx)
2843                        .proto_client()
2844                        .send(proto::UpdateBuffer {
2845                            project_id: 0,
2846                            buffer_id: buffer_id.to_proto(),
2847                            operations: vec![operation.clone()],
2848                        })
2849                        .ok();
2850                }
2851
2852                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2853                    buffer_id,
2854                    operation,
2855                })
2856                .ok();
2857            }
2858
2859            _ => {}
2860        }
2861
2862        None
2863    }
2864
2865    fn on_image_event(
2866        &mut self,
2867        image: Entity<ImageItem>,
2868        event: &ImageItemEvent,
2869        cx: &mut Context<Self>,
2870    ) -> Option<()> {
2871        match event {
2872            ImageItemEvent::ReloadNeeded => {
2873                if !self.is_via_collab() {
2874                    self.reload_images([image.clone()].into_iter().collect(), cx)
2875                        .detach_and_log_err(cx);
2876                }
2877            }
2878            _ => {}
2879        }
2880
2881        None
2882    }
2883
2884    fn request_buffer_diff_recalculation(
2885        &mut self,
2886        buffer: &Entity<Buffer>,
2887        cx: &mut Context<Self>,
2888    ) {
2889        self.buffers_needing_diff.insert(buffer.downgrade());
2890        let first_insertion = self.buffers_needing_diff.len() == 1;
2891
2892        let settings = ProjectSettings::get_global(cx);
2893        let delay = if let Some(delay) = settings.git.gutter_debounce {
2894            delay
2895        } else {
2896            if first_insertion {
2897                let this = cx.weak_entity();
2898                cx.defer(move |cx| {
2899                    if let Some(this) = this.upgrade() {
2900                        this.update(cx, |this, cx| {
2901                            this.recalculate_buffer_diffs(cx).detach();
2902                        });
2903                    }
2904                });
2905            }
2906            return;
2907        };
2908
2909        const MIN_DELAY: u64 = 50;
2910        let delay = delay.max(MIN_DELAY);
2911        let duration = Duration::from_millis(delay);
2912
2913        self.git_diff_debouncer
2914            .fire_new(duration, cx, move |this, cx| {
2915                this.recalculate_buffer_diffs(cx)
2916            });
2917    }
2918
2919    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2920        cx.spawn(async move |this, cx| {
2921            loop {
2922                let task = this
2923                    .update(cx, |this, cx| {
2924                        let buffers = this
2925                            .buffers_needing_diff
2926                            .drain()
2927                            .filter_map(|buffer| buffer.upgrade())
2928                            .collect::<Vec<_>>();
2929                        if buffers.is_empty() {
2930                            None
2931                        } else {
2932                            Some(this.git_store.update(cx, |git_store, cx| {
2933                                git_store.recalculate_buffer_diffs(buffers, cx)
2934                            }))
2935                        }
2936                    })
2937                    .ok()
2938                    .flatten();
2939
2940                if let Some(task) = task {
2941                    task.await;
2942                } else {
2943                    break;
2944                }
2945            }
2946        })
2947    }
2948
2949    pub fn set_language_for_buffer(
2950        &mut self,
2951        buffer: &Entity<Buffer>,
2952        new_language: Arc<Language>,
2953        cx: &mut Context<Self>,
2954    ) {
2955        self.lsp_store.update(cx, |lsp_store, cx| {
2956            lsp_store.set_language_for_buffer(buffer, new_language, cx)
2957        })
2958    }
2959
2960    pub fn restart_language_servers_for_buffers(
2961        &mut self,
2962        buffers: Vec<Entity<Buffer>>,
2963        cx: &mut Context<Self>,
2964    ) {
2965        self.lsp_store.update(cx, |lsp_store, cx| {
2966            lsp_store.restart_language_servers_for_buffers(buffers, cx)
2967        })
2968    }
2969
2970    pub fn stop_language_servers_for_buffers(
2971        &mut self,
2972        buffers: Vec<Entity<Buffer>>,
2973        cx: &mut Context<Self>,
2974    ) {
2975        self.lsp_store.update(cx, |lsp_store, cx| {
2976            lsp_store.stop_language_servers_for_buffers(buffers, cx)
2977        })
2978    }
2979
2980    pub fn cancel_language_server_work_for_buffers(
2981        &mut self,
2982        buffers: impl IntoIterator<Item = Entity<Buffer>>,
2983        cx: &mut Context<Self>,
2984    ) {
2985        self.lsp_store.update(cx, |lsp_store, cx| {
2986            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
2987        })
2988    }
2989
2990    pub fn cancel_language_server_work(
2991        &mut self,
2992        server_id: LanguageServerId,
2993        token_to_cancel: Option<String>,
2994        cx: &mut Context<Self>,
2995    ) {
2996        self.lsp_store.update(cx, |lsp_store, cx| {
2997            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
2998        })
2999    }
3000
3001    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3002        self.buffer_ordered_messages_tx
3003            .unbounded_send(message)
3004            .map_err(|e| anyhow!(e))
3005    }
3006
3007    pub fn available_toolchains(
3008        &self,
3009        path: ProjectPath,
3010        language_name: LanguageName,
3011        cx: &App,
3012    ) -> Task<Option<ToolchainList>> {
3013        if let Some(toolchain_store) = self.toolchain_store.clone() {
3014            cx.spawn(async move |cx| {
3015                cx.update(|cx| {
3016                    toolchain_store
3017                        .read(cx)
3018                        .list_toolchains(path, language_name, cx)
3019                })
3020                .ok()?
3021                .await
3022            })
3023        } else {
3024            Task::ready(None)
3025        }
3026    }
3027
3028    pub async fn toolchain_term(
3029        languages: Arc<LanguageRegistry>,
3030        language_name: LanguageName,
3031    ) -> Option<SharedString> {
3032        languages
3033            .language_for_name(language_name.as_ref())
3034            .await
3035            .ok()?
3036            .toolchain_lister()
3037            .map(|lister| lister.term())
3038    }
3039
3040    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3041        self.toolchain_store.clone()
3042    }
3043    pub fn activate_toolchain(
3044        &self,
3045        path: ProjectPath,
3046        toolchain: Toolchain,
3047        cx: &mut App,
3048    ) -> Task<Option<()>> {
3049        let Some(toolchain_store) = self.toolchain_store.clone() else {
3050            return Task::ready(None);
3051        };
3052        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3053    }
3054    pub fn active_toolchain(
3055        &self,
3056        path: ProjectPath,
3057        language_name: LanguageName,
3058        cx: &App,
3059    ) -> Task<Option<Toolchain>> {
3060        let Some(toolchain_store) = self.toolchain_store.clone() else {
3061            return Task::ready(None);
3062        };
3063        toolchain_store
3064            .read(cx)
3065            .active_toolchain(path, language_name, cx)
3066    }
3067    pub fn language_server_statuses<'a>(
3068        &'a self,
3069        cx: &'a App,
3070    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3071        self.lsp_store.read(cx).language_server_statuses()
3072    }
3073
3074    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3075        self.lsp_store.read(cx).last_formatting_failure()
3076    }
3077
3078    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3079        self.lsp_store
3080            .update(cx, |store, _| store.reset_last_formatting_failure());
3081    }
3082
3083    pub fn reload_buffers(
3084        &self,
3085        buffers: HashSet<Entity<Buffer>>,
3086        push_to_history: bool,
3087        cx: &mut Context<Self>,
3088    ) -> Task<Result<ProjectTransaction>> {
3089        self.buffer_store.update(cx, |buffer_store, cx| {
3090            buffer_store.reload_buffers(buffers, push_to_history, cx)
3091        })
3092    }
3093
3094    pub fn reload_images(
3095        &self,
3096        images: HashSet<Entity<ImageItem>>,
3097        cx: &mut Context<Self>,
3098    ) -> Task<Result<()>> {
3099        self.image_store
3100            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3101    }
3102
3103    pub fn format(
3104        &mut self,
3105        buffers: HashSet<Entity<Buffer>>,
3106        target: LspFormatTarget,
3107        push_to_history: bool,
3108        trigger: lsp_store::FormatTrigger,
3109        cx: &mut Context<Project>,
3110    ) -> Task<anyhow::Result<ProjectTransaction>> {
3111        self.lsp_store.update(cx, |lsp_store, cx| {
3112            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3113        })
3114    }
3115
3116    #[inline(never)]
3117    fn definition_impl(
3118        &mut self,
3119        buffer: &Entity<Buffer>,
3120        position: PointUtf16,
3121        cx: &mut Context<Self>,
3122    ) -> Task<Result<Vec<LocationLink>>> {
3123        self.request_lsp(
3124            buffer.clone(),
3125            LanguageServerToQuery::FirstCapable,
3126            GetDefinition { position },
3127            cx,
3128        )
3129    }
3130    pub fn definition<T: ToPointUtf16>(
3131        &mut self,
3132        buffer: &Entity<Buffer>,
3133        position: T,
3134        cx: &mut Context<Self>,
3135    ) -> Task<Result<Vec<LocationLink>>> {
3136        let position = position.to_point_utf16(buffer.read(cx));
3137        self.definition_impl(buffer, position, cx)
3138    }
3139
3140    fn declaration_impl(
3141        &mut self,
3142        buffer: &Entity<Buffer>,
3143        position: PointUtf16,
3144        cx: &mut Context<Self>,
3145    ) -> Task<Result<Vec<LocationLink>>> {
3146        self.request_lsp(
3147            buffer.clone(),
3148            LanguageServerToQuery::FirstCapable,
3149            GetDeclaration { position },
3150            cx,
3151        )
3152    }
3153
3154    pub fn declaration<T: ToPointUtf16>(
3155        &mut self,
3156        buffer: &Entity<Buffer>,
3157        position: T,
3158        cx: &mut Context<Self>,
3159    ) -> Task<Result<Vec<LocationLink>>> {
3160        let position = position.to_point_utf16(buffer.read(cx));
3161        self.declaration_impl(buffer, position, cx)
3162    }
3163
3164    fn type_definition_impl(
3165        &mut self,
3166        buffer: &Entity<Buffer>,
3167        position: PointUtf16,
3168        cx: &mut Context<Self>,
3169    ) -> Task<Result<Vec<LocationLink>>> {
3170        self.request_lsp(
3171            buffer.clone(),
3172            LanguageServerToQuery::FirstCapable,
3173            GetTypeDefinition { position },
3174            cx,
3175        )
3176    }
3177
3178    pub fn type_definition<T: ToPointUtf16>(
3179        &mut self,
3180        buffer: &Entity<Buffer>,
3181        position: T,
3182        cx: &mut Context<Self>,
3183    ) -> Task<Result<Vec<LocationLink>>> {
3184        let position = position.to_point_utf16(buffer.read(cx));
3185        self.type_definition_impl(buffer, position, cx)
3186    }
3187
3188    pub fn implementation<T: ToPointUtf16>(
3189        &mut self,
3190        buffer: &Entity<Buffer>,
3191        position: T,
3192        cx: &mut Context<Self>,
3193    ) -> Task<Result<Vec<LocationLink>>> {
3194        let position = position.to_point_utf16(buffer.read(cx));
3195        self.request_lsp(
3196            buffer.clone(),
3197            LanguageServerToQuery::FirstCapable,
3198            GetImplementation { position },
3199            cx,
3200        )
3201    }
3202
3203    pub fn references<T: ToPointUtf16>(
3204        &mut self,
3205        buffer: &Entity<Buffer>,
3206        position: T,
3207        cx: &mut Context<Self>,
3208    ) -> Task<Result<Vec<Location>>> {
3209        let position = position.to_point_utf16(buffer.read(cx));
3210        self.request_lsp(
3211            buffer.clone(),
3212            LanguageServerToQuery::FirstCapable,
3213            GetReferences { position },
3214            cx,
3215        )
3216    }
3217
3218    fn document_highlights_impl(
3219        &mut self,
3220        buffer: &Entity<Buffer>,
3221        position: PointUtf16,
3222        cx: &mut Context<Self>,
3223    ) -> Task<Result<Vec<DocumentHighlight>>> {
3224        self.request_lsp(
3225            buffer.clone(),
3226            LanguageServerToQuery::FirstCapable,
3227            GetDocumentHighlights { position },
3228            cx,
3229        )
3230    }
3231
3232    pub fn document_highlights<T: ToPointUtf16>(
3233        &mut self,
3234        buffer: &Entity<Buffer>,
3235        position: T,
3236        cx: &mut Context<Self>,
3237    ) -> Task<Result<Vec<DocumentHighlight>>> {
3238        let position = position.to_point_utf16(buffer.read(cx));
3239        self.document_highlights_impl(buffer, position, cx)
3240    }
3241
3242    pub fn document_symbols(
3243        &mut self,
3244        buffer: &Entity<Buffer>,
3245        cx: &mut Context<Self>,
3246    ) -> Task<Result<Vec<DocumentSymbol>>> {
3247        self.request_lsp(
3248            buffer.clone(),
3249            LanguageServerToQuery::FirstCapable,
3250            GetDocumentSymbols,
3251            cx,
3252        )
3253    }
3254
3255    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3256        self.lsp_store
3257            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3258    }
3259
3260    pub fn open_buffer_for_symbol(
3261        &mut self,
3262        symbol: &Symbol,
3263        cx: &mut Context<Self>,
3264    ) -> Task<Result<Entity<Buffer>>> {
3265        self.lsp_store.update(cx, |lsp_store, cx| {
3266            lsp_store.open_buffer_for_symbol(symbol, cx)
3267        })
3268    }
3269
3270    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3271        let guard = self.retain_remotely_created_models(cx);
3272        let Some(ssh_client) = self.ssh_client.as_ref() else {
3273            return Task::ready(Err(anyhow!("not an ssh project")));
3274        };
3275
3276        let proto_client = ssh_client.read(cx).proto_client();
3277
3278        cx.spawn(async move |project, cx| {
3279            let buffer = proto_client
3280                .request(proto::OpenServerSettings {
3281                    project_id: SSH_PROJECT_ID,
3282                })
3283                .await?;
3284
3285            let buffer = project
3286                .update(cx, |project, cx| {
3287                    project.buffer_store.update(cx, |buffer_store, cx| {
3288                        anyhow::Ok(
3289                            buffer_store
3290                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3291                        )
3292                    })
3293                })??
3294                .await;
3295
3296            drop(guard);
3297            buffer
3298        })
3299    }
3300
3301    pub fn open_local_buffer_via_lsp(
3302        &mut self,
3303        abs_path: lsp::Url,
3304        language_server_id: LanguageServerId,
3305        language_server_name: LanguageServerName,
3306        cx: &mut Context<Self>,
3307    ) -> Task<Result<Entity<Buffer>>> {
3308        self.lsp_store.update(cx, |lsp_store, cx| {
3309            lsp_store.open_local_buffer_via_lsp(
3310                abs_path,
3311                language_server_id,
3312                language_server_name,
3313                cx,
3314            )
3315        })
3316    }
3317
3318    pub fn signature_help<T: ToPointUtf16>(
3319        &self,
3320        buffer: &Entity<Buffer>,
3321        position: T,
3322        cx: &mut Context<Self>,
3323    ) -> Task<Vec<SignatureHelp>> {
3324        self.lsp_store.update(cx, |lsp_store, cx| {
3325            lsp_store.signature_help(buffer, position, cx)
3326        })
3327    }
3328
3329    pub fn hover<T: ToPointUtf16>(
3330        &self,
3331        buffer: &Entity<Buffer>,
3332        position: T,
3333        cx: &mut Context<Self>,
3334    ) -> Task<Vec<Hover>> {
3335        let position = position.to_point_utf16(buffer.read(cx));
3336        self.lsp_store
3337            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3338    }
3339
3340    pub fn linked_edit(
3341        &self,
3342        buffer: &Entity<Buffer>,
3343        position: Anchor,
3344        cx: &mut Context<Self>,
3345    ) -> Task<Result<Vec<Range<Anchor>>>> {
3346        self.lsp_store.update(cx, |lsp_store, cx| {
3347            lsp_store.linked_edit(buffer, position, cx)
3348        })
3349    }
3350
3351    pub fn completions<T: ToOffset + ToPointUtf16>(
3352        &self,
3353        buffer: &Entity<Buffer>,
3354        position: T,
3355        context: CompletionContext,
3356        cx: &mut Context<Self>,
3357    ) -> Task<Result<Option<Vec<Completion>>>> {
3358        let position = position.to_point_utf16(buffer.read(cx));
3359        self.lsp_store.update(cx, |lsp_store, cx| {
3360            lsp_store.completions(buffer, position, context, cx)
3361        })
3362    }
3363
3364    pub fn code_actions<T: Clone + ToOffset>(
3365        &mut self,
3366        buffer_handle: &Entity<Buffer>,
3367        range: Range<T>,
3368        kinds: Option<Vec<CodeActionKind>>,
3369        cx: &mut Context<Self>,
3370    ) -> Task<Result<Vec<CodeAction>>> {
3371        let buffer = buffer_handle.read(cx);
3372        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3373        self.lsp_store.update(cx, |lsp_store, cx| {
3374            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3375        })
3376    }
3377
3378    pub fn code_lens<T: Clone + ToOffset>(
3379        &mut self,
3380        buffer_handle: &Entity<Buffer>,
3381        range: Range<T>,
3382        cx: &mut Context<Self>,
3383    ) -> Task<Result<Vec<CodeAction>>> {
3384        let snapshot = buffer_handle.read(cx).snapshot();
3385        let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3386        let code_lens_actions = self
3387            .lsp_store
3388            .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3389
3390        cx.background_spawn(async move {
3391            let mut code_lens_actions = code_lens_actions.await?;
3392            code_lens_actions.retain(|code_lens_action| {
3393                range
3394                    .start
3395                    .cmp(&code_lens_action.range.start, &snapshot)
3396                    .is_ge()
3397                    && range
3398                        .end
3399                        .cmp(&code_lens_action.range.end, &snapshot)
3400                        .is_le()
3401            });
3402            Ok(code_lens_actions)
3403        })
3404    }
3405
3406    pub fn apply_code_action(
3407        &self,
3408        buffer_handle: Entity<Buffer>,
3409        action: CodeAction,
3410        push_to_history: bool,
3411        cx: &mut Context<Self>,
3412    ) -> Task<Result<ProjectTransaction>> {
3413        self.lsp_store.update(cx, |lsp_store, cx| {
3414            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3415        })
3416    }
3417
3418    pub fn apply_code_action_kind(
3419        &self,
3420        buffers: HashSet<Entity<Buffer>>,
3421        kind: CodeActionKind,
3422        push_to_history: bool,
3423        cx: &mut Context<Self>,
3424    ) -> Task<Result<ProjectTransaction>> {
3425        self.lsp_store.update(cx, |lsp_store, cx| {
3426            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3427        })
3428    }
3429
3430    fn prepare_rename_impl(
3431        &mut self,
3432        buffer: Entity<Buffer>,
3433        position: PointUtf16,
3434        cx: &mut Context<Self>,
3435    ) -> Task<Result<PrepareRenameResponse>> {
3436        self.request_lsp(
3437            buffer,
3438            LanguageServerToQuery::FirstCapable,
3439            PrepareRename { position },
3440            cx,
3441        )
3442    }
3443    pub fn prepare_rename<T: ToPointUtf16>(
3444        &mut self,
3445        buffer: Entity<Buffer>,
3446        position: T,
3447        cx: &mut Context<Self>,
3448    ) -> Task<Result<PrepareRenameResponse>> {
3449        let position = position.to_point_utf16(buffer.read(cx));
3450        self.prepare_rename_impl(buffer, position, cx)
3451    }
3452
3453    pub fn perform_rename<T: ToPointUtf16>(
3454        &mut self,
3455        buffer: Entity<Buffer>,
3456        position: T,
3457        new_name: String,
3458        cx: &mut Context<Self>,
3459    ) -> Task<Result<ProjectTransaction>> {
3460        let push_to_history = true;
3461        let position = position.to_point_utf16(buffer.read(cx));
3462        self.request_lsp(
3463            buffer,
3464            LanguageServerToQuery::FirstCapable,
3465            PerformRename {
3466                position,
3467                new_name,
3468                push_to_history,
3469            },
3470            cx,
3471        )
3472    }
3473
3474    pub fn on_type_format<T: ToPointUtf16>(
3475        &mut self,
3476        buffer: Entity<Buffer>,
3477        position: T,
3478        trigger: String,
3479        push_to_history: bool,
3480        cx: &mut Context<Self>,
3481    ) -> Task<Result<Option<Transaction>>> {
3482        self.lsp_store.update(cx, |lsp_store, cx| {
3483            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3484        })
3485    }
3486
3487    pub fn inlay_hints<T: ToOffset>(
3488        &mut self,
3489        buffer_handle: Entity<Buffer>,
3490        range: Range<T>,
3491        cx: &mut Context<Self>,
3492    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3493        let buffer = buffer_handle.read(cx);
3494        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3495        self.lsp_store.update(cx, |lsp_store, cx| {
3496            lsp_store.inlay_hints(buffer_handle, range, cx)
3497        })
3498    }
3499
3500    pub fn resolve_inlay_hint(
3501        &self,
3502        hint: InlayHint,
3503        buffer_handle: Entity<Buffer>,
3504        server_id: LanguageServerId,
3505        cx: &mut Context<Self>,
3506    ) -> Task<anyhow::Result<InlayHint>> {
3507        self.lsp_store.update(cx, |lsp_store, cx| {
3508            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3509        })
3510    }
3511
3512    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3513        let (result_tx, result_rx) = smol::channel::unbounded();
3514
3515        let matching_buffers_rx = if query.is_opened_only() {
3516            self.sort_search_candidates(&query, cx)
3517        } else {
3518            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3519        };
3520
3521        cx.spawn(async move |_, cx| {
3522            let mut range_count = 0;
3523            let mut buffer_count = 0;
3524            let mut limit_reached = false;
3525            let query = Arc::new(query);
3526            let mut chunks = matching_buffers_rx.ready_chunks(64);
3527
3528            // Now that we know what paths match the query, we will load at most
3529            // 64 buffers at a time to avoid overwhelming the main thread. For each
3530            // opened buffer, we will spawn a background task that retrieves all the
3531            // ranges in the buffer matched by the query.
3532            let mut chunks = pin!(chunks);
3533            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3534                let mut chunk_results = Vec::new();
3535                for buffer in matching_buffer_chunk {
3536                    let buffer = buffer.clone();
3537                    let query = query.clone();
3538                    let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3539                    chunk_results.push(cx.background_spawn(async move {
3540                        let ranges = query
3541                            .search(&snapshot, None)
3542                            .await
3543                            .iter()
3544                            .map(|range| {
3545                                snapshot.anchor_before(range.start)
3546                                    ..snapshot.anchor_after(range.end)
3547                            })
3548                            .collect::<Vec<_>>();
3549                        anyhow::Ok((buffer, ranges))
3550                    }));
3551                }
3552
3553                let chunk_results = futures::future::join_all(chunk_results).await;
3554                for result in chunk_results {
3555                    if let Some((buffer, ranges)) = result.log_err() {
3556                        range_count += ranges.len();
3557                        buffer_count += 1;
3558                        result_tx
3559                            .send(SearchResult::Buffer { buffer, ranges })
3560                            .await?;
3561                        if buffer_count > MAX_SEARCH_RESULT_FILES
3562                            || range_count > MAX_SEARCH_RESULT_RANGES
3563                        {
3564                            limit_reached = true;
3565                            break 'outer;
3566                        }
3567                    }
3568                }
3569            }
3570
3571            if limit_reached {
3572                result_tx.send(SearchResult::LimitReached).await?;
3573            }
3574
3575            anyhow::Ok(())
3576        })
3577        .detach();
3578
3579        result_rx
3580    }
3581
3582    fn find_search_candidate_buffers(
3583        &mut self,
3584        query: &SearchQuery,
3585        limit: usize,
3586        cx: &mut Context<Project>,
3587    ) -> Receiver<Entity<Buffer>> {
3588        if self.is_local() {
3589            let fs = self.fs.clone();
3590            self.buffer_store.update(cx, |buffer_store, cx| {
3591                buffer_store.find_search_candidates(query, limit, fs, cx)
3592            })
3593        } else {
3594            self.find_search_candidates_remote(query, limit, cx)
3595        }
3596    }
3597
3598    fn sort_search_candidates(
3599        &mut self,
3600        search_query: &SearchQuery,
3601        cx: &mut Context<Project>,
3602    ) -> Receiver<Entity<Buffer>> {
3603        let worktree_store = self.worktree_store.read(cx);
3604        let mut buffers = search_query
3605            .buffers()
3606            .into_iter()
3607            .flatten()
3608            .filter(|buffer| {
3609                let b = buffer.read(cx);
3610                if let Some(file) = b.file() {
3611                    if !search_query.match_path(file.path()) {
3612                        return false;
3613                    }
3614                    if let Some(entry) = b
3615                        .entry_id(cx)
3616                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3617                    {
3618                        if entry.is_ignored && !search_query.include_ignored() {
3619                            return false;
3620                        }
3621                    }
3622                }
3623                true
3624            })
3625            .collect::<Vec<_>>();
3626        let (tx, rx) = smol::channel::unbounded();
3627        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3628            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3629            (None, Some(_)) => std::cmp::Ordering::Less,
3630            (Some(_), None) => std::cmp::Ordering::Greater,
3631            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3632        });
3633        for buffer in buffers {
3634            tx.send_blocking(buffer.clone()).unwrap()
3635        }
3636
3637        rx
3638    }
3639
3640    fn find_search_candidates_remote(
3641        &mut self,
3642        query: &SearchQuery,
3643        limit: usize,
3644        cx: &mut Context<Project>,
3645    ) -> Receiver<Entity<Buffer>> {
3646        let (tx, rx) = smol::channel::unbounded();
3647
3648        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3649            (ssh_client.read(cx).proto_client(), 0)
3650        } else if let Some(remote_id) = self.remote_id() {
3651            (self.client.clone().into(), remote_id)
3652        } else {
3653            return rx;
3654        };
3655
3656        let request = client.request(proto::FindSearchCandidates {
3657            project_id: remote_id,
3658            query: Some(query.to_proto()),
3659            limit: limit as _,
3660        });
3661        let guard = self.retain_remotely_created_models(cx);
3662
3663        cx.spawn(async move |project, cx| {
3664            let response = request.await?;
3665            for buffer_id in response.buffer_ids {
3666                let buffer_id = BufferId::new(buffer_id)?;
3667                let buffer = project
3668                    .update(cx, |project, cx| {
3669                        project.buffer_store.update(cx, |buffer_store, cx| {
3670                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3671                        })
3672                    })?
3673                    .await?;
3674                let _ = tx.send(buffer).await;
3675            }
3676
3677            drop(guard);
3678            anyhow::Ok(())
3679        })
3680        .detach_and_log_err(cx);
3681        rx
3682    }
3683
3684    pub fn request_lsp<R: LspCommand>(
3685        &mut self,
3686        buffer_handle: Entity<Buffer>,
3687        server: LanguageServerToQuery,
3688        request: R,
3689        cx: &mut Context<Self>,
3690    ) -> Task<Result<R::Response>>
3691    where
3692        <R::LspRequest as lsp::request::Request>::Result: Send,
3693        <R::LspRequest as lsp::request::Request>::Params: Send,
3694    {
3695        let guard = self.retain_remotely_created_models(cx);
3696        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3697            lsp_store.request_lsp(buffer_handle, server, request, cx)
3698        });
3699        cx.spawn(async move |_, _| {
3700            let result = task.await;
3701            drop(guard);
3702            result
3703        })
3704    }
3705
3706    /// Move a worktree to a new position in the worktree order.
3707    ///
3708    /// The worktree will moved to the opposite side of the destination worktree.
3709    ///
3710    /// # Example
3711    ///
3712    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3713    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3714    ///
3715    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3716    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3717    ///
3718    /// # Errors
3719    ///
3720    /// An error will be returned if the worktree or destination worktree are not found.
3721    pub fn move_worktree(
3722        &mut self,
3723        source: WorktreeId,
3724        destination: WorktreeId,
3725        cx: &mut Context<Self>,
3726    ) -> Result<()> {
3727        self.worktree_store.update(cx, |worktree_store, cx| {
3728            worktree_store.move_worktree(source, destination, cx)
3729        })
3730    }
3731
3732    pub fn find_or_create_worktree(
3733        &mut self,
3734        abs_path: impl AsRef<Path>,
3735        visible: bool,
3736        cx: &mut Context<Self>,
3737    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3738        self.worktree_store.update(cx, |worktree_store, cx| {
3739            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3740        })
3741    }
3742
3743    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3744        self.worktree_store.read_with(cx, |worktree_store, cx| {
3745            worktree_store.find_worktree(abs_path, cx)
3746        })
3747    }
3748
3749    pub fn is_shared(&self) -> bool {
3750        match &self.client_state {
3751            ProjectClientState::Shared { .. } => true,
3752            ProjectClientState::Local => false,
3753            ProjectClientState::Remote { .. } => true,
3754        }
3755    }
3756
3757    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3758    pub fn resolve_path_in_buffer(
3759        &self,
3760        path: &str,
3761        buffer: &Entity<Buffer>,
3762        cx: &mut Context<Self>,
3763    ) -> Task<Option<ResolvedPath>> {
3764        let path_buf = PathBuf::from(path);
3765        if path_buf.is_absolute() || path.starts_with("~") {
3766            self.resolve_abs_path(path, cx)
3767        } else {
3768            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3769        }
3770    }
3771
3772    pub fn resolve_abs_file_path(
3773        &self,
3774        path: &str,
3775        cx: &mut Context<Self>,
3776    ) -> Task<Option<ResolvedPath>> {
3777        let resolve_task = self.resolve_abs_path(path, cx);
3778        cx.background_spawn(async move {
3779            let resolved_path = resolve_task.await;
3780            resolved_path.filter(|path| path.is_file())
3781        })
3782    }
3783
3784    pub fn resolve_abs_path(
3785        &self,
3786        path: &str,
3787        cx: &mut Context<Self>,
3788    ) -> Task<Option<ResolvedPath>> {
3789        if self.is_local() {
3790            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3791            let fs = self.fs.clone();
3792            cx.background_spawn(async move {
3793                let path = expanded.as_path();
3794                let metadata = fs.metadata(path).await.ok().flatten();
3795
3796                metadata.map(|metadata| ResolvedPath::AbsPath {
3797                    path: expanded,
3798                    is_dir: metadata.is_dir,
3799                })
3800            })
3801        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3802            let request_path = Path::new(path);
3803            let request = ssh_client
3804                .read(cx)
3805                .proto_client()
3806                .request(proto::GetPathMetadata {
3807                    project_id: SSH_PROJECT_ID,
3808                    path: request_path.to_proto(),
3809                });
3810            cx.background_spawn(async move {
3811                let response = request.await.log_err()?;
3812                if response.exists {
3813                    Some(ResolvedPath::AbsPath {
3814                        path: PathBuf::from_proto(response.path),
3815                        is_dir: response.is_dir,
3816                    })
3817                } else {
3818                    None
3819                }
3820            })
3821        } else {
3822            return Task::ready(None);
3823        }
3824    }
3825
3826    fn resolve_path_in_worktrees(
3827        &self,
3828        path: PathBuf,
3829        buffer: &Entity<Buffer>,
3830        cx: &mut Context<Self>,
3831    ) -> Task<Option<ResolvedPath>> {
3832        let mut candidates = vec![path.clone()];
3833
3834        if let Some(file) = buffer.read(cx).file() {
3835            if let Some(dir) = file.path().parent() {
3836                let joined = dir.to_path_buf().join(path);
3837                candidates.push(joined);
3838            }
3839        }
3840
3841        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3842        let worktrees_with_ids: Vec<_> = self
3843            .worktrees(cx)
3844            .map(|worktree| {
3845                let id = worktree.read(cx).id();
3846                (worktree, id)
3847            })
3848            .collect();
3849
3850        cx.spawn(async move |_, mut cx| {
3851            if let Some(buffer_worktree_id) = buffer_worktree_id {
3852                if let Some((worktree, _)) = worktrees_with_ids
3853                    .iter()
3854                    .find(|(_, id)| *id == buffer_worktree_id)
3855                {
3856                    for candidate in candidates.iter() {
3857                        if let Some(path) =
3858                            Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3859                        {
3860                            return Some(path);
3861                        }
3862                    }
3863                }
3864            }
3865            for (worktree, id) in worktrees_with_ids {
3866                if Some(id) == buffer_worktree_id {
3867                    continue;
3868                }
3869                for candidate in candidates.iter() {
3870                    if let Some(path) =
3871                        Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3872                    {
3873                        return Some(path);
3874                    }
3875                }
3876            }
3877            None
3878        })
3879    }
3880
3881    fn resolve_path_in_worktree(
3882        worktree: &Entity<Worktree>,
3883        path: &PathBuf,
3884        cx: &mut AsyncApp,
3885    ) -> Option<ResolvedPath> {
3886        worktree
3887            .update(cx, |worktree, _| {
3888                let root_entry_path = &worktree.root_entry()?.path;
3889                let resolved = resolve_path(root_entry_path, path);
3890                let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
3891                worktree.entry_for_path(stripped).map(|entry| {
3892                    let project_path = ProjectPath {
3893                        worktree_id: worktree.id(),
3894                        path: entry.path.clone(),
3895                    };
3896                    ResolvedPath::ProjectPath {
3897                        project_path,
3898                        is_dir: entry.is_dir(),
3899                    }
3900                })
3901            })
3902            .ok()?
3903    }
3904
3905    pub fn list_directory(
3906        &self,
3907        query: String,
3908        cx: &mut Context<Self>,
3909    ) -> Task<Result<Vec<DirectoryItem>>> {
3910        if self.is_local() {
3911            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
3912        } else if let Some(session) = self.ssh_client.as_ref() {
3913            let path_buf = PathBuf::from(query);
3914            let request = proto::ListRemoteDirectory {
3915                dev_server_id: SSH_PROJECT_ID,
3916                path: path_buf.to_proto(),
3917                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
3918            };
3919
3920            let response = session.read(cx).proto_client().request(request);
3921            cx.background_spawn(async move {
3922                let proto::ListRemoteDirectoryResponse {
3923                    entries,
3924                    entry_info,
3925                } = response.await?;
3926                Ok(entries
3927                    .into_iter()
3928                    .zip(entry_info)
3929                    .map(|(entry, info)| DirectoryItem {
3930                        path: PathBuf::from(entry),
3931                        is_dir: info.is_dir,
3932                    })
3933                    .collect())
3934            })
3935        } else {
3936            Task::ready(Err(anyhow!("cannot list directory in remote project")))
3937        }
3938    }
3939
3940    pub fn create_worktree(
3941        &mut self,
3942        abs_path: impl AsRef<Path>,
3943        visible: bool,
3944        cx: &mut Context<Self>,
3945    ) -> Task<Result<Entity<Worktree>>> {
3946        self.worktree_store.update(cx, |worktree_store, cx| {
3947            worktree_store.create_worktree(abs_path, visible, cx)
3948        })
3949    }
3950
3951    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3952        self.worktree_store.update(cx, |worktree_store, cx| {
3953            worktree_store.remove_worktree(id_to_remove, cx);
3954        });
3955    }
3956
3957    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
3958        self.worktree_store.update(cx, |worktree_store, cx| {
3959            worktree_store.add(worktree, cx);
3960        });
3961    }
3962
3963    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
3964        let new_active_entry = entry.and_then(|project_path| {
3965            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
3966            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
3967            Some(entry.id)
3968        });
3969        if new_active_entry != self.active_entry {
3970            self.active_entry = new_active_entry;
3971            self.lsp_store.update(cx, |lsp_store, _| {
3972                lsp_store.set_active_entry(new_active_entry);
3973            });
3974            cx.emit(Event::ActiveEntryChanged(new_active_entry));
3975        }
3976    }
3977
3978    pub fn language_servers_running_disk_based_diagnostics<'a>(
3979        &'a self,
3980        cx: &'a App,
3981    ) -> impl Iterator<Item = LanguageServerId> + 'a {
3982        self.lsp_store
3983            .read(cx)
3984            .language_servers_running_disk_based_diagnostics()
3985    }
3986
3987    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
3988        self.lsp_store
3989            .read(cx)
3990            .diagnostic_summary(include_ignored, cx)
3991    }
3992
3993    pub fn diagnostic_summaries<'a>(
3994        &'a self,
3995        include_ignored: bool,
3996        cx: &'a App,
3997    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
3998        self.lsp_store
3999            .read(cx)
4000            .diagnostic_summaries(include_ignored, cx)
4001    }
4002
4003    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4004        self.active_entry
4005    }
4006
4007    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4008        self.worktree_store.read(cx).entry_for_path(path, cx)
4009    }
4010
4011    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4012        let worktree = self.worktree_for_entry(entry_id, cx)?;
4013        let worktree = worktree.read(cx);
4014        let worktree_id = worktree.id();
4015        let path = worktree.entry_for_id(entry_id)?.path.clone();
4016        Some(ProjectPath { worktree_id, path })
4017    }
4018
4019    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4020        self.worktree_for_id(project_path.worktree_id, cx)?
4021            .read(cx)
4022            .absolutize(&project_path.path)
4023            .ok()
4024    }
4025
4026    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4027    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4028    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4029    /// the first visible worktree that has an entry for that relative path.
4030    ///
4031    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4032    /// root name from paths.
4033    ///
4034    /// # Arguments
4035    ///
4036    /// * `path` - A full path that starts with a worktree root name, or alternatively a
4037    ///            relative path within a visible worktree.
4038    /// * `cx` - A reference to the `AppContext`.
4039    ///
4040    /// # Returns
4041    ///
4042    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4043    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4044        let path = path.as_ref();
4045        let worktree_store = self.worktree_store.read(cx);
4046
4047        for worktree in worktree_store.visible_worktrees(cx) {
4048            let worktree_root_name = worktree.read(cx).root_name();
4049            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4050                return Some(ProjectPath {
4051                    worktree_id: worktree.read(cx).id(),
4052                    path: relative_path.into(),
4053                });
4054            }
4055        }
4056
4057        for worktree in worktree_store.visible_worktrees(cx) {
4058            let worktree = worktree.read(cx);
4059            if let Some(entry) = worktree.entry_for_path(path) {
4060                return Some(ProjectPath {
4061                    worktree_id: worktree.id(),
4062                    path: entry.path.clone(),
4063                });
4064            }
4065        }
4066
4067        None
4068    }
4069
4070    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4071        self.find_worktree(abs_path, cx)
4072            .map(|(worktree, relative_path)| ProjectPath {
4073                worktree_id: worktree.read(cx).id(),
4074                path: relative_path.into(),
4075            })
4076    }
4077
4078    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4079        Some(
4080            self.worktree_for_id(project_path.worktree_id, cx)?
4081                .read(cx)
4082                .abs_path()
4083                .to_path_buf(),
4084        )
4085    }
4086
4087    pub fn blame_buffer(
4088        &self,
4089        buffer: &Entity<Buffer>,
4090        version: Option<clock::Global>,
4091        cx: &mut App,
4092    ) -> Task<Result<Option<Blame>>> {
4093        self.git_store.update(cx, |git_store, cx| {
4094            git_store.blame_buffer(buffer, version, cx)
4095        })
4096    }
4097
4098    pub fn get_permalink_to_line(
4099        &self,
4100        buffer: &Entity<Buffer>,
4101        selection: Range<u32>,
4102        cx: &mut App,
4103    ) -> Task<Result<url::Url>> {
4104        self.git_store.update(cx, |git_store, cx| {
4105            git_store.get_permalink_to_line(buffer, selection, cx)
4106        })
4107    }
4108
4109    // RPC message handlers
4110
4111    async fn handle_unshare_project(
4112        this: Entity<Self>,
4113        _: TypedEnvelope<proto::UnshareProject>,
4114        mut cx: AsyncApp,
4115    ) -> Result<()> {
4116        this.update(&mut cx, |this, cx| {
4117            if this.is_local() || this.is_via_ssh() {
4118                this.unshare(cx)?;
4119            } else {
4120                this.disconnected_from_host(cx);
4121            }
4122            Ok(())
4123        })?
4124    }
4125
4126    async fn handle_add_collaborator(
4127        this: Entity<Self>,
4128        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4129        mut cx: AsyncApp,
4130    ) -> Result<()> {
4131        let collaborator = envelope
4132            .payload
4133            .collaborator
4134            .take()
4135            .ok_or_else(|| anyhow!("empty collaborator"))?;
4136
4137        let collaborator = Collaborator::from_proto(collaborator)?;
4138        this.update(&mut cx, |this, cx| {
4139            this.buffer_store.update(cx, |buffer_store, _| {
4140                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4141            });
4142            this.breakpoint_store.read(cx).broadcast();
4143            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4144            this.collaborators
4145                .insert(collaborator.peer_id, collaborator);
4146        })?;
4147
4148        Ok(())
4149    }
4150
4151    async fn handle_update_project_collaborator(
4152        this: Entity<Self>,
4153        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4154        mut cx: AsyncApp,
4155    ) -> Result<()> {
4156        let old_peer_id = envelope
4157            .payload
4158            .old_peer_id
4159            .ok_or_else(|| anyhow!("missing old peer id"))?;
4160        let new_peer_id = envelope
4161            .payload
4162            .new_peer_id
4163            .ok_or_else(|| anyhow!("missing new peer id"))?;
4164        this.update(&mut cx, |this, cx| {
4165            let collaborator = this
4166                .collaborators
4167                .remove(&old_peer_id)
4168                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4169            let is_host = collaborator.is_host;
4170            this.collaborators.insert(new_peer_id, collaborator);
4171
4172            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4173            this.buffer_store.update(cx, |buffer_store, _| {
4174                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4175            });
4176
4177            if is_host {
4178                this.buffer_store
4179                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4180                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4181                    .unwrap();
4182                cx.emit(Event::HostReshared);
4183            }
4184
4185            cx.emit(Event::CollaboratorUpdated {
4186                old_peer_id,
4187                new_peer_id,
4188            });
4189            Ok(())
4190        })?
4191    }
4192
4193    async fn handle_remove_collaborator(
4194        this: Entity<Self>,
4195        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4196        mut cx: AsyncApp,
4197    ) -> Result<()> {
4198        this.update(&mut cx, |this, cx| {
4199            let peer_id = envelope
4200                .payload
4201                .peer_id
4202                .ok_or_else(|| anyhow!("invalid peer id"))?;
4203            let replica_id = this
4204                .collaborators
4205                .remove(&peer_id)
4206                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4207                .replica_id;
4208            this.buffer_store.update(cx, |buffer_store, cx| {
4209                buffer_store.forget_shared_buffers_for(&peer_id);
4210                for buffer in buffer_store.buffers() {
4211                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4212                }
4213            });
4214            this.git_store.update(cx, |git_store, _| {
4215                git_store.forget_shared_diffs_for(&peer_id);
4216            });
4217
4218            cx.emit(Event::CollaboratorLeft(peer_id));
4219            Ok(())
4220        })?
4221    }
4222
4223    async fn handle_update_project(
4224        this: Entity<Self>,
4225        envelope: TypedEnvelope<proto::UpdateProject>,
4226        mut cx: AsyncApp,
4227    ) -> Result<()> {
4228        this.update(&mut cx, |this, cx| {
4229            // Don't handle messages that were sent before the response to us joining the project
4230            if envelope.message_id > this.join_project_response_message_id {
4231                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4232            }
4233            Ok(())
4234        })?
4235    }
4236
4237    async fn handle_toast(
4238        this: Entity<Self>,
4239        envelope: TypedEnvelope<proto::Toast>,
4240        mut cx: AsyncApp,
4241    ) -> Result<()> {
4242        this.update(&mut cx, |_, cx| {
4243            cx.emit(Event::Toast {
4244                notification_id: envelope.payload.notification_id.into(),
4245                message: envelope.payload.message,
4246            });
4247            Ok(())
4248        })?
4249    }
4250
4251    async fn handle_language_server_prompt_request(
4252        this: Entity<Self>,
4253        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4254        mut cx: AsyncApp,
4255    ) -> Result<proto::LanguageServerPromptResponse> {
4256        let (tx, mut rx) = smol::channel::bounded(1);
4257        let actions: Vec<_> = envelope
4258            .payload
4259            .actions
4260            .into_iter()
4261            .map(|action| MessageActionItem {
4262                title: action,
4263                properties: Default::default(),
4264            })
4265            .collect();
4266        this.update(&mut cx, |_, cx| {
4267            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4268                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4269                message: envelope.payload.message,
4270                actions: actions.clone(),
4271                lsp_name: envelope.payload.lsp_name,
4272                response_channel: tx,
4273            }));
4274
4275            anyhow::Ok(())
4276        })??;
4277
4278        // We drop `this` to avoid holding a reference in this future for too
4279        // long.
4280        // If we keep the reference, we might not drop the `Project` early
4281        // enough when closing a window and it will only get releases on the
4282        // next `flush_effects()` call.
4283        drop(this);
4284
4285        let mut rx = pin!(rx);
4286        let answer = rx.next().await;
4287
4288        Ok(LanguageServerPromptResponse {
4289            action_response: answer.and_then(|answer| {
4290                actions
4291                    .iter()
4292                    .position(|action| *action == answer)
4293                    .map(|index| index as u64)
4294            }),
4295        })
4296    }
4297
4298    async fn handle_hide_toast(
4299        this: Entity<Self>,
4300        envelope: TypedEnvelope<proto::HideToast>,
4301        mut cx: AsyncApp,
4302    ) -> Result<()> {
4303        this.update(&mut cx, |_, cx| {
4304            cx.emit(Event::HideToast {
4305                notification_id: envelope.payload.notification_id.into(),
4306            });
4307            Ok(())
4308        })?
4309    }
4310
4311    // Collab sends UpdateWorktree protos as messages
4312    async fn handle_update_worktree(
4313        this: Entity<Self>,
4314        envelope: TypedEnvelope<proto::UpdateWorktree>,
4315        mut cx: AsyncApp,
4316    ) -> Result<()> {
4317        this.update(&mut cx, |this, cx| {
4318            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4319            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4320                worktree.update(cx, |worktree, _| {
4321                    let worktree = worktree.as_remote_mut().unwrap();
4322                    worktree.update_from_remote(envelope.payload);
4323                });
4324            }
4325            Ok(())
4326        })?
4327    }
4328
4329    async fn handle_update_buffer_from_ssh(
4330        this: Entity<Self>,
4331        envelope: TypedEnvelope<proto::UpdateBuffer>,
4332        cx: AsyncApp,
4333    ) -> Result<proto::Ack> {
4334        let buffer_store = this.read_with(&cx, |this, cx| {
4335            if let Some(remote_id) = this.remote_id() {
4336                let mut payload = envelope.payload.clone();
4337                payload.project_id = remote_id;
4338                cx.background_spawn(this.client.request(payload))
4339                    .detach_and_log_err(cx);
4340            }
4341            this.buffer_store.clone()
4342        })?;
4343        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4344    }
4345
4346    async fn handle_update_buffer(
4347        this: Entity<Self>,
4348        envelope: TypedEnvelope<proto::UpdateBuffer>,
4349        cx: AsyncApp,
4350    ) -> Result<proto::Ack> {
4351        let buffer_store = this.read_with(&cx, |this, cx| {
4352            if let Some(ssh) = &this.ssh_client {
4353                let mut payload = envelope.payload.clone();
4354                payload.project_id = SSH_PROJECT_ID;
4355                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4356                    .detach_and_log_err(cx);
4357            }
4358            this.buffer_store.clone()
4359        })?;
4360        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4361    }
4362
4363    fn retain_remotely_created_models(
4364        &mut self,
4365        cx: &mut Context<Self>,
4366    ) -> RemotelyCreatedModelGuard {
4367        {
4368            let mut remotely_create_models = self.remotely_created_models.lock();
4369            if remotely_create_models.retain_count == 0 {
4370                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4371                remotely_create_models.worktrees =
4372                    self.worktree_store.read(cx).worktrees().collect();
4373            }
4374            remotely_create_models.retain_count += 1;
4375        }
4376        RemotelyCreatedModelGuard {
4377            remote_models: Arc::downgrade(&self.remotely_created_models),
4378        }
4379    }
4380
4381    async fn handle_create_buffer_for_peer(
4382        this: Entity<Self>,
4383        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4384        mut cx: AsyncApp,
4385    ) -> Result<()> {
4386        this.update(&mut cx, |this, cx| {
4387            this.buffer_store.update(cx, |buffer_store, cx| {
4388                buffer_store.handle_create_buffer_for_peer(
4389                    envelope,
4390                    this.replica_id(),
4391                    this.capability(),
4392                    cx,
4393                )
4394            })
4395        })?
4396    }
4397
4398    async fn handle_synchronize_buffers(
4399        this: Entity<Self>,
4400        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4401        mut cx: AsyncApp,
4402    ) -> Result<proto::SynchronizeBuffersResponse> {
4403        let response = this.update(&mut cx, |this, cx| {
4404            let client = this.client.clone();
4405            this.buffer_store.update(cx, |this, cx| {
4406                this.handle_synchronize_buffers(envelope, cx, client)
4407            })
4408        })??;
4409
4410        Ok(response)
4411    }
4412
4413    async fn handle_search_candidate_buffers(
4414        this: Entity<Self>,
4415        envelope: TypedEnvelope<proto::FindSearchCandidates>,
4416        mut cx: AsyncApp,
4417    ) -> Result<proto::FindSearchCandidatesResponse> {
4418        let peer_id = envelope.original_sender_id()?;
4419        let message = envelope.payload;
4420        let query = SearchQuery::from_proto(
4421            message
4422                .query
4423                .ok_or_else(|| anyhow!("missing query field"))?,
4424        )?;
4425        let results = this.update(&mut cx, |this, cx| {
4426            this.find_search_candidate_buffers(&query, message.limit as _, cx)
4427        })?;
4428
4429        let mut response = proto::FindSearchCandidatesResponse {
4430            buffer_ids: Vec::new(),
4431        };
4432
4433        while let Ok(buffer) = results.recv().await {
4434            this.update(&mut cx, |this, cx| {
4435                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4436                response.buffer_ids.push(buffer_id.to_proto());
4437            })?;
4438        }
4439
4440        Ok(response)
4441    }
4442
4443    async fn handle_open_buffer_by_id(
4444        this: Entity<Self>,
4445        envelope: TypedEnvelope<proto::OpenBufferById>,
4446        mut cx: AsyncApp,
4447    ) -> Result<proto::OpenBufferResponse> {
4448        let peer_id = envelope.original_sender_id()?;
4449        let buffer_id = BufferId::new(envelope.payload.id)?;
4450        let buffer = this
4451            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4452            .await?;
4453        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4454    }
4455
4456    async fn handle_open_buffer_by_path(
4457        this: Entity<Self>,
4458        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4459        mut cx: AsyncApp,
4460    ) -> Result<proto::OpenBufferResponse> {
4461        let peer_id = envelope.original_sender_id()?;
4462        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4463        let open_buffer = this.update(&mut cx, |this, cx| {
4464            this.open_buffer(
4465                ProjectPath {
4466                    worktree_id,
4467                    path: Arc::<Path>::from_proto(envelope.payload.path),
4468                },
4469                cx,
4470            )
4471        })?;
4472
4473        let buffer = open_buffer.await?;
4474        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4475    }
4476
4477    async fn handle_open_new_buffer(
4478        this: Entity<Self>,
4479        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4480        mut cx: AsyncApp,
4481    ) -> Result<proto::OpenBufferResponse> {
4482        let buffer = this
4483            .update(&mut cx, |this, cx| this.create_buffer(cx))?
4484            .await?;
4485        let peer_id = envelope.original_sender_id()?;
4486
4487        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4488    }
4489
4490    fn respond_to_open_buffer_request(
4491        this: Entity<Self>,
4492        buffer: Entity<Buffer>,
4493        peer_id: proto::PeerId,
4494        cx: &mut AsyncApp,
4495    ) -> Result<proto::OpenBufferResponse> {
4496        this.update(cx, |this, cx| {
4497            let is_private = buffer
4498                .read(cx)
4499                .file()
4500                .map(|f| f.is_private())
4501                .unwrap_or_default();
4502            if is_private {
4503                Err(anyhow!(ErrorCode::UnsharedItem))
4504            } else {
4505                Ok(proto::OpenBufferResponse {
4506                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4507                })
4508            }
4509        })?
4510    }
4511
4512    fn create_buffer_for_peer(
4513        &mut self,
4514        buffer: &Entity<Buffer>,
4515        peer_id: proto::PeerId,
4516        cx: &mut App,
4517    ) -> BufferId {
4518        self.buffer_store
4519            .update(cx, |buffer_store, cx| {
4520                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4521            })
4522            .detach_and_log_err(cx);
4523        buffer.read(cx).remote_id()
4524    }
4525
4526    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4527        let project_id = match self.client_state {
4528            ProjectClientState::Remote {
4529                sharing_has_stopped,
4530                remote_id,
4531                ..
4532            } => {
4533                if sharing_has_stopped {
4534                    return Task::ready(Err(anyhow!(
4535                        "can't synchronize remote buffers on a readonly project"
4536                    )));
4537                } else {
4538                    remote_id
4539                }
4540            }
4541            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4542                return Task::ready(Err(anyhow!(
4543                    "can't synchronize remote buffers on a local project"
4544                )));
4545            }
4546        };
4547
4548        let client = self.client.clone();
4549        cx.spawn(async move |this, cx| {
4550            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4551                this.buffer_store.read(cx).buffer_version_info(cx)
4552            })?;
4553            let response = client
4554                .request(proto::SynchronizeBuffers {
4555                    project_id,
4556                    buffers,
4557                })
4558                .await?;
4559
4560            let send_updates_for_buffers = this.update(cx, |this, cx| {
4561                response
4562                    .buffers
4563                    .into_iter()
4564                    .map(|buffer| {
4565                        let client = client.clone();
4566                        let buffer_id = match BufferId::new(buffer.id) {
4567                            Ok(id) => id,
4568                            Err(e) => {
4569                                return Task::ready(Err(e));
4570                            }
4571                        };
4572                        let remote_version = language::proto::deserialize_version(&buffer.version);
4573                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4574                            let operations =
4575                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4576                            cx.background_spawn(async move {
4577                                let operations = operations.await;
4578                                for chunk in split_operations(operations) {
4579                                    client
4580                                        .request(proto::UpdateBuffer {
4581                                            project_id,
4582                                            buffer_id: buffer_id.into(),
4583                                            operations: chunk,
4584                                        })
4585                                        .await?;
4586                                }
4587                                anyhow::Ok(())
4588                            })
4589                        } else {
4590                            Task::ready(Ok(()))
4591                        }
4592                    })
4593                    .collect::<Vec<_>>()
4594            })?;
4595
4596            // Any incomplete buffers have open requests waiting. Request that the host sends
4597            // creates these buffers for us again to unblock any waiting futures.
4598            for id in incomplete_buffer_ids {
4599                cx.background_spawn(client.request(proto::OpenBufferById {
4600                    project_id,
4601                    id: id.into(),
4602                }))
4603                .detach();
4604            }
4605
4606            futures::future::join_all(send_updates_for_buffers)
4607                .await
4608                .into_iter()
4609                .collect()
4610        })
4611    }
4612
4613    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4614        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4615    }
4616
4617    /// Iterator of all open buffers that have unsaved changes
4618    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4619        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4620            let buf = buf.read(cx);
4621            if buf.is_dirty() {
4622                buf.project_path(cx)
4623            } else {
4624                None
4625            }
4626        })
4627    }
4628
4629    fn set_worktrees_from_proto(
4630        &mut self,
4631        worktrees: Vec<proto::WorktreeMetadata>,
4632        cx: &mut Context<Project>,
4633    ) -> Result<()> {
4634        self.worktree_store.update(cx, |worktree_store, cx| {
4635            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4636        })
4637    }
4638
4639    fn set_collaborators_from_proto(
4640        &mut self,
4641        messages: Vec<proto::Collaborator>,
4642        cx: &mut Context<Self>,
4643    ) -> Result<()> {
4644        let mut collaborators = HashMap::default();
4645        for message in messages {
4646            let collaborator = Collaborator::from_proto(message)?;
4647            collaborators.insert(collaborator.peer_id, collaborator);
4648        }
4649        for old_peer_id in self.collaborators.keys() {
4650            if !collaborators.contains_key(old_peer_id) {
4651                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4652            }
4653        }
4654        self.collaborators = collaborators;
4655        Ok(())
4656    }
4657
4658    pub fn supplementary_language_servers<'a>(
4659        &'a self,
4660        cx: &'a App,
4661    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4662        self.lsp_store.read(cx).supplementary_language_servers()
4663    }
4664
4665    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4666        self.lsp_store.update(cx, |this, cx| {
4667            this.language_servers_for_local_buffer(buffer, cx)
4668                .any(
4669                    |(_, server)| match server.capabilities().inlay_hint_provider {
4670                        Some(lsp::OneOf::Left(enabled)) => enabled,
4671                        Some(lsp::OneOf::Right(_)) => true,
4672                        None => false,
4673                    },
4674                )
4675        })
4676    }
4677
4678    pub fn language_server_id_for_name(
4679        &self,
4680        buffer: &Buffer,
4681        name: &str,
4682        cx: &mut App,
4683    ) -> Task<Option<LanguageServerId>> {
4684        if self.is_local() {
4685            Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4686                lsp_store
4687                    .language_servers_for_local_buffer(buffer, cx)
4688                    .find_map(|(adapter, server)| {
4689                        if adapter.name.0 == name {
4690                            Some(server.server_id())
4691                        } else {
4692                            None
4693                        }
4694                    })
4695            }))
4696        } else if let Some(project_id) = self.remote_id() {
4697            let request = self.client.request(proto::LanguageServerIdForName {
4698                project_id,
4699                buffer_id: buffer.remote_id().to_proto(),
4700                name: name.to_string(),
4701            });
4702            cx.background_spawn(async move {
4703                let response = request.await.log_err()?;
4704                response.server_id.map(LanguageServerId::from_proto)
4705            })
4706        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4707            let request =
4708                ssh_client
4709                    .read(cx)
4710                    .proto_client()
4711                    .request(proto::LanguageServerIdForName {
4712                        project_id: SSH_PROJECT_ID,
4713                        buffer_id: buffer.remote_id().to_proto(),
4714                        name: name.to_string(),
4715                    });
4716            cx.background_spawn(async move {
4717                let response = request.await.log_err()?;
4718                response.server_id.map(LanguageServerId::from_proto)
4719            })
4720        } else {
4721            Task::ready(None)
4722        }
4723    }
4724
4725    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4726        self.lsp_store.update(cx, |this, cx| {
4727            this.language_servers_for_local_buffer(buffer, cx)
4728                .next()
4729                .is_some()
4730        })
4731    }
4732
4733    pub fn git_init(
4734        &self,
4735        path: Arc<Path>,
4736        fallback_branch_name: String,
4737        cx: &App,
4738    ) -> Task<Result<()>> {
4739        self.git_store
4740            .read(cx)
4741            .git_init(path, fallback_branch_name, cx)
4742    }
4743
4744    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4745        &self.buffer_store
4746    }
4747
4748    pub fn git_store(&self) -> &Entity<GitStore> {
4749        &self.git_store
4750    }
4751
4752    #[cfg(test)]
4753    fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4754        cx.spawn(async move |this, cx| {
4755            let scans_complete = this
4756                .read_with(cx, |this, cx| {
4757                    this.worktrees(cx)
4758                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4759                        .collect::<Vec<_>>()
4760                })
4761                .unwrap();
4762            join_all(scans_complete).await;
4763            let barriers = this
4764                .update(cx, |this, cx| {
4765                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4766                    repos
4767                        .into_iter()
4768                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4769                        .collect::<Vec<_>>()
4770                })
4771                .unwrap();
4772            join_all(barriers).await;
4773        })
4774    }
4775
4776    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4777        self.git_store.read(cx).active_repository()
4778    }
4779
4780    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4781        self.git_store.read(cx).repositories()
4782    }
4783
4784    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4785        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4786    }
4787}
4788
4789pub struct PathMatchCandidateSet {
4790    pub snapshot: Snapshot,
4791    pub include_ignored: bool,
4792    pub include_root_name: bool,
4793    pub candidates: Candidates,
4794}
4795
4796pub enum Candidates {
4797    /// Only consider directories.
4798    Directories,
4799    /// Only consider files.
4800    Files,
4801    /// Consider directories and files.
4802    Entries,
4803}
4804
4805impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4806    type Candidates = PathMatchCandidateSetIter<'a>;
4807
4808    fn id(&self) -> usize {
4809        self.snapshot.id().to_usize()
4810    }
4811
4812    fn len(&self) -> usize {
4813        match self.candidates {
4814            Candidates::Files => {
4815                if self.include_ignored {
4816                    self.snapshot.file_count()
4817                } else {
4818                    self.snapshot.visible_file_count()
4819                }
4820            }
4821
4822            Candidates::Directories => {
4823                if self.include_ignored {
4824                    self.snapshot.dir_count()
4825                } else {
4826                    self.snapshot.visible_dir_count()
4827                }
4828            }
4829
4830            Candidates::Entries => {
4831                if self.include_ignored {
4832                    self.snapshot.entry_count()
4833                } else {
4834                    self.snapshot.visible_entry_count()
4835                }
4836            }
4837        }
4838    }
4839
4840    fn prefix(&self) -> Arc<str> {
4841        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
4842            self.snapshot.root_name().into()
4843        } else if self.include_root_name {
4844            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
4845        } else {
4846            Arc::default()
4847        }
4848    }
4849
4850    fn candidates(&'a self, start: usize) -> Self::Candidates {
4851        PathMatchCandidateSetIter {
4852            traversal: match self.candidates {
4853                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
4854                Candidates::Files => self.snapshot.files(self.include_ignored, start),
4855                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
4856            },
4857        }
4858    }
4859}
4860
4861pub struct PathMatchCandidateSetIter<'a> {
4862    traversal: Traversal<'a>,
4863}
4864
4865impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
4866    type Item = fuzzy::PathMatchCandidate<'a>;
4867
4868    fn next(&mut self) -> Option<Self::Item> {
4869        self.traversal
4870            .next()
4871            .map(|entry| fuzzy::PathMatchCandidate {
4872                is_dir: entry.kind.is_dir(),
4873                path: &entry.path,
4874                char_bag: entry.char_bag,
4875            })
4876    }
4877}
4878
4879impl EventEmitter<Event> for Project {}
4880
4881impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
4882    fn from(val: &'a ProjectPath) -> Self {
4883        SettingsLocation {
4884            worktree_id: val.worktree_id,
4885            path: val.path.as_ref(),
4886        }
4887    }
4888}
4889
4890impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
4891    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
4892        Self {
4893            worktree_id,
4894            path: path.as_ref().into(),
4895        }
4896    }
4897}
4898
4899pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
4900    let mut path_components = path.components();
4901    let mut base_components = base.components();
4902    let mut components: Vec<Component> = Vec::new();
4903    loop {
4904        match (path_components.next(), base_components.next()) {
4905            (None, None) => break,
4906            (Some(a), None) => {
4907                components.push(a);
4908                components.extend(path_components.by_ref());
4909                break;
4910            }
4911            (None, _) => components.push(Component::ParentDir),
4912            (Some(a), Some(b)) if components.is_empty() && a == b => (),
4913            (Some(a), Some(Component::CurDir)) => components.push(a),
4914            (Some(a), Some(_)) => {
4915                components.push(Component::ParentDir);
4916                for _ in base_components {
4917                    components.push(Component::ParentDir);
4918                }
4919                components.push(a);
4920                components.extend(path_components.by_ref());
4921                break;
4922            }
4923        }
4924    }
4925    components.iter().map(|c| c.as_os_str()).collect()
4926}
4927
4928fn resolve_path(base: &Path, path: &Path) -> PathBuf {
4929    let mut result = base.to_path_buf();
4930    for component in path.components() {
4931        match component {
4932            Component::ParentDir => {
4933                result.pop();
4934            }
4935            Component::CurDir => (),
4936            _ => result.push(component),
4937        }
4938    }
4939    result
4940}
4941
4942/// ResolvedPath is a path that has been resolved to either a ProjectPath
4943/// or an AbsPath and that *exists*.
4944#[derive(Debug, Clone)]
4945pub enum ResolvedPath {
4946    ProjectPath {
4947        project_path: ProjectPath,
4948        is_dir: bool,
4949    },
4950    AbsPath {
4951        path: PathBuf,
4952        is_dir: bool,
4953    },
4954}
4955
4956impl ResolvedPath {
4957    pub fn abs_path(&self) -> Option<&Path> {
4958        match self {
4959            Self::AbsPath { path, .. } => Some(path.as_path()),
4960            _ => None,
4961        }
4962    }
4963
4964    pub fn project_path(&self) -> Option<&ProjectPath> {
4965        match self {
4966            Self::ProjectPath { project_path, .. } => Some(&project_path),
4967            _ => None,
4968        }
4969    }
4970
4971    pub fn is_file(&self) -> bool {
4972        !self.is_dir()
4973    }
4974
4975    pub fn is_dir(&self) -> bool {
4976        match self {
4977            Self::ProjectPath { is_dir, .. } => *is_dir,
4978            Self::AbsPath { is_dir, .. } => *is_dir,
4979        }
4980    }
4981}
4982
4983impl ProjectItem for Buffer {
4984    fn try_open(
4985        project: &Entity<Project>,
4986        path: &ProjectPath,
4987        cx: &mut App,
4988    ) -> Option<Task<Result<Entity<Self>>>> {
4989        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
4990    }
4991
4992    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
4993        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
4994    }
4995
4996    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
4997        self.file().map(|file| ProjectPath {
4998            worktree_id: file.worktree_id(cx),
4999            path: file.path().clone(),
5000        })
5001    }
5002
5003    fn is_dirty(&self) -> bool {
5004        self.is_dirty()
5005    }
5006}
5007
5008impl Completion {
5009    /// A key that can be used to sort completions when displaying
5010    /// them to the user.
5011    pub fn sort_key(&self) -> (usize, &str) {
5012        const DEFAULT_KIND_KEY: usize = 3;
5013        let kind_key = self
5014            .source
5015            // `lsp::CompletionListItemDefaults` has no `kind` field
5016            .lsp_completion(false)
5017            .and_then(|lsp_completion| lsp_completion.kind)
5018            .and_then(|lsp_completion_kind| match lsp_completion_kind {
5019                lsp::CompletionItemKind::KEYWORD => Some(0),
5020                lsp::CompletionItemKind::VARIABLE => Some(1),
5021                lsp::CompletionItemKind::CONSTANT => Some(2),
5022                _ => None,
5023            })
5024            .unwrap_or(DEFAULT_KIND_KEY);
5025        (kind_key, &self.label.text[self.label.filter_range.clone()])
5026    }
5027
5028    /// Whether this completion is a snippet.
5029    pub fn is_snippet(&self) -> bool {
5030        self.source
5031            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5032            .lsp_completion(true)
5033            .map_or(false, |lsp_completion| {
5034                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5035            })
5036    }
5037
5038    /// Returns the corresponding color for this completion.
5039    ///
5040    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5041    pub fn color(&self) -> Option<Hsla> {
5042        // `lsp::CompletionListItemDefaults` has no `kind` field
5043        let lsp_completion = self.source.lsp_completion(false)?;
5044        if lsp_completion.kind? == CompletionItemKind::COLOR {
5045            return color_extractor::extract_color(&lsp_completion);
5046        }
5047        None
5048    }
5049}
5050
5051pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5052    entries.sort_by(|entry_a, entry_b| {
5053        let entry_a = entry_a.as_ref();
5054        let entry_b = entry_b.as_ref();
5055        compare_paths(
5056            (&entry_a.path, entry_a.is_file()),
5057            (&entry_b.path, entry_b.is_file()),
5058        )
5059    });
5060}
5061
5062fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5063    match level {
5064        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5065        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5066        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5067    }
5068}