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