project.rs

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