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