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