project.rs

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