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 directory_environment(
1649        &self,
1650        abs_path: Arc<Path>,
1651        cx: &mut App,
1652    ) -> Shared<Task<Option<HashMap<String, String>>>> {
1653        self.environment.update(cx, |environment, cx| {
1654            environment.get_directory_environment(abs_path, cx)
1655        })
1656    }
1657
1658    pub fn shell_environment_errors<'a>(
1659        &'a self,
1660        cx: &'a App,
1661    ) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
1662        self.environment.read(cx).environment_errors()
1663    }
1664
1665    pub fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
1666        self.environment.update(cx, |environment, cx| {
1667            environment.remove_environment_error(abs_path, cx);
1668        });
1669    }
1670
1671    #[cfg(any(test, feature = "test-support"))]
1672    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1673        self.buffer_store
1674            .read(cx)
1675            .get_by_path(&path.into(), cx)
1676            .is_some()
1677    }
1678
1679    pub fn fs(&self) -> &Arc<dyn Fs> {
1680        &self.fs
1681    }
1682
1683    pub fn remote_id(&self) -> Option<u64> {
1684        match self.client_state {
1685            ProjectClientState::Local => None,
1686            ProjectClientState::Shared { remote_id, .. }
1687            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1688        }
1689    }
1690
1691    pub fn supports_terminal(&self, _cx: &App) -> bool {
1692        if self.is_local() {
1693            return true;
1694        }
1695        if self.is_via_ssh() {
1696            return true;
1697        }
1698
1699        return false;
1700    }
1701
1702    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1703        if let Some(ssh_state) = &self.ssh_client {
1704            return Some(ssh_state.read(cx).connection_string().into());
1705        }
1706
1707        return None;
1708    }
1709
1710    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1711        self.ssh_client
1712            .as_ref()
1713            .map(|ssh| ssh.read(cx).connection_state())
1714    }
1715
1716    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1717        self.ssh_client
1718            .as_ref()
1719            .map(|ssh| ssh.read(cx).connection_options())
1720    }
1721
1722    pub fn replica_id(&self) -> ReplicaId {
1723        match self.client_state {
1724            ProjectClientState::Remote { replica_id, .. } => replica_id,
1725            _ => {
1726                if self.ssh_client.is_some() {
1727                    1
1728                } else {
1729                    0
1730                }
1731            }
1732        }
1733    }
1734
1735    pub fn task_store(&self) -> &Entity<TaskStore> {
1736        &self.task_store
1737    }
1738
1739    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1740        &self.snippets
1741    }
1742
1743    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1744        match kind {
1745            SearchInputKind::Query => &self.search_history,
1746            SearchInputKind::Include => &self.search_included_history,
1747            SearchInputKind::Exclude => &self.search_excluded_history,
1748        }
1749    }
1750
1751    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1752        match kind {
1753            SearchInputKind::Query => &mut self.search_history,
1754            SearchInputKind::Include => &mut self.search_included_history,
1755            SearchInputKind::Exclude => &mut self.search_excluded_history,
1756        }
1757    }
1758
1759    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1760        &self.collaborators
1761    }
1762
1763    pub fn host(&self) -> Option<&Collaborator> {
1764        self.collaborators.values().find(|c| c.is_host)
1765    }
1766
1767    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1768        self.worktree_store.update(cx, |store, _| {
1769            store.set_worktrees_reordered(worktrees_reordered);
1770        });
1771    }
1772
1773    /// Collect all worktrees, including ones that don't appear in the project panel
1774    pub fn worktrees<'a>(
1775        &self,
1776        cx: &'a App,
1777    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1778        self.worktree_store.read(cx).worktrees()
1779    }
1780
1781    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1782    pub fn visible_worktrees<'a>(
1783        &'a self,
1784        cx: &'a App,
1785    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1786        self.worktree_store.read(cx).visible_worktrees(cx)
1787    }
1788
1789    pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
1790        self.visible_worktrees(cx)
1791            .find(|tree| tree.read(cx).root_name() == root_name)
1792    }
1793
1794    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1795        self.visible_worktrees(cx)
1796            .map(|tree| tree.read(cx).root_name())
1797    }
1798
1799    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1800        self.worktree_store.read(cx).worktree_for_id(id, cx)
1801    }
1802
1803    pub fn worktree_for_entry(
1804        &self,
1805        entry_id: ProjectEntryId,
1806        cx: &App,
1807    ) -> Option<Entity<Worktree>> {
1808        self.worktree_store
1809            .read(cx)
1810            .worktree_for_entry(entry_id, cx)
1811    }
1812
1813    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1814        self.worktree_for_entry(entry_id, cx)
1815            .map(|worktree| worktree.read(cx).id())
1816    }
1817
1818    /// Checks if the entry is the root of a worktree.
1819    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1820        self.worktree_for_entry(entry_id, cx)
1821            .map(|worktree| {
1822                worktree
1823                    .read(cx)
1824                    .root_entry()
1825                    .is_some_and(|e| e.id == entry_id)
1826            })
1827            .unwrap_or(false)
1828    }
1829
1830    pub fn project_path_git_status(
1831        &self,
1832        project_path: &ProjectPath,
1833        cx: &App,
1834    ) -> Option<FileStatus> {
1835        self.git_store
1836            .read(cx)
1837            .project_path_git_status(project_path, cx)
1838    }
1839
1840    pub fn visibility_for_paths(
1841        &self,
1842        paths: &[PathBuf],
1843        metadatas: &[Metadata],
1844        exclude_sub_dirs: bool,
1845        cx: &App,
1846    ) -> Option<bool> {
1847        paths
1848            .iter()
1849            .zip(metadatas)
1850            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1851            .max()
1852            .flatten()
1853    }
1854
1855    pub fn visibility_for_path(
1856        &self,
1857        path: &Path,
1858        metadata: &Metadata,
1859        exclude_sub_dirs: bool,
1860        cx: &App,
1861    ) -> Option<bool> {
1862        let sanitized_path = SanitizedPath::from(path);
1863        let path = sanitized_path.as_path();
1864        self.worktrees(cx)
1865            .filter_map(|worktree| {
1866                let worktree = worktree.read(cx);
1867                let abs_path = worktree.as_local()?.abs_path();
1868                let contains = path == abs_path
1869                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1870                contains.then(|| worktree.is_visible())
1871            })
1872            .max()
1873    }
1874
1875    pub fn create_entry(
1876        &mut self,
1877        project_path: impl Into<ProjectPath>,
1878        is_directory: bool,
1879        cx: &mut Context<Self>,
1880    ) -> Task<Result<CreatedEntry>> {
1881        let project_path = project_path.into();
1882        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1883            return Task::ready(Err(anyhow!(format!(
1884                "No worktree for path {project_path:?}"
1885            ))));
1886        };
1887        worktree.update(cx, |worktree, cx| {
1888            worktree.create_entry(project_path.path, is_directory, None, cx)
1889        })
1890    }
1891
1892    pub fn copy_entry(
1893        &mut self,
1894        entry_id: ProjectEntryId,
1895        relative_worktree_source_path: Option<PathBuf>,
1896        new_path: impl Into<Arc<Path>>,
1897        cx: &mut Context<Self>,
1898    ) -> Task<Result<Option<Entry>>> {
1899        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1900            return Task::ready(Ok(None));
1901        };
1902        worktree.update(cx, |worktree, cx| {
1903            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1904        })
1905    }
1906
1907    /// Renames the project entry with given `entry_id`.
1908    ///
1909    /// `new_path` is a relative path to worktree root.
1910    /// If root entry is renamed then its new root name is used instead.
1911    pub fn rename_entry(
1912        &mut self,
1913        entry_id: ProjectEntryId,
1914        new_path: impl Into<Arc<Path>>,
1915        cx: &mut Context<Self>,
1916    ) -> Task<Result<CreatedEntry>> {
1917        let worktree_store = self.worktree_store.read(cx);
1918        let new_path = new_path.into();
1919        let Some((worktree, old_path, is_dir)) = worktree_store
1920            .worktree_and_entry_for_id(entry_id, cx)
1921            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1922        else {
1923            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1924        };
1925
1926        let worktree_id = worktree.read(cx).id();
1927        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1928
1929        let lsp_store = self.lsp_store().downgrade();
1930        cx.spawn(async move |_, cx| {
1931            let (old_abs_path, new_abs_path) = {
1932                let root_path = worktree.update(cx, |this, _| this.abs_path())?;
1933                let new_abs_path = if is_root_entry {
1934                    root_path.parent().unwrap().join(&new_path)
1935                } else {
1936                    root_path.join(&new_path)
1937                };
1938                (root_path.join(&old_path), new_abs_path)
1939            };
1940            LspStore::will_rename_entry(
1941                lsp_store.clone(),
1942                worktree_id,
1943                &old_abs_path,
1944                &new_abs_path,
1945                is_dir,
1946                cx.clone(),
1947            )
1948            .await;
1949
1950            let entry = worktree
1951                .update(cx, |worktree, cx| {
1952                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1953                })?
1954                .await?;
1955
1956            lsp_store
1957                .update(cx, |this, _| {
1958                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1959                })
1960                .ok();
1961            Ok(entry)
1962        })
1963    }
1964
1965    pub fn delete_file(
1966        &mut self,
1967        path: ProjectPath,
1968        trash: bool,
1969        cx: &mut Context<Self>,
1970    ) -> Option<Task<Result<()>>> {
1971        let entry = self.entry_for_path(&path, cx)?;
1972        self.delete_entry(entry.id, trash, cx)
1973    }
1974
1975    pub fn delete_entry(
1976        &mut self,
1977        entry_id: ProjectEntryId,
1978        trash: bool,
1979        cx: &mut Context<Self>,
1980    ) -> Option<Task<Result<()>>> {
1981        let worktree = self.worktree_for_entry(entry_id, cx)?;
1982        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1983        worktree.update(cx, |worktree, cx| {
1984            worktree.delete_entry(entry_id, trash, cx)
1985        })
1986    }
1987
1988    pub fn expand_entry(
1989        &mut self,
1990        worktree_id: WorktreeId,
1991        entry_id: ProjectEntryId,
1992        cx: &mut Context<Self>,
1993    ) -> Option<Task<Result<()>>> {
1994        let worktree = self.worktree_for_id(worktree_id, cx)?;
1995        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
1996    }
1997
1998    pub fn expand_all_for_entry(
1999        &mut self,
2000        worktree_id: WorktreeId,
2001        entry_id: ProjectEntryId,
2002        cx: &mut Context<Self>,
2003    ) -> Option<Task<Result<()>>> {
2004        let worktree = self.worktree_for_id(worktree_id, cx)?;
2005        let task = worktree.update(cx, |worktree, cx| {
2006            worktree.expand_all_for_entry(entry_id, cx)
2007        });
2008        Some(cx.spawn(async move |this, cx| {
2009            task.ok_or_else(|| anyhow!("no task"))?.await?;
2010            this.update(cx, |_, cx| {
2011                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2012            })?;
2013            Ok(())
2014        }))
2015    }
2016
2017    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2018        if !matches!(self.client_state, ProjectClientState::Local) {
2019            return Err(anyhow!("project was already shared"));
2020        }
2021
2022        self.client_subscriptions.extend([
2023            self.client
2024                .subscribe_to_entity(project_id)?
2025                .set_entity(&cx.entity(), &mut cx.to_async()),
2026            self.client
2027                .subscribe_to_entity(project_id)?
2028                .set_entity(&self.worktree_store, &mut cx.to_async()),
2029            self.client
2030                .subscribe_to_entity(project_id)?
2031                .set_entity(&self.buffer_store, &mut cx.to_async()),
2032            self.client
2033                .subscribe_to_entity(project_id)?
2034                .set_entity(&self.lsp_store, &mut cx.to_async()),
2035            self.client
2036                .subscribe_to_entity(project_id)?
2037                .set_entity(&self.settings_observer, &mut cx.to_async()),
2038            self.client
2039                .subscribe_to_entity(project_id)?
2040                .set_entity(&self.dap_store, &mut cx.to_async()),
2041            self.client
2042                .subscribe_to_entity(project_id)?
2043                .set_entity(&self.breakpoint_store, &mut cx.to_async()),
2044            self.client
2045                .subscribe_to_entity(project_id)?
2046                .set_entity(&self.git_store, &mut cx.to_async()),
2047        ]);
2048
2049        self.buffer_store.update(cx, |buffer_store, cx| {
2050            buffer_store.shared(project_id, self.client.clone().into(), cx)
2051        });
2052        self.worktree_store.update(cx, |worktree_store, cx| {
2053            worktree_store.shared(project_id, self.client.clone().into(), cx);
2054        });
2055        self.lsp_store.update(cx, |lsp_store, cx| {
2056            lsp_store.shared(project_id, self.client.clone().into(), cx)
2057        });
2058        self.breakpoint_store.update(cx, |breakpoint_store, _| {
2059            breakpoint_store.shared(project_id, self.client.clone().into())
2060        });
2061        self.dap_store.update(cx, |dap_store, cx| {
2062            dap_store.shared(project_id, self.client.clone().into(), cx);
2063        });
2064        self.task_store.update(cx, |task_store, cx| {
2065            task_store.shared(project_id, self.client.clone().into(), cx);
2066        });
2067        self.settings_observer.update(cx, |settings_observer, cx| {
2068            settings_observer.shared(project_id, self.client.clone().into(), cx)
2069        });
2070        self.git_store.update(cx, |git_store, cx| {
2071            git_store.shared(project_id, self.client.clone().into(), cx)
2072        });
2073
2074        self.client_state = ProjectClientState::Shared {
2075            remote_id: project_id,
2076        };
2077
2078        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2079        Ok(())
2080    }
2081
2082    pub fn reshared(
2083        &mut self,
2084        message: proto::ResharedProject,
2085        cx: &mut Context<Self>,
2086    ) -> Result<()> {
2087        self.buffer_store
2088            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2089        self.set_collaborators_from_proto(message.collaborators, cx)?;
2090
2091        self.worktree_store.update(cx, |worktree_store, cx| {
2092            worktree_store.send_project_updates(cx);
2093        });
2094        if let Some(remote_id) = self.remote_id() {
2095            self.git_store.update(cx, |git_store, cx| {
2096                git_store.shared(remote_id, self.client.clone().into(), cx)
2097            });
2098        }
2099        cx.emit(Event::Reshared);
2100        Ok(())
2101    }
2102
2103    pub fn rejoined(
2104        &mut self,
2105        message: proto::RejoinedProject,
2106        message_id: u32,
2107        cx: &mut Context<Self>,
2108    ) -> Result<()> {
2109        cx.update_global::<SettingsStore, _>(|store, cx| {
2110            self.worktree_store.update(cx, |worktree_store, cx| {
2111                for worktree in worktree_store.worktrees() {
2112                    store
2113                        .clear_local_settings(worktree.read(cx).id(), cx)
2114                        .log_err();
2115                }
2116            });
2117        });
2118
2119        self.join_project_response_message_id = message_id;
2120        self.set_worktrees_from_proto(message.worktrees, cx)?;
2121        self.set_collaborators_from_proto(message.collaborators, cx)?;
2122        self.lsp_store.update(cx, |lsp_store, _| {
2123            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
2124        });
2125        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2126            .unwrap();
2127        cx.emit(Event::Rejoined);
2128        Ok(())
2129    }
2130
2131    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2132        self.unshare_internal(cx)?;
2133        cx.emit(Event::RemoteIdChanged(None));
2134        Ok(())
2135    }
2136
2137    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2138        if self.is_via_collab() {
2139            return Err(anyhow!("attempted to unshare a remote project"));
2140        }
2141
2142        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2143            self.client_state = ProjectClientState::Local;
2144            self.collaborators.clear();
2145            self.client_subscriptions.clear();
2146            self.worktree_store.update(cx, |store, cx| {
2147                store.unshared(cx);
2148            });
2149            self.buffer_store.update(cx, |buffer_store, cx| {
2150                buffer_store.forget_shared_buffers();
2151                buffer_store.unshared(cx)
2152            });
2153            self.task_store.update(cx, |task_store, cx| {
2154                task_store.unshared(cx);
2155            });
2156            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2157                breakpoint_store.unshared(cx);
2158            });
2159            self.dap_store.update(cx, |dap_store, cx| {
2160                dap_store.unshared(cx);
2161            });
2162            self.settings_observer.update(cx, |settings_observer, cx| {
2163                settings_observer.unshared(cx);
2164            });
2165            self.git_store.update(cx, |git_store, cx| {
2166                git_store.unshared(cx);
2167            });
2168
2169            self.client
2170                .send(proto::UnshareProject {
2171                    project_id: remote_id,
2172                })
2173                .ok();
2174            Ok(())
2175        } else {
2176            Err(anyhow!("attempted to unshare an unshared project"))
2177        }
2178    }
2179
2180    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2181        if self.is_disconnected(cx) {
2182            return;
2183        }
2184        self.disconnected_from_host_internal(cx);
2185        cx.emit(Event::DisconnectedFromHost);
2186    }
2187
2188    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2189        let new_capability =
2190            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2191                Capability::ReadWrite
2192            } else {
2193                Capability::ReadOnly
2194            };
2195        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2196            if *capability == new_capability {
2197                return;
2198            }
2199
2200            *capability = new_capability;
2201            for buffer in self.opened_buffers(cx) {
2202                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2203            }
2204        }
2205    }
2206
2207    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2208        if let ProjectClientState::Remote {
2209            sharing_has_stopped,
2210            ..
2211        } = &mut self.client_state
2212        {
2213            *sharing_has_stopped = true;
2214            self.collaborators.clear();
2215            self.worktree_store.update(cx, |store, cx| {
2216                store.disconnected_from_host(cx);
2217            });
2218            self.buffer_store.update(cx, |buffer_store, cx| {
2219                buffer_store.disconnected_from_host(cx)
2220            });
2221            self.lsp_store
2222                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2223        }
2224    }
2225
2226    pub fn close(&mut self, cx: &mut Context<Self>) {
2227        cx.emit(Event::Closed);
2228    }
2229
2230    pub fn is_disconnected(&self, cx: &App) -> bool {
2231        match &self.client_state {
2232            ProjectClientState::Remote {
2233                sharing_has_stopped,
2234                ..
2235            } => *sharing_has_stopped,
2236            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
2237            _ => false,
2238        }
2239    }
2240
2241    fn ssh_is_disconnected(&self, cx: &App) -> bool {
2242        self.ssh_client
2243            .as_ref()
2244            .map(|ssh| ssh.read(cx).is_disconnected())
2245            .unwrap_or(false)
2246    }
2247
2248    pub fn capability(&self) -> Capability {
2249        match &self.client_state {
2250            ProjectClientState::Remote { capability, .. } => *capability,
2251            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2252        }
2253    }
2254
2255    pub fn is_read_only(&self, cx: &App) -> bool {
2256        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2257    }
2258
2259    pub fn is_local(&self) -> bool {
2260        match &self.client_state {
2261            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2262                self.ssh_client.is_none()
2263            }
2264            ProjectClientState::Remote { .. } => false,
2265        }
2266    }
2267
2268    pub fn is_via_ssh(&self) -> bool {
2269        match &self.client_state {
2270            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2271                self.ssh_client.is_some()
2272            }
2273            ProjectClientState::Remote { .. } => false,
2274        }
2275    }
2276
2277    pub fn is_via_collab(&self) -> bool {
2278        match &self.client_state {
2279            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2280            ProjectClientState::Remote { .. } => true,
2281        }
2282    }
2283
2284    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2285        self.buffer_store
2286            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
2287    }
2288
2289    pub fn create_local_buffer(
2290        &mut self,
2291        text: &str,
2292        language: Option<Arc<Language>>,
2293        cx: &mut Context<Self>,
2294    ) -> Entity<Buffer> {
2295        if self.is_via_collab() || self.is_via_ssh() {
2296            panic!("called create_local_buffer on a remote project")
2297        }
2298        self.buffer_store.update(cx, |buffer_store, cx| {
2299            buffer_store.create_local_buffer(text, language, cx)
2300        })
2301    }
2302
2303    pub fn open_path(
2304        &mut self,
2305        path: ProjectPath,
2306        cx: &mut Context<Self>,
2307    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
2308        let task = self.open_buffer(path.clone(), cx);
2309        cx.spawn(async move |_project, cx| {
2310            let buffer = task.await?;
2311            let project_entry_id = buffer.read_with(cx, |buffer, cx| {
2312                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
2313            })?;
2314
2315            let buffer: &AnyEntity = &buffer;
2316            Ok((project_entry_id, buffer.clone()))
2317        })
2318    }
2319
2320    pub fn open_local_buffer(
2321        &mut self,
2322        abs_path: impl AsRef<Path>,
2323        cx: &mut Context<Self>,
2324    ) -> Task<Result<Entity<Buffer>>> {
2325        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2326            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
2327        } else {
2328            Task::ready(Err(anyhow!("no such path")))
2329        }
2330    }
2331
2332    #[cfg(any(test, feature = "test-support"))]
2333    pub fn open_local_buffer_with_lsp(
2334        &mut self,
2335        abs_path: impl AsRef<Path>,
2336        cx: &mut Context<Self>,
2337    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2338        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2339            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2340        } else {
2341            Task::ready(Err(anyhow!("no such path")))
2342        }
2343    }
2344
2345    pub fn open_buffer(
2346        &mut self,
2347        path: impl Into<ProjectPath>,
2348        cx: &mut App,
2349    ) -> Task<Result<Entity<Buffer>>> {
2350        if self.is_disconnected(cx) {
2351            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2352        }
2353
2354        self.buffer_store.update(cx, |buffer_store, cx| {
2355            buffer_store.open_buffer(path.into(), cx)
2356        })
2357    }
2358
2359    #[cfg(any(test, feature = "test-support"))]
2360    pub fn open_buffer_with_lsp(
2361        &mut self,
2362        path: impl Into<ProjectPath>,
2363        cx: &mut Context<Self>,
2364    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2365        let buffer = self.open_buffer(path, cx);
2366        cx.spawn(async move |this, cx| {
2367            let buffer = buffer.await?;
2368            let handle = this.update(cx, |project, cx| {
2369                project.register_buffer_with_language_servers(&buffer, cx)
2370            })?;
2371            Ok((buffer, handle))
2372        })
2373    }
2374
2375    pub fn register_buffer_with_language_servers(
2376        &self,
2377        buffer: &Entity<Buffer>,
2378        cx: &mut App,
2379    ) -> OpenLspBufferHandle {
2380        self.lsp_store.update(cx, |lsp_store, cx| {
2381            lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2382        })
2383    }
2384
2385    pub fn open_unstaged_diff(
2386        &mut self,
2387        buffer: Entity<Buffer>,
2388        cx: &mut Context<Self>,
2389    ) -> Task<Result<Entity<BufferDiff>>> {
2390        if self.is_disconnected(cx) {
2391            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2392        }
2393        self.git_store
2394            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2395    }
2396
2397    pub fn open_uncommitted_diff(
2398        &mut self,
2399        buffer: Entity<Buffer>,
2400        cx: &mut Context<Self>,
2401    ) -> Task<Result<Entity<BufferDiff>>> {
2402        if self.is_disconnected(cx) {
2403            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2404        }
2405        self.git_store.update(cx, |git_store, cx| {
2406            git_store.open_uncommitted_diff(buffer, cx)
2407        })
2408    }
2409
2410    pub fn open_buffer_by_id(
2411        &mut self,
2412        id: BufferId,
2413        cx: &mut Context<Self>,
2414    ) -> Task<Result<Entity<Buffer>>> {
2415        if let Some(buffer) = self.buffer_for_id(id, cx) {
2416            Task::ready(Ok(buffer))
2417        } else if self.is_local() || self.is_via_ssh() {
2418            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2419        } else if let Some(project_id) = self.remote_id() {
2420            let request = self.client.request(proto::OpenBufferById {
2421                project_id,
2422                id: id.into(),
2423            });
2424            cx.spawn(async move |project, cx| {
2425                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2426                project
2427                    .update(cx, |project, cx| {
2428                        project.buffer_store.update(cx, |buffer_store, cx| {
2429                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2430                        })
2431                    })?
2432                    .await
2433            })
2434        } else {
2435            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2436        }
2437    }
2438
2439    pub fn save_buffers(
2440        &self,
2441        buffers: HashSet<Entity<Buffer>>,
2442        cx: &mut Context<Self>,
2443    ) -> Task<Result<()>> {
2444        cx.spawn(async move |this, cx| {
2445            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2446                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2447                    .ok()
2448            });
2449            try_join_all(save_tasks).await?;
2450            Ok(())
2451        })
2452    }
2453
2454    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2455        self.buffer_store
2456            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2457    }
2458
2459    pub fn save_buffer_as(
2460        &mut self,
2461        buffer: Entity<Buffer>,
2462        path: ProjectPath,
2463        cx: &mut Context<Self>,
2464    ) -> Task<Result<()>> {
2465        self.buffer_store.update(cx, |buffer_store, cx| {
2466            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2467        })
2468    }
2469
2470    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2471        self.buffer_store.read(cx).get_by_path(path, cx)
2472    }
2473
2474    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2475        {
2476            let mut remotely_created_models = self.remotely_created_models.lock();
2477            if remotely_created_models.retain_count > 0 {
2478                remotely_created_models.buffers.push(buffer.clone())
2479            }
2480        }
2481
2482        self.request_buffer_diff_recalculation(buffer, cx);
2483
2484        cx.subscribe(buffer, |this, buffer, event, cx| {
2485            this.on_buffer_event(buffer, event, cx);
2486        })
2487        .detach();
2488
2489        Ok(())
2490    }
2491
2492    pub fn open_image(
2493        &mut self,
2494        path: impl Into<ProjectPath>,
2495        cx: &mut Context<Self>,
2496    ) -> Task<Result<Entity<ImageItem>>> {
2497        if self.is_disconnected(cx) {
2498            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2499        }
2500
2501        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2502            image_store.open_image(path.into(), cx)
2503        });
2504
2505        let weak_project = cx.entity().downgrade();
2506        cx.spawn(async move |_, cx| {
2507            let image_item = open_image_task.await?;
2508            let project = weak_project
2509                .upgrade()
2510                .ok_or_else(|| anyhow!("Project dropped"))?;
2511
2512            let metadata = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2513            image_item.update(cx, |image_item, cx| {
2514                image_item.image_metadata = Some(metadata);
2515                cx.emit(ImageItemEvent::MetadataUpdated);
2516            })?;
2517
2518            Ok(image_item)
2519        })
2520    }
2521
2522    async fn send_buffer_ordered_messages(
2523        this: WeakEntity<Self>,
2524        rx: UnboundedReceiver<BufferOrderedMessage>,
2525        cx: &mut AsyncApp,
2526    ) -> Result<()> {
2527        const MAX_BATCH_SIZE: usize = 128;
2528
2529        let mut operations_by_buffer_id = HashMap::default();
2530        async fn flush_operations(
2531            this: &WeakEntity<Project>,
2532            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2533            needs_resync_with_host: &mut bool,
2534            is_local: bool,
2535            cx: &mut AsyncApp,
2536        ) -> Result<()> {
2537            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2538                let request = this.update(cx, |this, _| {
2539                    let project_id = this.remote_id()?;
2540                    Some(this.client.request(proto::UpdateBuffer {
2541                        buffer_id: buffer_id.into(),
2542                        project_id,
2543                        operations,
2544                    }))
2545                })?;
2546                if let Some(request) = request {
2547                    if request.await.is_err() && !is_local {
2548                        *needs_resync_with_host = true;
2549                        break;
2550                    }
2551                }
2552            }
2553            Ok(())
2554        }
2555
2556        let mut needs_resync_with_host = false;
2557        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2558
2559        while let Some(changes) = changes.next().await {
2560            let is_local = this.update(cx, |this, _| this.is_local())?;
2561
2562            for change in changes {
2563                match change {
2564                    BufferOrderedMessage::Operation {
2565                        buffer_id,
2566                        operation,
2567                    } => {
2568                        if needs_resync_with_host {
2569                            continue;
2570                        }
2571
2572                        operations_by_buffer_id
2573                            .entry(buffer_id)
2574                            .or_insert(Vec::new())
2575                            .push(operation);
2576                    }
2577
2578                    BufferOrderedMessage::Resync => {
2579                        operations_by_buffer_id.clear();
2580                        if this
2581                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2582                            .await
2583                            .is_ok()
2584                        {
2585                            needs_resync_with_host = false;
2586                        }
2587                    }
2588
2589                    BufferOrderedMessage::LanguageServerUpdate {
2590                        language_server_id,
2591                        message,
2592                    } => {
2593                        flush_operations(
2594                            &this,
2595                            &mut operations_by_buffer_id,
2596                            &mut needs_resync_with_host,
2597                            is_local,
2598                            cx,
2599                        )
2600                        .await?;
2601
2602                        this.update(cx, |this, _| {
2603                            if let Some(project_id) = this.remote_id() {
2604                                this.client
2605                                    .send(proto::UpdateLanguageServer {
2606                                        project_id,
2607                                        language_server_id: language_server_id.0 as u64,
2608                                        variant: Some(message),
2609                                    })
2610                                    .log_err();
2611                            }
2612                        })?;
2613                    }
2614                }
2615            }
2616
2617            flush_operations(
2618                &this,
2619                &mut operations_by_buffer_id,
2620                &mut needs_resync_with_host,
2621                is_local,
2622                cx,
2623            )
2624            .await?;
2625        }
2626
2627        Ok(())
2628    }
2629
2630    fn on_buffer_store_event(
2631        &mut self,
2632        _: Entity<BufferStore>,
2633        event: &BufferStoreEvent,
2634        cx: &mut Context<Self>,
2635    ) {
2636        match event {
2637            BufferStoreEvent::BufferAdded(buffer) => {
2638                self.register_buffer(buffer, cx).log_err();
2639            }
2640            BufferStoreEvent::BufferDropped(buffer_id) => {
2641                if let Some(ref ssh_client) = self.ssh_client {
2642                    ssh_client
2643                        .read(cx)
2644                        .proto_client()
2645                        .send(proto::CloseBuffer {
2646                            project_id: 0,
2647                            buffer_id: buffer_id.to_proto(),
2648                        })
2649                        .log_err();
2650                }
2651            }
2652            _ => {}
2653        }
2654    }
2655
2656    fn on_image_store_event(
2657        &mut self,
2658        _: Entity<ImageStore>,
2659        event: &ImageStoreEvent,
2660        cx: &mut Context<Self>,
2661    ) {
2662        match event {
2663            ImageStoreEvent::ImageAdded(image) => {
2664                cx.subscribe(image, |this, image, event, cx| {
2665                    this.on_image_event(image, event, cx);
2666                })
2667                .detach();
2668            }
2669        }
2670    }
2671
2672    fn on_dap_store_event(
2673        &mut self,
2674        _: Entity<DapStore>,
2675        event: &DapStoreEvent,
2676        cx: &mut Context<Self>,
2677    ) {
2678        match event {
2679            DapStoreEvent::Notification(message) => {
2680                cx.emit(Event::Toast {
2681                    notification_id: "dap".into(),
2682                    message: message.clone(),
2683                });
2684            }
2685            _ => {}
2686        }
2687    }
2688
2689    fn on_lsp_store_event(
2690        &mut self,
2691        _: Entity<LspStore>,
2692        event: &LspStoreEvent,
2693        cx: &mut Context<Self>,
2694    ) {
2695        match event {
2696            LspStoreEvent::DiagnosticsUpdated {
2697                language_server_id,
2698                path,
2699            } => cx.emit(Event::DiagnosticsUpdated {
2700                path: path.clone(),
2701                language_server_id: *language_server_id,
2702            }),
2703            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2704                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2705            ),
2706            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2707                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2708            }
2709            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2710                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2711            ),
2712            LspStoreEvent::LanguageDetected {
2713                buffer,
2714                new_language,
2715            } => {
2716                let Some(_) = new_language else {
2717                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2718                    return;
2719                };
2720            }
2721            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2722            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2723            LspStoreEvent::LanguageServerPrompt(prompt) => {
2724                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2725            }
2726            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2727                cx.emit(Event::DiskBasedDiagnosticsStarted {
2728                    language_server_id: *language_server_id,
2729                });
2730            }
2731            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2732                cx.emit(Event::DiskBasedDiagnosticsFinished {
2733                    language_server_id: *language_server_id,
2734                });
2735            }
2736            LspStoreEvent::LanguageServerUpdate {
2737                language_server_id,
2738                message,
2739            } => {
2740                if self.is_local() {
2741                    self.enqueue_buffer_ordered_message(
2742                        BufferOrderedMessage::LanguageServerUpdate {
2743                            language_server_id: *language_server_id,
2744                            message: message.clone(),
2745                        },
2746                    )
2747                    .ok();
2748                }
2749            }
2750            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2751                notification_id: "lsp".into(),
2752                message: message.clone(),
2753            }),
2754            LspStoreEvent::SnippetEdit {
2755                buffer_id,
2756                edits,
2757                most_recent_edit,
2758            } => {
2759                if most_recent_edit.replica_id == self.replica_id() {
2760                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2761                }
2762            }
2763        }
2764    }
2765
2766    fn on_ssh_event(
2767        &mut self,
2768        _: Entity<SshRemoteClient>,
2769        event: &remote::SshRemoteEvent,
2770        cx: &mut Context<Self>,
2771    ) {
2772        match event {
2773            remote::SshRemoteEvent::Disconnected => {
2774                // if self.is_via_ssh() {
2775                // self.collaborators.clear();
2776                self.worktree_store.update(cx, |store, cx| {
2777                    store.disconnected_from_host(cx);
2778                });
2779                self.buffer_store.update(cx, |buffer_store, cx| {
2780                    buffer_store.disconnected_from_host(cx)
2781                });
2782                self.lsp_store.update(cx, |lsp_store, _cx| {
2783                    lsp_store.disconnected_from_ssh_remote()
2784                });
2785                cx.emit(Event::DisconnectedFromSshRemote);
2786            }
2787        }
2788    }
2789
2790    fn on_settings_observer_event(
2791        &mut self,
2792        _: Entity<SettingsObserver>,
2793        event: &SettingsObserverEvent,
2794        cx: &mut Context<Self>,
2795    ) {
2796        match event {
2797            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2798                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2799                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
2800                    cx.emit(Event::Toast {
2801                        notification_id: format!("local-settings-{path:?}").into(),
2802                        message,
2803                    });
2804                }
2805                Ok(path) => cx.emit(Event::HideToast {
2806                    notification_id: format!("local-settings-{path:?}").into(),
2807                }),
2808                Err(_) => {}
2809            },
2810            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
2811                Err(InvalidSettingsError::Tasks { message, path }) => {
2812                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
2813                    cx.emit(Event::Toast {
2814                        notification_id: format!("local-tasks-{path:?}").into(),
2815                        message,
2816                    });
2817                }
2818                Ok(path) => cx.emit(Event::HideToast {
2819                    notification_id: format!("local-tasks-{path:?}").into(),
2820                }),
2821                Err(_) => {}
2822            },
2823        }
2824    }
2825
2826    fn on_worktree_store_event(
2827        &mut self,
2828        _: Entity<WorktreeStore>,
2829        event: &WorktreeStoreEvent,
2830        cx: &mut Context<Self>,
2831    ) {
2832        match event {
2833            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2834                self.on_worktree_added(worktree, cx);
2835                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2836            }
2837            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2838                cx.emit(Event::WorktreeRemoved(*id));
2839            }
2840            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2841                self.on_worktree_released(*id, cx);
2842            }
2843            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2844            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2845            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2846                self.client()
2847                    .telemetry()
2848                    .report_discovered_project_events(*worktree_id, changes);
2849                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2850            }
2851            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2852                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2853            }
2854            // Listen to the GitStore instead.
2855            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
2856        }
2857    }
2858
2859    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2860        let mut remotely_created_models = self.remotely_created_models.lock();
2861        if remotely_created_models.retain_count > 0 {
2862            remotely_created_models.worktrees.push(worktree.clone())
2863        }
2864    }
2865
2866    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2867        if let Some(ssh) = &self.ssh_client {
2868            ssh.read(cx)
2869                .proto_client()
2870                .send(proto::RemoveWorktree {
2871                    worktree_id: id_to_remove.to_proto(),
2872                })
2873                .log_err();
2874        }
2875    }
2876
2877    fn on_buffer_event(
2878        &mut self,
2879        buffer: Entity<Buffer>,
2880        event: &BufferEvent,
2881        cx: &mut Context<Self>,
2882    ) -> Option<()> {
2883        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2884            self.request_buffer_diff_recalculation(&buffer, cx);
2885        }
2886
2887        let buffer_id = buffer.read(cx).remote_id();
2888        match event {
2889            BufferEvent::ReloadNeeded => {
2890                if !self.is_via_collab() {
2891                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2892                        .detach_and_log_err(cx);
2893                }
2894            }
2895            BufferEvent::Operation {
2896                operation,
2897                is_local: true,
2898            } => {
2899                let operation = language::proto::serialize_operation(operation);
2900
2901                if let Some(ssh) = &self.ssh_client {
2902                    ssh.read(cx)
2903                        .proto_client()
2904                        .send(proto::UpdateBuffer {
2905                            project_id: 0,
2906                            buffer_id: buffer_id.to_proto(),
2907                            operations: vec![operation.clone()],
2908                        })
2909                        .ok();
2910                }
2911
2912                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2913                    buffer_id,
2914                    operation,
2915                })
2916                .ok();
2917            }
2918
2919            _ => {}
2920        }
2921
2922        None
2923    }
2924
2925    fn on_image_event(
2926        &mut self,
2927        image: Entity<ImageItem>,
2928        event: &ImageItemEvent,
2929        cx: &mut Context<Self>,
2930    ) -> Option<()> {
2931        match event {
2932            ImageItemEvent::ReloadNeeded => {
2933                if !self.is_via_collab() {
2934                    self.reload_images([image.clone()].into_iter().collect(), cx)
2935                        .detach_and_log_err(cx);
2936                }
2937            }
2938            _ => {}
2939        }
2940
2941        None
2942    }
2943
2944    fn request_buffer_diff_recalculation(
2945        &mut self,
2946        buffer: &Entity<Buffer>,
2947        cx: &mut Context<Self>,
2948    ) {
2949        self.buffers_needing_diff.insert(buffer.downgrade());
2950        let first_insertion = self.buffers_needing_diff.len() == 1;
2951
2952        let settings = ProjectSettings::get_global(cx);
2953        let delay = if let Some(delay) = settings.git.gutter_debounce {
2954            delay
2955        } else {
2956            if first_insertion {
2957                let this = cx.weak_entity();
2958                cx.defer(move |cx| {
2959                    if let Some(this) = this.upgrade() {
2960                        this.update(cx, |this, cx| {
2961                            this.recalculate_buffer_diffs(cx).detach();
2962                        });
2963                    }
2964                });
2965            }
2966            return;
2967        };
2968
2969        const MIN_DELAY: u64 = 50;
2970        let delay = delay.max(MIN_DELAY);
2971        let duration = Duration::from_millis(delay);
2972
2973        self.git_diff_debouncer
2974            .fire_new(duration, cx, move |this, cx| {
2975                this.recalculate_buffer_diffs(cx)
2976            });
2977    }
2978
2979    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2980        cx.spawn(async move |this, cx| {
2981            loop {
2982                let task = this
2983                    .update(cx, |this, cx| {
2984                        let buffers = this
2985                            .buffers_needing_diff
2986                            .drain()
2987                            .filter_map(|buffer| buffer.upgrade())
2988                            .collect::<Vec<_>>();
2989                        if buffers.is_empty() {
2990                            None
2991                        } else {
2992                            Some(this.git_store.update(cx, |git_store, cx| {
2993                                git_store.recalculate_buffer_diffs(buffers, cx)
2994                            }))
2995                        }
2996                    })
2997                    .ok()
2998                    .flatten();
2999
3000                if let Some(task) = task {
3001                    task.await;
3002                } else {
3003                    break;
3004                }
3005            }
3006        })
3007    }
3008
3009    pub fn set_language_for_buffer(
3010        &mut self,
3011        buffer: &Entity<Buffer>,
3012        new_language: Arc<Language>,
3013        cx: &mut Context<Self>,
3014    ) {
3015        self.lsp_store.update(cx, |lsp_store, cx| {
3016            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3017        })
3018    }
3019
3020    pub fn restart_language_servers_for_buffers(
3021        &mut self,
3022        buffers: Vec<Entity<Buffer>>,
3023        cx: &mut Context<Self>,
3024    ) {
3025        self.lsp_store.update(cx, |lsp_store, cx| {
3026            lsp_store.restart_language_servers_for_buffers(buffers, cx)
3027        })
3028    }
3029
3030    pub fn stop_language_servers_for_buffers(
3031        &mut self,
3032        buffers: Vec<Entity<Buffer>>,
3033        cx: &mut Context<Self>,
3034    ) {
3035        self.lsp_store.update(cx, |lsp_store, cx| {
3036            lsp_store.stop_language_servers_for_buffers(buffers, cx)
3037        })
3038    }
3039
3040    pub fn cancel_language_server_work_for_buffers(
3041        &mut self,
3042        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3043        cx: &mut Context<Self>,
3044    ) {
3045        self.lsp_store.update(cx, |lsp_store, cx| {
3046            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3047        })
3048    }
3049
3050    pub fn cancel_language_server_work(
3051        &mut self,
3052        server_id: LanguageServerId,
3053        token_to_cancel: Option<String>,
3054        cx: &mut Context<Self>,
3055    ) {
3056        self.lsp_store.update(cx, |lsp_store, cx| {
3057            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3058        })
3059    }
3060
3061    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3062        self.buffer_ordered_messages_tx
3063            .unbounded_send(message)
3064            .map_err(|e| anyhow!(e))
3065    }
3066
3067    pub fn available_toolchains(
3068        &self,
3069        path: ProjectPath,
3070        language_name: LanguageName,
3071        cx: &App,
3072    ) -> Task<Option<ToolchainList>> {
3073        if let Some(toolchain_store) = self.toolchain_store.clone() {
3074            cx.spawn(async move |cx| {
3075                cx.update(|cx| {
3076                    toolchain_store
3077                        .read(cx)
3078                        .list_toolchains(path, language_name, cx)
3079                })
3080                .ok()?
3081                .await
3082            })
3083        } else {
3084            Task::ready(None)
3085        }
3086    }
3087
3088    pub async fn toolchain_term(
3089        languages: Arc<LanguageRegistry>,
3090        language_name: LanguageName,
3091    ) -> Option<SharedString> {
3092        languages
3093            .language_for_name(language_name.as_ref())
3094            .await
3095            .ok()?
3096            .toolchain_lister()
3097            .map(|lister| lister.term())
3098    }
3099
3100    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3101        self.toolchain_store.clone()
3102    }
3103    pub fn activate_toolchain(
3104        &self,
3105        path: ProjectPath,
3106        toolchain: Toolchain,
3107        cx: &mut App,
3108    ) -> Task<Option<()>> {
3109        let Some(toolchain_store) = self.toolchain_store.clone() else {
3110            return Task::ready(None);
3111        };
3112        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3113    }
3114    pub fn active_toolchain(
3115        &self,
3116        path: ProjectPath,
3117        language_name: LanguageName,
3118        cx: &App,
3119    ) -> Task<Option<Toolchain>> {
3120        let Some(toolchain_store) = self.toolchain_store.clone() else {
3121            return Task::ready(None);
3122        };
3123        toolchain_store
3124            .read(cx)
3125            .active_toolchain(path, language_name, cx)
3126    }
3127    pub fn language_server_statuses<'a>(
3128        &'a self,
3129        cx: &'a App,
3130    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3131        self.lsp_store.read(cx).language_server_statuses()
3132    }
3133
3134    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3135        self.lsp_store.read(cx).last_formatting_failure()
3136    }
3137
3138    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3139        self.lsp_store
3140            .update(cx, |store, _| store.reset_last_formatting_failure());
3141    }
3142
3143    pub fn reload_buffers(
3144        &self,
3145        buffers: HashSet<Entity<Buffer>>,
3146        push_to_history: bool,
3147        cx: &mut Context<Self>,
3148    ) -> Task<Result<ProjectTransaction>> {
3149        self.buffer_store.update(cx, |buffer_store, cx| {
3150            buffer_store.reload_buffers(buffers, push_to_history, cx)
3151        })
3152    }
3153
3154    pub fn reload_images(
3155        &self,
3156        images: HashSet<Entity<ImageItem>>,
3157        cx: &mut Context<Self>,
3158    ) -> Task<Result<()>> {
3159        self.image_store
3160            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3161    }
3162
3163    pub fn format(
3164        &mut self,
3165        buffers: HashSet<Entity<Buffer>>,
3166        target: LspFormatTarget,
3167        push_to_history: bool,
3168        trigger: lsp_store::FormatTrigger,
3169        cx: &mut Context<Project>,
3170    ) -> Task<anyhow::Result<ProjectTransaction>> {
3171        self.lsp_store.update(cx, |lsp_store, cx| {
3172            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3173        })
3174    }
3175
3176    #[inline(never)]
3177    fn definition_impl(
3178        &mut self,
3179        buffer: &Entity<Buffer>,
3180        position: PointUtf16,
3181        cx: &mut Context<Self>,
3182    ) -> Task<Result<Vec<LocationLink>>> {
3183        self.request_lsp(
3184            buffer.clone(),
3185            LanguageServerToQuery::FirstCapable,
3186            GetDefinition { position },
3187            cx,
3188        )
3189    }
3190    pub fn definition<T: ToPointUtf16>(
3191        &mut self,
3192        buffer: &Entity<Buffer>,
3193        position: T,
3194        cx: &mut Context<Self>,
3195    ) -> Task<Result<Vec<LocationLink>>> {
3196        let position = position.to_point_utf16(buffer.read(cx));
3197        self.definition_impl(buffer, position, cx)
3198    }
3199
3200    fn declaration_impl(
3201        &mut self,
3202        buffer: &Entity<Buffer>,
3203        position: PointUtf16,
3204        cx: &mut Context<Self>,
3205    ) -> Task<Result<Vec<LocationLink>>> {
3206        self.request_lsp(
3207            buffer.clone(),
3208            LanguageServerToQuery::FirstCapable,
3209            GetDeclaration { position },
3210            cx,
3211        )
3212    }
3213
3214    pub fn declaration<T: ToPointUtf16>(
3215        &mut self,
3216        buffer: &Entity<Buffer>,
3217        position: T,
3218        cx: &mut Context<Self>,
3219    ) -> Task<Result<Vec<LocationLink>>> {
3220        let position = position.to_point_utf16(buffer.read(cx));
3221        self.declaration_impl(buffer, position, cx)
3222    }
3223
3224    fn type_definition_impl(
3225        &mut self,
3226        buffer: &Entity<Buffer>,
3227        position: PointUtf16,
3228        cx: &mut Context<Self>,
3229    ) -> Task<Result<Vec<LocationLink>>> {
3230        self.request_lsp(
3231            buffer.clone(),
3232            LanguageServerToQuery::FirstCapable,
3233            GetTypeDefinition { position },
3234            cx,
3235        )
3236    }
3237
3238    pub fn type_definition<T: ToPointUtf16>(
3239        &mut self,
3240        buffer: &Entity<Buffer>,
3241        position: T,
3242        cx: &mut Context<Self>,
3243    ) -> Task<Result<Vec<LocationLink>>> {
3244        let position = position.to_point_utf16(buffer.read(cx));
3245        self.type_definition_impl(buffer, position, cx)
3246    }
3247
3248    pub fn implementation<T: ToPointUtf16>(
3249        &mut self,
3250        buffer: &Entity<Buffer>,
3251        position: T,
3252        cx: &mut Context<Self>,
3253    ) -> Task<Result<Vec<LocationLink>>> {
3254        let position = position.to_point_utf16(buffer.read(cx));
3255        self.request_lsp(
3256            buffer.clone(),
3257            LanguageServerToQuery::FirstCapable,
3258            GetImplementation { position },
3259            cx,
3260        )
3261    }
3262
3263    pub fn references<T: ToPointUtf16>(
3264        &mut self,
3265        buffer: &Entity<Buffer>,
3266        position: T,
3267        cx: &mut Context<Self>,
3268    ) -> Task<Result<Vec<Location>>> {
3269        let position = position.to_point_utf16(buffer.read(cx));
3270        self.request_lsp(
3271            buffer.clone(),
3272            LanguageServerToQuery::FirstCapable,
3273            GetReferences { position },
3274            cx,
3275        )
3276    }
3277
3278    fn document_highlights_impl(
3279        &mut self,
3280        buffer: &Entity<Buffer>,
3281        position: PointUtf16,
3282        cx: &mut Context<Self>,
3283    ) -> Task<Result<Vec<DocumentHighlight>>> {
3284        self.request_lsp(
3285            buffer.clone(),
3286            LanguageServerToQuery::FirstCapable,
3287            GetDocumentHighlights { position },
3288            cx,
3289        )
3290    }
3291
3292    pub fn document_highlights<T: ToPointUtf16>(
3293        &mut self,
3294        buffer: &Entity<Buffer>,
3295        position: T,
3296        cx: &mut Context<Self>,
3297    ) -> Task<Result<Vec<DocumentHighlight>>> {
3298        let position = position.to_point_utf16(buffer.read(cx));
3299        self.document_highlights_impl(buffer, position, cx)
3300    }
3301
3302    pub fn document_symbols(
3303        &mut self,
3304        buffer: &Entity<Buffer>,
3305        cx: &mut Context<Self>,
3306    ) -> Task<Result<Vec<DocumentSymbol>>> {
3307        self.request_lsp(
3308            buffer.clone(),
3309            LanguageServerToQuery::FirstCapable,
3310            GetDocumentSymbols,
3311            cx,
3312        )
3313    }
3314
3315    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3316        self.lsp_store
3317            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3318    }
3319
3320    pub fn open_buffer_for_symbol(
3321        &mut self,
3322        symbol: &Symbol,
3323        cx: &mut Context<Self>,
3324    ) -> Task<Result<Entity<Buffer>>> {
3325        self.lsp_store.update(cx, |lsp_store, cx| {
3326            lsp_store.open_buffer_for_symbol(symbol, cx)
3327        })
3328    }
3329
3330    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3331        let guard = self.retain_remotely_created_models(cx);
3332        let Some(ssh_client) = self.ssh_client.as_ref() else {
3333            return Task::ready(Err(anyhow!("not an ssh project")));
3334        };
3335
3336        let proto_client = ssh_client.read(cx).proto_client();
3337
3338        cx.spawn(async move |project, cx| {
3339            let buffer = proto_client
3340                .request(proto::OpenServerSettings {
3341                    project_id: SSH_PROJECT_ID,
3342                })
3343                .await?;
3344
3345            let buffer = project
3346                .update(cx, |project, cx| {
3347                    project.buffer_store.update(cx, |buffer_store, cx| {
3348                        anyhow::Ok(
3349                            buffer_store
3350                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3351                        )
3352                    })
3353                })??
3354                .await;
3355
3356            drop(guard);
3357            buffer
3358        })
3359    }
3360
3361    pub fn open_local_buffer_via_lsp(
3362        &mut self,
3363        abs_path: lsp::Url,
3364        language_server_id: LanguageServerId,
3365        language_server_name: LanguageServerName,
3366        cx: &mut Context<Self>,
3367    ) -> Task<Result<Entity<Buffer>>> {
3368        self.lsp_store.update(cx, |lsp_store, cx| {
3369            lsp_store.open_local_buffer_via_lsp(
3370                abs_path,
3371                language_server_id,
3372                language_server_name,
3373                cx,
3374            )
3375        })
3376    }
3377
3378    pub fn signature_help<T: ToPointUtf16>(
3379        &self,
3380        buffer: &Entity<Buffer>,
3381        position: T,
3382        cx: &mut Context<Self>,
3383    ) -> Task<Vec<SignatureHelp>> {
3384        self.lsp_store.update(cx, |lsp_store, cx| {
3385            lsp_store.signature_help(buffer, position, cx)
3386        })
3387    }
3388
3389    pub fn hover<T: ToPointUtf16>(
3390        &self,
3391        buffer: &Entity<Buffer>,
3392        position: T,
3393        cx: &mut Context<Self>,
3394    ) -> Task<Vec<Hover>> {
3395        let position = position.to_point_utf16(buffer.read(cx));
3396        self.lsp_store
3397            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3398    }
3399
3400    pub fn linked_edit(
3401        &self,
3402        buffer: &Entity<Buffer>,
3403        position: Anchor,
3404        cx: &mut Context<Self>,
3405    ) -> Task<Result<Vec<Range<Anchor>>>> {
3406        self.lsp_store.update(cx, |lsp_store, cx| {
3407            lsp_store.linked_edit(buffer, position, cx)
3408        })
3409    }
3410
3411    pub fn completions<T: ToOffset + ToPointUtf16>(
3412        &self,
3413        buffer: &Entity<Buffer>,
3414        position: T,
3415        context: CompletionContext,
3416        cx: &mut Context<Self>,
3417    ) -> Task<Result<Option<Vec<Completion>>>> {
3418        let position = position.to_point_utf16(buffer.read(cx));
3419        self.lsp_store.update(cx, |lsp_store, cx| {
3420            lsp_store.completions(buffer, position, context, cx)
3421        })
3422    }
3423
3424    pub fn code_actions<T: Clone + ToOffset>(
3425        &mut self,
3426        buffer_handle: &Entity<Buffer>,
3427        range: Range<T>,
3428        kinds: Option<Vec<CodeActionKind>>,
3429        cx: &mut Context<Self>,
3430    ) -> Task<Result<Vec<CodeAction>>> {
3431        let buffer = buffer_handle.read(cx);
3432        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3433        self.lsp_store.update(cx, |lsp_store, cx| {
3434            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3435        })
3436    }
3437
3438    pub fn code_lens<T: Clone + ToOffset>(
3439        &mut self,
3440        buffer_handle: &Entity<Buffer>,
3441        range: Range<T>,
3442        cx: &mut Context<Self>,
3443    ) -> Task<Result<Vec<CodeAction>>> {
3444        let snapshot = buffer_handle.read(cx).snapshot();
3445        let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3446        let code_lens_actions = self
3447            .lsp_store
3448            .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3449
3450        cx.background_spawn(async move {
3451            let mut code_lens_actions = code_lens_actions.await?;
3452            code_lens_actions.retain(|code_lens_action| {
3453                range
3454                    .start
3455                    .cmp(&code_lens_action.range.start, &snapshot)
3456                    .is_ge()
3457                    && range
3458                        .end
3459                        .cmp(&code_lens_action.range.end, &snapshot)
3460                        .is_le()
3461            });
3462            Ok(code_lens_actions)
3463        })
3464    }
3465
3466    pub fn apply_code_action(
3467        &self,
3468        buffer_handle: Entity<Buffer>,
3469        action: CodeAction,
3470        push_to_history: bool,
3471        cx: &mut Context<Self>,
3472    ) -> Task<Result<ProjectTransaction>> {
3473        self.lsp_store.update(cx, |lsp_store, cx| {
3474            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3475        })
3476    }
3477
3478    pub fn apply_code_action_kind(
3479        &self,
3480        buffers: HashSet<Entity<Buffer>>,
3481        kind: CodeActionKind,
3482        push_to_history: bool,
3483        cx: &mut Context<Self>,
3484    ) -> Task<Result<ProjectTransaction>> {
3485        self.lsp_store.update(cx, |lsp_store, cx| {
3486            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3487        })
3488    }
3489
3490    fn prepare_rename_impl(
3491        &mut self,
3492        buffer: Entity<Buffer>,
3493        position: PointUtf16,
3494        cx: &mut Context<Self>,
3495    ) -> Task<Result<PrepareRenameResponse>> {
3496        self.request_lsp(
3497            buffer,
3498            LanguageServerToQuery::FirstCapable,
3499            PrepareRename { position },
3500            cx,
3501        )
3502    }
3503    pub fn prepare_rename<T: ToPointUtf16>(
3504        &mut self,
3505        buffer: Entity<Buffer>,
3506        position: T,
3507        cx: &mut Context<Self>,
3508    ) -> Task<Result<PrepareRenameResponse>> {
3509        let position = position.to_point_utf16(buffer.read(cx));
3510        self.prepare_rename_impl(buffer, position, cx)
3511    }
3512
3513    pub fn perform_rename<T: ToPointUtf16>(
3514        &mut self,
3515        buffer: Entity<Buffer>,
3516        position: T,
3517        new_name: String,
3518        cx: &mut Context<Self>,
3519    ) -> Task<Result<ProjectTransaction>> {
3520        let push_to_history = true;
3521        let position = position.to_point_utf16(buffer.read(cx));
3522        self.request_lsp(
3523            buffer,
3524            LanguageServerToQuery::FirstCapable,
3525            PerformRename {
3526                position,
3527                new_name,
3528                push_to_history,
3529            },
3530            cx,
3531        )
3532    }
3533
3534    pub fn on_type_format<T: ToPointUtf16>(
3535        &mut self,
3536        buffer: Entity<Buffer>,
3537        position: T,
3538        trigger: String,
3539        push_to_history: bool,
3540        cx: &mut Context<Self>,
3541    ) -> Task<Result<Option<Transaction>>> {
3542        self.lsp_store.update(cx, |lsp_store, cx| {
3543            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3544        })
3545    }
3546
3547    pub fn inline_values(
3548        &mut self,
3549        session: Entity<Session>,
3550        active_stack_frame: ActiveStackFrame,
3551        buffer_handle: Entity<Buffer>,
3552        range: Range<text::Anchor>,
3553        cx: &mut Context<Self>,
3554    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3555        let snapshot = buffer_handle.read(cx).snapshot();
3556
3557        let Some(inline_value_provider) = session
3558            .read(cx)
3559            .adapter_name()
3560            .map(|adapter_name| DapRegistry::global(cx).adapter(&adapter_name))
3561            .and_then(|adapter| adapter.inline_value_provider())
3562        else {
3563            return Task::ready(Err(anyhow::anyhow!("Inline value provider not found")));
3564        };
3565
3566        let mut text_objects =
3567            snapshot.text_object_ranges(range.end..range.end, Default::default());
3568        let text_object_range = text_objects
3569            .find(|(_, obj)| matches!(obj, language::TextObject::AroundFunction))
3570            .map(|(range, _)| snapshot.anchor_before(range.start))
3571            .unwrap_or(range.start);
3572
3573        let variable_ranges = snapshot
3574            .debug_variable_ranges(
3575                text_object_range.to_offset(&snapshot)..range.end.to_offset(&snapshot),
3576            )
3577            .filter_map(|range| {
3578                let lsp_range = language::range_to_lsp(
3579                    range.range.start.to_point_utf16(&snapshot)
3580                        ..range.range.end.to_point_utf16(&snapshot),
3581                )
3582                .ok()?;
3583
3584                Some((
3585                    snapshot.text_for_range(range.range).collect::<String>(),
3586                    lsp_range,
3587                ))
3588            })
3589            .collect::<Vec<_>>();
3590
3591        let inline_values = inline_value_provider.provide(variable_ranges);
3592
3593        let stack_frame_id = active_stack_frame.stack_frame_id;
3594        cx.spawn(async move |this, cx| {
3595            this.update(cx, |project, cx| {
3596                project.dap_store().update(cx, |dap_store, cx| {
3597                    dap_store.resolve_inline_values(
3598                        session,
3599                        stack_frame_id,
3600                        buffer_handle,
3601                        inline_values,
3602                        cx,
3603                    )
3604                })
3605            })?
3606            .await
3607        })
3608    }
3609
3610    pub fn inlay_hints<T: ToOffset>(
3611        &mut self,
3612        buffer_handle: Entity<Buffer>,
3613        range: Range<T>,
3614        cx: &mut Context<Self>,
3615    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3616        let buffer = buffer_handle.read(cx);
3617        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3618        self.lsp_store.update(cx, |lsp_store, cx| {
3619            lsp_store.inlay_hints(buffer_handle, range, cx)
3620        })
3621    }
3622
3623    pub fn resolve_inlay_hint(
3624        &self,
3625        hint: InlayHint,
3626        buffer_handle: Entity<Buffer>,
3627        server_id: LanguageServerId,
3628        cx: &mut Context<Self>,
3629    ) -> Task<anyhow::Result<InlayHint>> {
3630        self.lsp_store.update(cx, |lsp_store, cx| {
3631            lsp_store.resolve_inlay_hint(hint, buffer_handle, server_id, cx)
3632        })
3633    }
3634
3635    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
3636        let (result_tx, result_rx) = smol::channel::unbounded();
3637
3638        let matching_buffers_rx = if query.is_opened_only() {
3639            self.sort_search_candidates(&query, cx)
3640        } else {
3641            self.find_search_candidate_buffers(&query, MAX_SEARCH_RESULT_FILES + 1, cx)
3642        };
3643
3644        cx.spawn(async move |_, cx| {
3645            let mut range_count = 0;
3646            let mut buffer_count = 0;
3647            let mut limit_reached = false;
3648            let query = Arc::new(query);
3649            let mut chunks = matching_buffers_rx.ready_chunks(64);
3650
3651            // Now that we know what paths match the query, we will load at most
3652            // 64 buffers at a time to avoid overwhelming the main thread. For each
3653            // opened buffer, we will spawn a background task that retrieves all the
3654            // ranges in the buffer matched by the query.
3655            let mut chunks = pin!(chunks);
3656            'outer: while let Some(matching_buffer_chunk) = chunks.next().await {
3657                let mut chunk_results = Vec::new();
3658                for buffer in matching_buffer_chunk {
3659                    let buffer = buffer.clone();
3660                    let query = query.clone();
3661                    let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot())?;
3662                    chunk_results.push(cx.background_spawn(async move {
3663                        let ranges = query
3664                            .search(&snapshot, None)
3665                            .await
3666                            .iter()
3667                            .map(|range| {
3668                                snapshot.anchor_before(range.start)
3669                                    ..snapshot.anchor_after(range.end)
3670                            })
3671                            .collect::<Vec<_>>();
3672                        anyhow::Ok((buffer, ranges))
3673                    }));
3674                }
3675
3676                let chunk_results = futures::future::join_all(chunk_results).await;
3677                for result in chunk_results {
3678                    if let Some((buffer, ranges)) = result.log_err() {
3679                        range_count += ranges.len();
3680                        buffer_count += 1;
3681                        result_tx
3682                            .send(SearchResult::Buffer { buffer, ranges })
3683                            .await?;
3684                        if buffer_count > MAX_SEARCH_RESULT_FILES
3685                            || range_count > MAX_SEARCH_RESULT_RANGES
3686                        {
3687                            limit_reached = true;
3688                            break 'outer;
3689                        }
3690                    }
3691                }
3692            }
3693
3694            if limit_reached {
3695                result_tx.send(SearchResult::LimitReached).await?;
3696            }
3697
3698            anyhow::Ok(())
3699        })
3700        .detach();
3701
3702        result_rx
3703    }
3704
3705    fn find_search_candidate_buffers(
3706        &mut self,
3707        query: &SearchQuery,
3708        limit: usize,
3709        cx: &mut Context<Project>,
3710    ) -> Receiver<Entity<Buffer>> {
3711        if self.is_local() {
3712            let fs = self.fs.clone();
3713            self.buffer_store.update(cx, |buffer_store, cx| {
3714                buffer_store.find_search_candidates(query, limit, fs, cx)
3715            })
3716        } else {
3717            self.find_search_candidates_remote(query, limit, cx)
3718        }
3719    }
3720
3721    fn sort_search_candidates(
3722        &mut self,
3723        search_query: &SearchQuery,
3724        cx: &mut Context<Project>,
3725    ) -> Receiver<Entity<Buffer>> {
3726        let worktree_store = self.worktree_store.read(cx);
3727        let mut buffers = search_query
3728            .buffers()
3729            .into_iter()
3730            .flatten()
3731            .filter(|buffer| {
3732                let b = buffer.read(cx);
3733                if let Some(file) = b.file() {
3734                    if !search_query.match_path(file.path()) {
3735                        return false;
3736                    }
3737                    if let Some(entry) = b
3738                        .entry_id(cx)
3739                        .and_then(|entry_id| worktree_store.entry_for_id(entry_id, cx))
3740                    {
3741                        if entry.is_ignored && !search_query.include_ignored() {
3742                            return false;
3743                        }
3744                    }
3745                }
3746                true
3747            })
3748            .collect::<Vec<_>>();
3749        let (tx, rx) = smol::channel::unbounded();
3750        buffers.sort_by(|a, b| match (a.read(cx).file(), b.read(cx).file()) {
3751            (None, None) => a.read(cx).remote_id().cmp(&b.read(cx).remote_id()),
3752            (None, Some(_)) => std::cmp::Ordering::Less,
3753            (Some(_), None) => std::cmp::Ordering::Greater,
3754            (Some(a), Some(b)) => compare_paths((a.path(), true), (b.path(), true)),
3755        });
3756        for buffer in buffers {
3757            tx.send_blocking(buffer.clone()).unwrap()
3758        }
3759
3760        rx
3761    }
3762
3763    fn find_search_candidates_remote(
3764        &mut self,
3765        query: &SearchQuery,
3766        limit: usize,
3767        cx: &mut Context<Project>,
3768    ) -> Receiver<Entity<Buffer>> {
3769        let (tx, rx) = smol::channel::unbounded();
3770
3771        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.ssh_client {
3772            (ssh_client.read(cx).proto_client(), 0)
3773        } else if let Some(remote_id) = self.remote_id() {
3774            (self.client.clone().into(), remote_id)
3775        } else {
3776            return rx;
3777        };
3778
3779        let request = client.request(proto::FindSearchCandidates {
3780            project_id: remote_id,
3781            query: Some(query.to_proto()),
3782            limit: limit as _,
3783        });
3784        let guard = self.retain_remotely_created_models(cx);
3785
3786        cx.spawn(async move |project, cx| {
3787            let response = request.await?;
3788            for buffer_id in response.buffer_ids {
3789                let buffer_id = BufferId::new(buffer_id)?;
3790                let buffer = project
3791                    .update(cx, |project, cx| {
3792                        project.buffer_store.update(cx, |buffer_store, cx| {
3793                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3794                        })
3795                    })?
3796                    .await?;
3797                let _ = tx.send(buffer).await;
3798            }
3799
3800            drop(guard);
3801            anyhow::Ok(())
3802        })
3803        .detach_and_log_err(cx);
3804        rx
3805    }
3806
3807    pub fn request_lsp<R: LspCommand>(
3808        &mut self,
3809        buffer_handle: Entity<Buffer>,
3810        server: LanguageServerToQuery,
3811        request: R,
3812        cx: &mut Context<Self>,
3813    ) -> Task<Result<R::Response>>
3814    where
3815        <R::LspRequest as lsp::request::Request>::Result: Send,
3816        <R::LspRequest as lsp::request::Request>::Params: Send,
3817    {
3818        let guard = self.retain_remotely_created_models(cx);
3819        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3820            lsp_store.request_lsp(buffer_handle, server, request, cx)
3821        });
3822        cx.spawn(async move |_, _| {
3823            let result = task.await;
3824            drop(guard);
3825            result
3826        })
3827    }
3828
3829    /// Move a worktree to a new position in the worktree order.
3830    ///
3831    /// The worktree will moved to the opposite side of the destination worktree.
3832    ///
3833    /// # Example
3834    ///
3835    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
3836    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
3837    ///
3838    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
3839    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
3840    ///
3841    /// # Errors
3842    ///
3843    /// An error will be returned if the worktree or destination worktree are not found.
3844    pub fn move_worktree(
3845        &mut self,
3846        source: WorktreeId,
3847        destination: WorktreeId,
3848        cx: &mut Context<Self>,
3849    ) -> Result<()> {
3850        self.worktree_store.update(cx, |worktree_store, cx| {
3851            worktree_store.move_worktree(source, destination, cx)
3852        })
3853    }
3854
3855    pub fn find_or_create_worktree(
3856        &mut self,
3857        abs_path: impl AsRef<Path>,
3858        visible: bool,
3859        cx: &mut Context<Self>,
3860    ) -> Task<Result<(Entity<Worktree>, PathBuf)>> {
3861        self.worktree_store.update(cx, |worktree_store, cx| {
3862            worktree_store.find_or_create_worktree(abs_path, visible, cx)
3863        })
3864    }
3865
3866    pub fn find_worktree(&self, abs_path: &Path, cx: &App) -> Option<(Entity<Worktree>, PathBuf)> {
3867        self.worktree_store.read_with(cx, |worktree_store, cx| {
3868            worktree_store.find_worktree(abs_path, cx)
3869        })
3870    }
3871
3872    pub fn is_shared(&self) -> bool {
3873        match &self.client_state {
3874            ProjectClientState::Shared { .. } => true,
3875            ProjectClientState::Local => false,
3876            ProjectClientState::Remote { .. } => true,
3877        }
3878    }
3879
3880    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
3881    pub fn resolve_path_in_buffer(
3882        &self,
3883        path: &str,
3884        buffer: &Entity<Buffer>,
3885        cx: &mut Context<Self>,
3886    ) -> Task<Option<ResolvedPath>> {
3887        let path_buf = PathBuf::from(path);
3888        if path_buf.is_absolute() || path.starts_with("~") {
3889            self.resolve_abs_path(path, cx)
3890        } else {
3891            self.resolve_path_in_worktrees(path_buf, buffer, cx)
3892        }
3893    }
3894
3895    pub fn resolve_abs_file_path(
3896        &self,
3897        path: &str,
3898        cx: &mut Context<Self>,
3899    ) -> Task<Option<ResolvedPath>> {
3900        let resolve_task = self.resolve_abs_path(path, cx);
3901        cx.background_spawn(async move {
3902            let resolved_path = resolve_task.await;
3903            resolved_path.filter(|path| path.is_file())
3904        })
3905    }
3906
3907    pub fn resolve_abs_path(
3908        &self,
3909        path: &str,
3910        cx: &mut Context<Self>,
3911    ) -> Task<Option<ResolvedPath>> {
3912        if self.is_local() {
3913            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3914            let fs = self.fs.clone();
3915            cx.background_spawn(async move {
3916                let path = expanded.as_path();
3917                let metadata = fs.metadata(path).await.ok().flatten();
3918
3919                metadata.map(|metadata| ResolvedPath::AbsPath {
3920                    path: expanded,
3921                    is_dir: metadata.is_dir,
3922                })
3923            })
3924        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3925            let request_path = Path::new(path);
3926            let request = ssh_client
3927                .read(cx)
3928                .proto_client()
3929                .request(proto::GetPathMetadata {
3930                    project_id: SSH_PROJECT_ID,
3931                    path: request_path.to_proto(),
3932                });
3933            cx.background_spawn(async move {
3934                let response = request.await.log_err()?;
3935                if response.exists {
3936                    Some(ResolvedPath::AbsPath {
3937                        path: PathBuf::from_proto(response.path),
3938                        is_dir: response.is_dir,
3939                    })
3940                } else {
3941                    None
3942                }
3943            })
3944        } else {
3945            return Task::ready(None);
3946        }
3947    }
3948
3949    fn resolve_path_in_worktrees(
3950        &self,
3951        path: PathBuf,
3952        buffer: &Entity<Buffer>,
3953        cx: &mut Context<Self>,
3954    ) -> Task<Option<ResolvedPath>> {
3955        let mut candidates = vec![path.clone()];
3956
3957        if let Some(file) = buffer.read(cx).file() {
3958            if let Some(dir) = file.path().parent() {
3959                let joined = dir.to_path_buf().join(path);
3960                candidates.push(joined);
3961            }
3962        }
3963
3964        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3965        let worktrees_with_ids: Vec<_> = self
3966            .worktrees(cx)
3967            .map(|worktree| {
3968                let id = worktree.read(cx).id();
3969                (worktree, id)
3970            })
3971            .collect();
3972
3973        cx.spawn(async move |_, mut cx| {
3974            if let Some(buffer_worktree_id) = buffer_worktree_id {
3975                if let Some((worktree, _)) = worktrees_with_ids
3976                    .iter()
3977                    .find(|(_, id)| *id == buffer_worktree_id)
3978                {
3979                    for candidate in candidates.iter() {
3980                        if let Some(path) =
3981                            Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3982                        {
3983                            return Some(path);
3984                        }
3985                    }
3986                }
3987            }
3988            for (worktree, id) in worktrees_with_ids {
3989                if Some(id) == buffer_worktree_id {
3990                    continue;
3991                }
3992                for candidate in candidates.iter() {
3993                    if let Some(path) =
3994                        Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3995                    {
3996                        return Some(path);
3997                    }
3998                }
3999            }
4000            None
4001        })
4002    }
4003
4004    fn resolve_path_in_worktree(
4005        worktree: &Entity<Worktree>,
4006        path: &PathBuf,
4007        cx: &mut AsyncApp,
4008    ) -> Option<ResolvedPath> {
4009        worktree
4010            .update(cx, |worktree, _| {
4011                let root_entry_path = &worktree.root_entry()?.path;
4012                let resolved = resolve_path(root_entry_path, path);
4013                let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4014                worktree.entry_for_path(stripped).map(|entry| {
4015                    let project_path = ProjectPath {
4016                        worktree_id: worktree.id(),
4017                        path: entry.path.clone(),
4018                    };
4019                    ResolvedPath::ProjectPath {
4020                        project_path,
4021                        is_dir: entry.is_dir(),
4022                    }
4023                })
4024            })
4025            .ok()?
4026    }
4027
4028    pub fn list_directory(
4029        &self,
4030        query: String,
4031        cx: &mut Context<Self>,
4032    ) -> Task<Result<Vec<DirectoryItem>>> {
4033        if self.is_local() {
4034            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
4035        } else if let Some(session) = self.ssh_client.as_ref() {
4036            let path_buf = PathBuf::from(query);
4037            let request = proto::ListRemoteDirectory {
4038                dev_server_id: SSH_PROJECT_ID,
4039                path: path_buf.to_proto(),
4040                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4041            };
4042
4043            let response = session.read(cx).proto_client().request(request);
4044            cx.background_spawn(async move {
4045                let proto::ListRemoteDirectoryResponse {
4046                    entries,
4047                    entry_info,
4048                } = response.await?;
4049                Ok(entries
4050                    .into_iter()
4051                    .zip(entry_info)
4052                    .map(|(entry, info)| DirectoryItem {
4053                        path: PathBuf::from(entry),
4054                        is_dir: info.is_dir,
4055                    })
4056                    .collect())
4057            })
4058        } else {
4059            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4060        }
4061    }
4062
4063    pub fn create_worktree(
4064        &mut self,
4065        abs_path: impl AsRef<Path>,
4066        visible: bool,
4067        cx: &mut Context<Self>,
4068    ) -> Task<Result<Entity<Worktree>>> {
4069        self.worktree_store.update(cx, |worktree_store, cx| {
4070            worktree_store.create_worktree(abs_path, visible, cx)
4071        })
4072    }
4073
4074    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4075        self.worktree_store.update(cx, |worktree_store, cx| {
4076            worktree_store.remove_worktree(id_to_remove, cx);
4077        });
4078    }
4079
4080    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4081        self.worktree_store.update(cx, |worktree_store, cx| {
4082            worktree_store.add(worktree, cx);
4083        });
4084    }
4085
4086    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4087        let new_active_entry = entry.and_then(|project_path| {
4088            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4089            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4090            Some(entry.id)
4091        });
4092        if new_active_entry != self.active_entry {
4093            self.active_entry = new_active_entry;
4094            self.lsp_store.update(cx, |lsp_store, _| {
4095                lsp_store.set_active_entry(new_active_entry);
4096            });
4097            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4098        }
4099    }
4100
4101    pub fn language_servers_running_disk_based_diagnostics<'a>(
4102        &'a self,
4103        cx: &'a App,
4104    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4105        self.lsp_store
4106            .read(cx)
4107            .language_servers_running_disk_based_diagnostics()
4108    }
4109
4110    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4111        self.lsp_store
4112            .read(cx)
4113            .diagnostic_summary(include_ignored, cx)
4114    }
4115
4116    pub fn diagnostic_summaries<'a>(
4117        &'a self,
4118        include_ignored: bool,
4119        cx: &'a App,
4120    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4121        self.lsp_store
4122            .read(cx)
4123            .diagnostic_summaries(include_ignored, cx)
4124    }
4125
4126    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4127        self.active_entry
4128    }
4129
4130    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4131        self.worktree_store.read(cx).entry_for_path(path, cx)
4132    }
4133
4134    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4135        let worktree = self.worktree_for_entry(entry_id, cx)?;
4136        let worktree = worktree.read(cx);
4137        let worktree_id = worktree.id();
4138        let path = worktree.entry_for_id(entry_id)?.path.clone();
4139        Some(ProjectPath { worktree_id, path })
4140    }
4141
4142    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4143        self.worktree_for_id(project_path.worktree_id, cx)?
4144            .read(cx)
4145            .absolutize(&project_path.path)
4146            .ok()
4147    }
4148
4149    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4150    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4151    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4152    /// the first visible worktree that has an entry for that relative path.
4153    ///
4154    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4155    /// root name from paths.
4156    ///
4157    /// # Arguments
4158    ///
4159    /// * `path` - A full path that starts with a worktree root name, or alternatively a
4160    ///            relative path within a visible worktree.
4161    /// * `cx` - A reference to the `AppContext`.
4162    ///
4163    /// # Returns
4164    ///
4165    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4166    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4167        let path = path.as_ref();
4168        let worktree_store = self.worktree_store.read(cx);
4169
4170        for worktree in worktree_store.visible_worktrees(cx) {
4171            let worktree_root_name = worktree.read(cx).root_name();
4172            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4173                return Some(ProjectPath {
4174                    worktree_id: worktree.read(cx).id(),
4175                    path: relative_path.into(),
4176                });
4177            }
4178        }
4179
4180        for worktree in worktree_store.visible_worktrees(cx) {
4181            let worktree = worktree.read(cx);
4182            if let Some(entry) = worktree.entry_for_path(path) {
4183                return Some(ProjectPath {
4184                    worktree_id: worktree.id(),
4185                    path: entry.path.clone(),
4186                });
4187            }
4188        }
4189
4190        None
4191    }
4192
4193    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4194        self.find_worktree(abs_path, cx)
4195            .map(|(worktree, relative_path)| ProjectPath {
4196                worktree_id: worktree.read(cx).id(),
4197                path: relative_path.into(),
4198            })
4199    }
4200
4201    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4202        Some(
4203            self.worktree_for_id(project_path.worktree_id, cx)?
4204                .read(cx)
4205                .abs_path()
4206                .to_path_buf(),
4207        )
4208    }
4209
4210    pub fn blame_buffer(
4211        &self,
4212        buffer: &Entity<Buffer>,
4213        version: Option<clock::Global>,
4214        cx: &mut App,
4215    ) -> Task<Result<Option<Blame>>> {
4216        self.git_store.update(cx, |git_store, cx| {
4217            git_store.blame_buffer(buffer, version, cx)
4218        })
4219    }
4220
4221    pub fn get_permalink_to_line(
4222        &self,
4223        buffer: &Entity<Buffer>,
4224        selection: Range<u32>,
4225        cx: &mut App,
4226    ) -> Task<Result<url::Url>> {
4227        self.git_store.update(cx, |git_store, cx| {
4228            git_store.get_permalink_to_line(buffer, selection, cx)
4229        })
4230    }
4231
4232    // RPC message handlers
4233
4234    async fn handle_unshare_project(
4235        this: Entity<Self>,
4236        _: TypedEnvelope<proto::UnshareProject>,
4237        mut cx: AsyncApp,
4238    ) -> Result<()> {
4239        this.update(&mut cx, |this, cx| {
4240            if this.is_local() || this.is_via_ssh() {
4241                this.unshare(cx)?;
4242            } else {
4243                this.disconnected_from_host(cx);
4244            }
4245            Ok(())
4246        })?
4247    }
4248
4249    async fn handle_add_collaborator(
4250        this: Entity<Self>,
4251        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4252        mut cx: AsyncApp,
4253    ) -> Result<()> {
4254        let collaborator = envelope
4255            .payload
4256            .collaborator
4257            .take()
4258            .ok_or_else(|| anyhow!("empty collaborator"))?;
4259
4260        let collaborator = Collaborator::from_proto(collaborator)?;
4261        this.update(&mut cx, |this, cx| {
4262            this.buffer_store.update(cx, |buffer_store, _| {
4263                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4264            });
4265            this.breakpoint_store.read(cx).broadcast();
4266            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4267            this.collaborators
4268                .insert(collaborator.peer_id, collaborator);
4269        })?;
4270
4271        Ok(())
4272    }
4273
4274    async fn handle_update_project_collaborator(
4275        this: Entity<Self>,
4276        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4277        mut cx: AsyncApp,
4278    ) -> Result<()> {
4279        let old_peer_id = envelope
4280            .payload
4281            .old_peer_id
4282            .ok_or_else(|| anyhow!("missing old peer id"))?;
4283        let new_peer_id = envelope
4284            .payload
4285            .new_peer_id
4286            .ok_or_else(|| anyhow!("missing new peer id"))?;
4287        this.update(&mut cx, |this, cx| {
4288            let collaborator = this
4289                .collaborators
4290                .remove(&old_peer_id)
4291                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4292            let is_host = collaborator.is_host;
4293            this.collaborators.insert(new_peer_id, collaborator);
4294
4295            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4296            this.buffer_store.update(cx, |buffer_store, _| {
4297                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4298            });
4299
4300            if is_host {
4301                this.buffer_store
4302                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4303                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4304                    .unwrap();
4305                cx.emit(Event::HostReshared);
4306            }
4307
4308            cx.emit(Event::CollaboratorUpdated {
4309                old_peer_id,
4310                new_peer_id,
4311            });
4312            Ok(())
4313        })?
4314    }
4315
4316    async fn handle_remove_collaborator(
4317        this: Entity<Self>,
4318        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4319        mut cx: AsyncApp,
4320    ) -> Result<()> {
4321        this.update(&mut cx, |this, cx| {
4322            let peer_id = envelope
4323                .payload
4324                .peer_id
4325                .ok_or_else(|| anyhow!("invalid peer id"))?;
4326            let replica_id = this
4327                .collaborators
4328                .remove(&peer_id)
4329                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4330                .replica_id;
4331            this.buffer_store.update(cx, |buffer_store, cx| {
4332                buffer_store.forget_shared_buffers_for(&peer_id);
4333                for buffer in buffer_store.buffers() {
4334                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4335                }
4336            });
4337            this.git_store.update(cx, |git_store, _| {
4338                git_store.forget_shared_diffs_for(&peer_id);
4339            });
4340
4341            cx.emit(Event::CollaboratorLeft(peer_id));
4342            Ok(())
4343        })?
4344    }
4345
4346    async fn handle_update_project(
4347        this: Entity<Self>,
4348        envelope: TypedEnvelope<proto::UpdateProject>,
4349        mut cx: AsyncApp,
4350    ) -> Result<()> {
4351        this.update(&mut cx, |this, cx| {
4352            // Don't handle messages that were sent before the response to us joining the project
4353            if envelope.message_id > this.join_project_response_message_id {
4354                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4355            }
4356            Ok(())
4357        })?
4358    }
4359
4360    async fn handle_toast(
4361        this: Entity<Self>,
4362        envelope: TypedEnvelope<proto::Toast>,
4363        mut cx: AsyncApp,
4364    ) -> Result<()> {
4365        this.update(&mut cx, |_, cx| {
4366            cx.emit(Event::Toast {
4367                notification_id: envelope.payload.notification_id.into(),
4368                message: envelope.payload.message,
4369            });
4370            Ok(())
4371        })?
4372    }
4373
4374    async fn handle_language_server_prompt_request(
4375        this: Entity<Self>,
4376        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4377        mut cx: AsyncApp,
4378    ) -> Result<proto::LanguageServerPromptResponse> {
4379        let (tx, mut rx) = smol::channel::bounded(1);
4380        let actions: Vec<_> = envelope
4381            .payload
4382            .actions
4383            .into_iter()
4384            .map(|action| MessageActionItem {
4385                title: action,
4386                properties: Default::default(),
4387            })
4388            .collect();
4389        this.update(&mut cx, |_, cx| {
4390            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4391                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4392                message: envelope.payload.message,
4393                actions: actions.clone(),
4394                lsp_name: envelope.payload.lsp_name,
4395                response_channel: tx,
4396            }));
4397
4398            anyhow::Ok(())
4399        })??;
4400
4401        // We drop `this` to avoid holding a reference in this future for too
4402        // long.
4403        // If we keep the reference, we might not drop the `Project` early
4404        // enough when closing a window and it will only get releases on the
4405        // next `flush_effects()` call.
4406        drop(this);
4407
4408        let mut rx = pin!(rx);
4409        let answer = rx.next().await;
4410
4411        Ok(LanguageServerPromptResponse {
4412            action_response: answer.and_then(|answer| {
4413                actions
4414                    .iter()
4415                    .position(|action| *action == answer)
4416                    .map(|index| index as u64)
4417            }),
4418        })
4419    }
4420
4421    async fn handle_hide_toast(
4422        this: Entity<Self>,
4423        envelope: TypedEnvelope<proto::HideToast>,
4424        mut cx: AsyncApp,
4425    ) -> Result<()> {
4426        this.update(&mut cx, |_, cx| {
4427            cx.emit(Event::HideToast {
4428                notification_id: envelope.payload.notification_id.into(),
4429            });
4430            Ok(())
4431        })?
4432    }
4433
4434    // Collab sends UpdateWorktree protos as messages
4435    async fn handle_update_worktree(
4436        this: Entity<Self>,
4437        envelope: TypedEnvelope<proto::UpdateWorktree>,
4438        mut cx: AsyncApp,
4439    ) -> Result<()> {
4440        this.update(&mut cx, |this, cx| {
4441            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4442            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4443                worktree.update(cx, |worktree, _| {
4444                    let worktree = worktree.as_remote_mut().unwrap();
4445                    worktree.update_from_remote(envelope.payload);
4446                });
4447            }
4448            Ok(())
4449        })?
4450    }
4451
4452    async fn handle_update_buffer_from_ssh(
4453        this: Entity<Self>,
4454        envelope: TypedEnvelope<proto::UpdateBuffer>,
4455        cx: AsyncApp,
4456    ) -> Result<proto::Ack> {
4457        let buffer_store = this.read_with(&cx, |this, cx| {
4458            if let Some(remote_id) = this.remote_id() {
4459                let mut payload = envelope.payload.clone();
4460                payload.project_id = remote_id;
4461                cx.background_spawn(this.client.request(payload))
4462                    .detach_and_log_err(cx);
4463            }
4464            this.buffer_store.clone()
4465        })?;
4466        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4467    }
4468
4469    async fn handle_update_buffer(
4470        this: Entity<Self>,
4471        envelope: TypedEnvelope<proto::UpdateBuffer>,
4472        cx: AsyncApp,
4473    ) -> Result<proto::Ack> {
4474        let buffer_store = this.read_with(&cx, |this, cx| {
4475            if let Some(ssh) = &this.ssh_client {
4476                let mut payload = envelope.payload.clone();
4477                payload.project_id = SSH_PROJECT_ID;
4478                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4479                    .detach_and_log_err(cx);
4480            }
4481            this.buffer_store.clone()
4482        })?;
4483        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4484    }
4485
4486    fn retain_remotely_created_models(
4487        &mut self,
4488        cx: &mut Context<Self>,
4489    ) -> RemotelyCreatedModelGuard {
4490        {
4491            let mut remotely_create_models = self.remotely_created_models.lock();
4492            if remotely_create_models.retain_count == 0 {
4493                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4494                remotely_create_models.worktrees =
4495                    self.worktree_store.read(cx).worktrees().collect();
4496            }
4497            remotely_create_models.retain_count += 1;
4498        }
4499        RemotelyCreatedModelGuard {
4500            remote_models: Arc::downgrade(&self.remotely_created_models),
4501        }
4502    }
4503
4504    async fn handle_create_buffer_for_peer(
4505        this: Entity<Self>,
4506        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4507        mut cx: AsyncApp,
4508    ) -> Result<()> {
4509        this.update(&mut cx, |this, cx| {
4510            this.buffer_store.update(cx, |buffer_store, cx| {
4511                buffer_store.handle_create_buffer_for_peer(
4512                    envelope,
4513                    this.replica_id(),
4514                    this.capability(),
4515                    cx,
4516                )
4517            })
4518        })?
4519    }
4520
4521    async fn handle_synchronize_buffers(
4522        this: Entity<Self>,
4523        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4524        mut cx: AsyncApp,
4525    ) -> Result<proto::SynchronizeBuffersResponse> {
4526        let response = this.update(&mut cx, |this, cx| {
4527            let client = this.client.clone();
4528            this.buffer_store.update(cx, |this, cx| {
4529                this.handle_synchronize_buffers(envelope, cx, client)
4530            })
4531        })??;
4532
4533        Ok(response)
4534    }
4535
4536    async fn handle_search_candidate_buffers(
4537        this: Entity<Self>,
4538        envelope: TypedEnvelope<proto::FindSearchCandidates>,
4539        mut cx: AsyncApp,
4540    ) -> Result<proto::FindSearchCandidatesResponse> {
4541        let peer_id = envelope.original_sender_id()?;
4542        let message = envelope.payload;
4543        let query = SearchQuery::from_proto(
4544            message
4545                .query
4546                .ok_or_else(|| anyhow!("missing query field"))?,
4547        )?;
4548        let results = this.update(&mut cx, |this, cx| {
4549            this.find_search_candidate_buffers(&query, message.limit as _, cx)
4550        })?;
4551
4552        let mut response = proto::FindSearchCandidatesResponse {
4553            buffer_ids: Vec::new(),
4554        };
4555
4556        while let Ok(buffer) = results.recv().await {
4557            this.update(&mut cx, |this, cx| {
4558                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4559                response.buffer_ids.push(buffer_id.to_proto());
4560            })?;
4561        }
4562
4563        Ok(response)
4564    }
4565
4566    async fn handle_open_buffer_by_id(
4567        this: Entity<Self>,
4568        envelope: TypedEnvelope<proto::OpenBufferById>,
4569        mut cx: AsyncApp,
4570    ) -> Result<proto::OpenBufferResponse> {
4571        let peer_id = envelope.original_sender_id()?;
4572        let buffer_id = BufferId::new(envelope.payload.id)?;
4573        let buffer = this
4574            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4575            .await?;
4576        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4577    }
4578
4579    async fn handle_open_buffer_by_path(
4580        this: Entity<Self>,
4581        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4582        mut cx: AsyncApp,
4583    ) -> Result<proto::OpenBufferResponse> {
4584        let peer_id = envelope.original_sender_id()?;
4585        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4586        let open_buffer = this.update(&mut cx, |this, cx| {
4587            this.open_buffer(
4588                ProjectPath {
4589                    worktree_id,
4590                    path: Arc::<Path>::from_proto(envelope.payload.path),
4591                },
4592                cx,
4593            )
4594        })?;
4595
4596        let buffer = open_buffer.await?;
4597        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4598    }
4599
4600    async fn handle_open_new_buffer(
4601        this: Entity<Self>,
4602        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4603        mut cx: AsyncApp,
4604    ) -> Result<proto::OpenBufferResponse> {
4605        let buffer = this
4606            .update(&mut cx, |this, cx| this.create_buffer(cx))?
4607            .await?;
4608        let peer_id = envelope.original_sender_id()?;
4609
4610        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4611    }
4612
4613    fn respond_to_open_buffer_request(
4614        this: Entity<Self>,
4615        buffer: Entity<Buffer>,
4616        peer_id: proto::PeerId,
4617        cx: &mut AsyncApp,
4618    ) -> Result<proto::OpenBufferResponse> {
4619        this.update(cx, |this, cx| {
4620            let is_private = buffer
4621                .read(cx)
4622                .file()
4623                .map(|f| f.is_private())
4624                .unwrap_or_default();
4625            if is_private {
4626                Err(anyhow!(ErrorCode::UnsharedItem))
4627            } else {
4628                Ok(proto::OpenBufferResponse {
4629                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4630                })
4631            }
4632        })?
4633    }
4634
4635    fn create_buffer_for_peer(
4636        &mut self,
4637        buffer: &Entity<Buffer>,
4638        peer_id: proto::PeerId,
4639        cx: &mut App,
4640    ) -> BufferId {
4641        self.buffer_store
4642            .update(cx, |buffer_store, cx| {
4643                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4644            })
4645            .detach_and_log_err(cx);
4646        buffer.read(cx).remote_id()
4647    }
4648
4649    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4650        let project_id = match self.client_state {
4651            ProjectClientState::Remote {
4652                sharing_has_stopped,
4653                remote_id,
4654                ..
4655            } => {
4656                if sharing_has_stopped {
4657                    return Task::ready(Err(anyhow!(
4658                        "can't synchronize remote buffers on a readonly project"
4659                    )));
4660                } else {
4661                    remote_id
4662                }
4663            }
4664            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4665                return Task::ready(Err(anyhow!(
4666                    "can't synchronize remote buffers on a local project"
4667                )));
4668            }
4669        };
4670
4671        let client = self.client.clone();
4672        cx.spawn(async move |this, cx| {
4673            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4674                this.buffer_store.read(cx).buffer_version_info(cx)
4675            })?;
4676            let response = client
4677                .request(proto::SynchronizeBuffers {
4678                    project_id,
4679                    buffers,
4680                })
4681                .await?;
4682
4683            let send_updates_for_buffers = this.update(cx, |this, cx| {
4684                response
4685                    .buffers
4686                    .into_iter()
4687                    .map(|buffer| {
4688                        let client = client.clone();
4689                        let buffer_id = match BufferId::new(buffer.id) {
4690                            Ok(id) => id,
4691                            Err(e) => {
4692                                return Task::ready(Err(e));
4693                            }
4694                        };
4695                        let remote_version = language::proto::deserialize_version(&buffer.version);
4696                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4697                            let operations =
4698                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4699                            cx.background_spawn(async move {
4700                                let operations = operations.await;
4701                                for chunk in split_operations(operations) {
4702                                    client
4703                                        .request(proto::UpdateBuffer {
4704                                            project_id,
4705                                            buffer_id: buffer_id.into(),
4706                                            operations: chunk,
4707                                        })
4708                                        .await?;
4709                                }
4710                                anyhow::Ok(())
4711                            })
4712                        } else {
4713                            Task::ready(Ok(()))
4714                        }
4715                    })
4716                    .collect::<Vec<_>>()
4717            })?;
4718
4719            // Any incomplete buffers have open requests waiting. Request that the host sends
4720            // creates these buffers for us again to unblock any waiting futures.
4721            for id in incomplete_buffer_ids {
4722                cx.background_spawn(client.request(proto::OpenBufferById {
4723                    project_id,
4724                    id: id.into(),
4725                }))
4726                .detach();
4727            }
4728
4729            futures::future::join_all(send_updates_for_buffers)
4730                .await
4731                .into_iter()
4732                .collect()
4733        })
4734    }
4735
4736    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4737        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4738    }
4739
4740    /// Iterator of all open buffers that have unsaved changes
4741    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4742        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4743            let buf = buf.read(cx);
4744            if buf.is_dirty() {
4745                buf.project_path(cx)
4746            } else {
4747                None
4748            }
4749        })
4750    }
4751
4752    fn set_worktrees_from_proto(
4753        &mut self,
4754        worktrees: Vec<proto::WorktreeMetadata>,
4755        cx: &mut Context<Project>,
4756    ) -> Result<()> {
4757        self.worktree_store.update(cx, |worktree_store, cx| {
4758            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4759        })
4760    }
4761
4762    fn set_collaborators_from_proto(
4763        &mut self,
4764        messages: Vec<proto::Collaborator>,
4765        cx: &mut Context<Self>,
4766    ) -> Result<()> {
4767        let mut collaborators = HashMap::default();
4768        for message in messages {
4769            let collaborator = Collaborator::from_proto(message)?;
4770            collaborators.insert(collaborator.peer_id, collaborator);
4771        }
4772        for old_peer_id in self.collaborators.keys() {
4773            if !collaborators.contains_key(old_peer_id) {
4774                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4775            }
4776        }
4777        self.collaborators = collaborators;
4778        Ok(())
4779    }
4780
4781    pub fn supplementary_language_servers<'a>(
4782        &'a self,
4783        cx: &'a App,
4784    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4785        self.lsp_store.read(cx).supplementary_language_servers()
4786    }
4787
4788    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4789        self.lsp_store.update(cx, |this, cx| {
4790            this.language_servers_for_local_buffer(buffer, cx)
4791                .any(
4792                    |(_, server)| match server.capabilities().inlay_hint_provider {
4793                        Some(lsp::OneOf::Left(enabled)) => enabled,
4794                        Some(lsp::OneOf::Right(_)) => true,
4795                        None => false,
4796                    },
4797                )
4798        })
4799    }
4800
4801    pub fn language_server_id_for_name(
4802        &self,
4803        buffer: &Buffer,
4804        name: &str,
4805        cx: &mut App,
4806    ) -> Task<Option<LanguageServerId>> {
4807        if self.is_local() {
4808            Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4809                lsp_store
4810                    .language_servers_for_local_buffer(buffer, cx)
4811                    .find_map(|(adapter, server)| {
4812                        if adapter.name.0 == name {
4813                            Some(server.server_id())
4814                        } else {
4815                            None
4816                        }
4817                    })
4818            }))
4819        } else if let Some(project_id) = self.remote_id() {
4820            let request = self.client.request(proto::LanguageServerIdForName {
4821                project_id,
4822                buffer_id: buffer.remote_id().to_proto(),
4823                name: name.to_string(),
4824            });
4825            cx.background_spawn(async move {
4826                let response = request.await.log_err()?;
4827                response.server_id.map(LanguageServerId::from_proto)
4828            })
4829        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4830            let request =
4831                ssh_client
4832                    .read(cx)
4833                    .proto_client()
4834                    .request(proto::LanguageServerIdForName {
4835                        project_id: SSH_PROJECT_ID,
4836                        buffer_id: buffer.remote_id().to_proto(),
4837                        name: name.to_string(),
4838                    });
4839            cx.background_spawn(async move {
4840                let response = request.await.log_err()?;
4841                response.server_id.map(LanguageServerId::from_proto)
4842            })
4843        } else {
4844            Task::ready(None)
4845        }
4846    }
4847
4848    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4849        self.lsp_store.update(cx, |this, cx| {
4850            this.language_servers_for_local_buffer(buffer, cx)
4851                .next()
4852                .is_some()
4853        })
4854    }
4855
4856    pub fn git_init(
4857        &self,
4858        path: Arc<Path>,
4859        fallback_branch_name: String,
4860        cx: &App,
4861    ) -> Task<Result<()>> {
4862        self.git_store
4863            .read(cx)
4864            .git_init(path, fallback_branch_name, cx)
4865    }
4866
4867    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4868        &self.buffer_store
4869    }
4870
4871    pub fn git_store(&self) -> &Entity<GitStore> {
4872        &self.git_store
4873    }
4874
4875    #[cfg(test)]
4876    fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4877        cx.spawn(async move |this, cx| {
4878            let scans_complete = this
4879                .read_with(cx, |this, cx| {
4880                    this.worktrees(cx)
4881                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4882                        .collect::<Vec<_>>()
4883                })
4884                .unwrap();
4885            join_all(scans_complete).await;
4886            let barriers = this
4887                .update(cx, |this, cx| {
4888                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4889                    repos
4890                        .into_iter()
4891                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4892                        .collect::<Vec<_>>()
4893                })
4894                .unwrap();
4895            join_all(barriers).await;
4896        })
4897    }
4898
4899    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4900        self.git_store.read(cx).active_repository()
4901    }
4902
4903    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4904        self.git_store.read(cx).repositories()
4905    }
4906
4907    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4908        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4909    }
4910
4911    pub fn set_agent_location(
4912        &mut self,
4913        new_location: Option<AgentLocation>,
4914        cx: &mut Context<Self>,
4915    ) {
4916        if let Some(old_location) = self.agent_location.as_ref() {
4917            old_location
4918                .buffer
4919                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
4920                .ok();
4921        }
4922
4923        if let Some(location) = new_location.as_ref() {
4924            location
4925                .buffer
4926                .update(cx, |buffer, cx| {
4927                    buffer.set_agent_selections(
4928                        Arc::from([language::Selection {
4929                            id: 0,
4930                            start: location.position,
4931                            end: location.position,
4932                            reversed: false,
4933                            goal: language::SelectionGoal::None,
4934                        }]),
4935                        false,
4936                        CursorShape::Hollow,
4937                        cx,
4938                    )
4939                })
4940                .ok();
4941        }
4942
4943        self.agent_location = new_location;
4944        cx.emit(Event::AgentLocationChanged);
4945    }
4946
4947    pub fn agent_location(&self) -> Option<AgentLocation> {
4948        self.agent_location.clone()
4949    }
4950}
4951
4952pub struct PathMatchCandidateSet {
4953    pub snapshot: Snapshot,
4954    pub include_ignored: bool,
4955    pub include_root_name: bool,
4956    pub candidates: Candidates,
4957}
4958
4959pub enum Candidates {
4960    /// Only consider directories.
4961    Directories,
4962    /// Only consider files.
4963    Files,
4964    /// Consider directories and files.
4965    Entries,
4966}
4967
4968impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4969    type Candidates = PathMatchCandidateSetIter<'a>;
4970
4971    fn id(&self) -> usize {
4972        self.snapshot.id().to_usize()
4973    }
4974
4975    fn len(&self) -> usize {
4976        match self.candidates {
4977            Candidates::Files => {
4978                if self.include_ignored {
4979                    self.snapshot.file_count()
4980                } else {
4981                    self.snapshot.visible_file_count()
4982                }
4983            }
4984
4985            Candidates::Directories => {
4986                if self.include_ignored {
4987                    self.snapshot.dir_count()
4988                } else {
4989                    self.snapshot.visible_dir_count()
4990                }
4991            }
4992
4993            Candidates::Entries => {
4994                if self.include_ignored {
4995                    self.snapshot.entry_count()
4996                } else {
4997                    self.snapshot.visible_entry_count()
4998                }
4999            }
5000        }
5001    }
5002
5003    fn prefix(&self) -> Arc<str> {
5004        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5005            self.snapshot.root_name().into()
5006        } else if self.include_root_name {
5007            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5008        } else {
5009            Arc::default()
5010        }
5011    }
5012
5013    fn candidates(&'a self, start: usize) -> Self::Candidates {
5014        PathMatchCandidateSetIter {
5015            traversal: match self.candidates {
5016                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5017                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5018                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5019            },
5020        }
5021    }
5022}
5023
5024pub struct PathMatchCandidateSetIter<'a> {
5025    traversal: Traversal<'a>,
5026}
5027
5028impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5029    type Item = fuzzy::PathMatchCandidate<'a>;
5030
5031    fn next(&mut self) -> Option<Self::Item> {
5032        self.traversal
5033            .next()
5034            .map(|entry| fuzzy::PathMatchCandidate {
5035                is_dir: entry.kind.is_dir(),
5036                path: &entry.path,
5037                char_bag: entry.char_bag,
5038            })
5039    }
5040}
5041
5042impl EventEmitter<Event> for Project {}
5043
5044impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5045    fn from(val: &'a ProjectPath) -> Self {
5046        SettingsLocation {
5047            worktree_id: val.worktree_id,
5048            path: val.path.as_ref(),
5049        }
5050    }
5051}
5052
5053impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5054    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5055        Self {
5056            worktree_id,
5057            path: path.as_ref().into(),
5058        }
5059    }
5060}
5061
5062pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5063    let mut path_components = path.components();
5064    let mut base_components = base.components();
5065    let mut components: Vec<Component> = Vec::new();
5066    loop {
5067        match (path_components.next(), base_components.next()) {
5068            (None, None) => break,
5069            (Some(a), None) => {
5070                components.push(a);
5071                components.extend(path_components.by_ref());
5072                break;
5073            }
5074            (None, _) => components.push(Component::ParentDir),
5075            (Some(a), Some(b)) if components.is_empty() && a == b => (),
5076            (Some(a), Some(Component::CurDir)) => components.push(a),
5077            (Some(a), Some(_)) => {
5078                components.push(Component::ParentDir);
5079                for _ in base_components {
5080                    components.push(Component::ParentDir);
5081                }
5082                components.push(a);
5083                components.extend(path_components.by_ref());
5084                break;
5085            }
5086        }
5087    }
5088    components.iter().map(|c| c.as_os_str()).collect()
5089}
5090
5091fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5092    let mut result = base.to_path_buf();
5093    for component in path.components() {
5094        match component {
5095            Component::ParentDir => {
5096                result.pop();
5097            }
5098            Component::CurDir => (),
5099            _ => result.push(component),
5100        }
5101    }
5102    result
5103}
5104
5105/// ResolvedPath is a path that has been resolved to either a ProjectPath
5106/// or an AbsPath and that *exists*.
5107#[derive(Debug, Clone)]
5108pub enum ResolvedPath {
5109    ProjectPath {
5110        project_path: ProjectPath,
5111        is_dir: bool,
5112    },
5113    AbsPath {
5114        path: PathBuf,
5115        is_dir: bool,
5116    },
5117}
5118
5119impl ResolvedPath {
5120    pub fn abs_path(&self) -> Option<&Path> {
5121        match self {
5122            Self::AbsPath { path, .. } => Some(path.as_path()),
5123            _ => None,
5124        }
5125    }
5126
5127    pub fn project_path(&self) -> Option<&ProjectPath> {
5128        match self {
5129            Self::ProjectPath { project_path, .. } => Some(&project_path),
5130            _ => None,
5131        }
5132    }
5133
5134    pub fn is_file(&self) -> bool {
5135        !self.is_dir()
5136    }
5137
5138    pub fn is_dir(&self) -> bool {
5139        match self {
5140            Self::ProjectPath { is_dir, .. } => *is_dir,
5141            Self::AbsPath { is_dir, .. } => *is_dir,
5142        }
5143    }
5144}
5145
5146impl ProjectItem for Buffer {
5147    fn try_open(
5148        project: &Entity<Project>,
5149        path: &ProjectPath,
5150        cx: &mut App,
5151    ) -> Option<Task<Result<Entity<Self>>>> {
5152        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5153    }
5154
5155    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5156        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5157    }
5158
5159    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5160        self.file().map(|file| ProjectPath {
5161            worktree_id: file.worktree_id(cx),
5162            path: file.path().clone(),
5163        })
5164    }
5165
5166    fn is_dirty(&self) -> bool {
5167        self.is_dirty()
5168    }
5169}
5170
5171impl Completion {
5172    /// A key that can be used to sort completions when displaying
5173    /// them to the user.
5174    pub fn sort_key(&self) -> (usize, &str) {
5175        const DEFAULT_KIND_KEY: usize = 3;
5176        let kind_key = self
5177            .source
5178            // `lsp::CompletionListItemDefaults` has no `kind` field
5179            .lsp_completion(false)
5180            .and_then(|lsp_completion| lsp_completion.kind)
5181            .and_then(|lsp_completion_kind| match lsp_completion_kind {
5182                lsp::CompletionItemKind::KEYWORD => Some(0),
5183                lsp::CompletionItemKind::VARIABLE => Some(1),
5184                lsp::CompletionItemKind::CONSTANT => Some(2),
5185                _ => None,
5186            })
5187            .unwrap_or(DEFAULT_KIND_KEY);
5188        (kind_key, &self.label.text[self.label.filter_range.clone()])
5189    }
5190
5191    /// Whether this completion is a snippet.
5192    pub fn is_snippet(&self) -> bool {
5193        self.source
5194            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5195            .lsp_completion(true)
5196            .map_or(false, |lsp_completion| {
5197                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5198            })
5199    }
5200
5201    /// Returns the corresponding color for this completion.
5202    ///
5203    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5204    pub fn color(&self) -> Option<Hsla> {
5205        // `lsp::CompletionListItemDefaults` has no `kind` field
5206        let lsp_completion = self.source.lsp_completion(false)?;
5207        if lsp_completion.kind? == CompletionItemKind::COLOR {
5208            return color_extractor::extract_color(&lsp_completion);
5209        }
5210        None
5211    }
5212}
5213
5214pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5215    entries.sort_by(|entry_a, entry_b| {
5216        let entry_a = entry_a.as_ref();
5217        let entry_b = entry_b.as_ref();
5218        compare_paths(
5219            (&entry_a.path, entry_a.is_file()),
5220            (&entry_b.path, entry_b.is_file()),
5221        )
5222    });
5223}
5224
5225fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5226    match level {
5227        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5228        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5229        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5230    }
5231}