project.rs

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