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