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