project.rs

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