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,
  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                    environment.clone(),
 898                    toolchain_store.read(cx).as_language_toolchain_store(),
 899                    worktree_store.clone(),
 900                    breakpoint_store.clone(),
 901                    cx,
 902                )
 903            });
 904            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
 905
 906            let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
 907            cx.subscribe(&image_store, Self::on_image_store_event)
 908                .detach();
 909
 910            let prettier_store = cx.new(|cx| {
 911                PrettierStore::new(
 912                    node.clone(),
 913                    fs.clone(),
 914                    languages.clone(),
 915                    worktree_store.clone(),
 916                    cx,
 917                )
 918            });
 919
 920            let task_store = cx.new(|cx| {
 921                TaskStore::local(
 922                    buffer_store.downgrade(),
 923                    worktree_store.clone(),
 924                    toolchain_store.read(cx).as_language_toolchain_store(),
 925                    environment.clone(),
 926                    cx,
 927                )
 928            });
 929
 930            let settings_observer = cx.new(|cx| {
 931                SettingsObserver::new_local(
 932                    fs.clone(),
 933                    worktree_store.clone(),
 934                    task_store.clone(),
 935                    cx,
 936                )
 937            });
 938            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
 939                .detach();
 940
 941            let lsp_store = cx.new(|cx| {
 942                LspStore::new_local(
 943                    buffer_store.clone(),
 944                    worktree_store.clone(),
 945                    prettier_store.clone(),
 946                    toolchain_store.clone(),
 947                    environment.clone(),
 948                    languages.clone(),
 949                    client.http_client(),
 950                    fs.clone(),
 951                    cx,
 952                )
 953            });
 954
 955            let git_store = cx.new(|cx| {
 956                GitStore::local(
 957                    &worktree_store,
 958                    buffer_store.clone(),
 959                    environment.clone(),
 960                    fs.clone(),
 961                    cx,
 962                )
 963            });
 964
 965            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
 966
 967            Self {
 968                buffer_ordered_messages_tx: tx,
 969                collaborators: Default::default(),
 970                worktree_store,
 971                buffer_store,
 972                image_store,
 973                lsp_store,
 974                context_server_store,
 975                join_project_response_message_id: 0,
 976                client_state: ProjectClientState::Local,
 977                git_store,
 978                client_subscriptions: Vec::new(),
 979                _subscriptions: vec![cx.on_release(Self::release)],
 980                active_entry: None,
 981                snippets,
 982                languages,
 983                client,
 984                task_store,
 985                user_store,
 986                settings_observer,
 987                fs,
 988                ssh_client: None,
 989                breakpoint_store,
 990                dap_store,
 991
 992                buffers_needing_diff: Default::default(),
 993                git_diff_debouncer: DebouncedDelay::new(),
 994                terminals: Terminals {
 995                    local_handles: Vec::new(),
 996                },
 997                node: Some(node),
 998                search_history: Self::new_search_history(),
 999                environment,
1000                remotely_created_models: Default::default(),
1001
1002                search_included_history: Self::new_search_history(),
1003                search_excluded_history: Self::new_search_history(),
1004
1005                toolchain_store: Some(toolchain_store),
1006
1007                agent_location: None,
1008            }
1009        })
1010    }
1011
1012    pub fn ssh(
1013        ssh: Entity<SshRemoteClient>,
1014        client: Arc<Client>,
1015        node: NodeRuntime,
1016        user_store: Entity<UserStore>,
1017        languages: Arc<LanguageRegistry>,
1018        fs: Arc<dyn Fs>,
1019        cx: &mut App,
1020    ) -> Entity<Self> {
1021        cx.new(|cx: &mut Context<Self>| {
1022            let (tx, rx) = mpsc::unbounded();
1023            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1024                .detach();
1025            let global_snippets_dir = paths::config_dir().join("snippets");
1026            let snippets =
1027                SnippetProvider::new(fs.clone(), BTreeSet::from_iter([global_snippets_dir]), cx);
1028
1029            let ssh_proto = ssh.read(cx).proto_client();
1030            let worktree_store =
1031                cx.new(|_| WorktreeStore::remote(false, ssh_proto.clone(), SSH_PROJECT_ID));
1032            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1033                .detach();
1034
1035            let context_server_store =
1036                cx.new(|cx| ContextServerStore::new(worktree_store.clone(), cx));
1037
1038            let buffer_store = cx.new(|cx| {
1039                BufferStore::remote(
1040                    worktree_store.clone(),
1041                    ssh.read(cx).proto_client(),
1042                    SSH_PROJECT_ID,
1043                    cx,
1044                )
1045            });
1046            let image_store = cx.new(|cx| {
1047                ImageStore::remote(
1048                    worktree_store.clone(),
1049                    ssh.read(cx).proto_client(),
1050                    SSH_PROJECT_ID,
1051                    cx,
1052                )
1053            });
1054            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1055                .detach();
1056            let toolchain_store = cx
1057                .new(|cx| ToolchainStore::remote(SSH_PROJECT_ID, ssh.read(cx).proto_client(), cx));
1058            let task_store = cx.new(|cx| {
1059                TaskStore::remote(
1060                    buffer_store.downgrade(),
1061                    worktree_store.clone(),
1062                    toolchain_store.read(cx).as_language_toolchain_store(),
1063                    ssh.read(cx).proto_client(),
1064                    SSH_PROJECT_ID,
1065                    cx,
1066                )
1067            });
1068
1069            let settings_observer = cx.new(|cx| {
1070                SettingsObserver::new_remote(
1071                    fs.clone(),
1072                    worktree_store.clone(),
1073                    task_store.clone(),
1074                    cx,
1075                )
1076            });
1077            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1078                .detach();
1079
1080            let environment = cx.new(|_| ProjectEnvironment::new(None));
1081
1082            let lsp_store = cx.new(|cx| {
1083                LspStore::new_remote(
1084                    buffer_store.clone(),
1085                    worktree_store.clone(),
1086                    Some(toolchain_store.clone()),
1087                    languages.clone(),
1088                    ssh_proto.clone(),
1089                    SSH_PROJECT_ID,
1090                    fs.clone(),
1091                    cx,
1092                )
1093            });
1094            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1095
1096            let breakpoint_store =
1097                cx.new(|_| BreakpointStore::remote(SSH_PROJECT_ID, ssh_proto.clone()));
1098
1099            let dap_store = cx.new(|cx| {
1100                DapStore::new_ssh(
1101                    SSH_PROJECT_ID,
1102                    ssh.clone(),
1103                    breakpoint_store.clone(),
1104                    worktree_store.clone(),
1105                    cx,
1106                )
1107            });
1108
1109            let git_store = cx.new(|cx| {
1110                GitStore::ssh(&worktree_store, buffer_store.clone(), ssh_proto.clone(), cx)
1111            });
1112
1113            cx.subscribe(&ssh, Self::on_ssh_event).detach();
1114
1115            let this = Self {
1116                buffer_ordered_messages_tx: tx,
1117                collaborators: Default::default(),
1118                worktree_store,
1119                buffer_store,
1120                image_store,
1121                lsp_store,
1122                context_server_store,
1123                breakpoint_store,
1124                dap_store,
1125                join_project_response_message_id: 0,
1126                client_state: ProjectClientState::Local,
1127                git_store,
1128                client_subscriptions: Vec::new(),
1129                _subscriptions: vec![
1130                    cx.on_release(Self::release),
1131                    cx.on_app_quit(|this, cx| {
1132                        let shutdown = this.ssh_client.take().and_then(|client| {
1133                            client
1134                                .read(cx)
1135                                .shutdown_processes(Some(proto::ShutdownRemoteServer {}))
1136                        });
1137
1138                        cx.background_executor().spawn(async move {
1139                            if let Some(shutdown) = shutdown {
1140                                shutdown.await;
1141                            }
1142                        })
1143                    }),
1144                ],
1145                active_entry: None,
1146                snippets,
1147                languages,
1148                client,
1149                task_store,
1150                user_store,
1151                settings_observer,
1152                fs,
1153                ssh_client: Some(ssh.clone()),
1154                buffers_needing_diff: Default::default(),
1155                git_diff_debouncer: DebouncedDelay::new(),
1156                terminals: Terminals {
1157                    local_handles: Vec::new(),
1158                },
1159                node: Some(node),
1160                search_history: Self::new_search_history(),
1161                environment,
1162                remotely_created_models: Default::default(),
1163
1164                search_included_history: Self::new_search_history(),
1165                search_excluded_history: Self::new_search_history(),
1166
1167                toolchain_store: Some(toolchain_store),
1168                agent_location: None,
1169            };
1170
1171            // ssh -> local machine handlers
1172            let ssh = ssh.read(cx);
1173            ssh.subscribe_to_entity(SSH_PROJECT_ID, &cx.entity());
1174            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.buffer_store);
1175            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.worktree_store);
1176            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.lsp_store);
1177            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.dap_store);
1178            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.settings_observer);
1179            ssh.subscribe_to_entity(SSH_PROJECT_ID, &this.git_store);
1180
1181            ssh_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1182            ssh_proto.add_entity_message_handler(Self::handle_update_worktree);
1183            ssh_proto.add_entity_message_handler(Self::handle_update_project);
1184            ssh_proto.add_entity_message_handler(Self::handle_toast);
1185            ssh_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1186            ssh_proto.add_entity_message_handler(Self::handle_hide_toast);
1187            ssh_proto.add_entity_request_handler(Self::handle_update_buffer_from_ssh);
1188            BufferStore::init(&ssh_proto);
1189            LspStore::init(&ssh_proto);
1190            SettingsObserver::init(&ssh_proto);
1191            TaskStore::init(Some(&ssh_proto));
1192            ToolchainStore::init(&ssh_proto);
1193            DapStore::init(&ssh_proto, cx);
1194            GitStore::init(&ssh_proto);
1195
1196            this
1197        })
1198    }
1199
1200    pub async fn remote(
1201        remote_id: u64,
1202        client: Arc<Client>,
1203        user_store: Entity<UserStore>,
1204        languages: Arc<LanguageRegistry>,
1205        fs: Arc<dyn Fs>,
1206        cx: AsyncApp,
1207    ) -> Result<Entity<Self>> {
1208        let project =
1209            Self::in_room(remote_id, client, user_store, languages, fs, cx.clone()).await?;
1210        cx.update(|cx| {
1211            connection_manager::Manager::global(cx).update(cx, |manager, cx| {
1212                manager.maintain_project_connection(&project, cx)
1213            })
1214        })?;
1215        Ok(project)
1216    }
1217
1218    pub async fn in_room(
1219        remote_id: u64,
1220        client: Arc<Client>,
1221        user_store: Entity<UserStore>,
1222        languages: Arc<LanguageRegistry>,
1223        fs: Arc<dyn Fs>,
1224        cx: AsyncApp,
1225    ) -> Result<Entity<Self>> {
1226        client.authenticate_and_connect(true, &cx).await?;
1227
1228        let subscriptions = [
1229            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1230            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1231            EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1232            EntitySubscription::WorktreeStore(
1233                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1234            ),
1235            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1236            EntitySubscription::SettingsObserver(
1237                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1238            ),
1239            EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1240        ];
1241        let response = client
1242            .request_envelope(proto::JoinProject {
1243                project_id: remote_id,
1244            })
1245            .await?;
1246        Self::from_join_project_response(
1247            response,
1248            subscriptions,
1249            client,
1250            false,
1251            user_store,
1252            languages,
1253            fs,
1254            cx,
1255        )
1256        .await
1257    }
1258
1259    async fn from_join_project_response(
1260        response: TypedEnvelope<proto::JoinProjectResponse>,
1261        subscriptions: [EntitySubscription; 7],
1262        client: Arc<Client>,
1263        run_tasks: bool,
1264        user_store: Entity<UserStore>,
1265        languages: Arc<LanguageRegistry>,
1266        fs: Arc<dyn Fs>,
1267        mut cx: AsyncApp,
1268    ) -> Result<Entity<Self>> {
1269        let remote_id = response.payload.project_id;
1270        let role = response.payload.role();
1271
1272        let worktree_store = cx.new(|_| {
1273            WorktreeStore::remote(true, client.clone().into(), response.payload.project_id)
1274        })?;
1275        let buffer_store = cx.new(|cx| {
1276            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1277        })?;
1278        let image_store = cx.new(|cx| {
1279            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1280        })?;
1281        let context_server_store =
1282            cx.new(|cx| ContextServerStore::new(worktree_store.clone(), cx))?;
1283
1284        let environment = cx.new(|_| ProjectEnvironment::new(None))?;
1285
1286        let breakpoint_store =
1287            cx.new(|_| BreakpointStore::remote(remote_id, client.clone().into()))?;
1288        let dap_store = cx.new(|cx| {
1289            DapStore::new_collab(
1290                remote_id,
1291                client.clone().into(),
1292                breakpoint_store.clone(),
1293                worktree_store.clone(),
1294                cx,
1295            )
1296        })?;
1297
1298        let lsp_store = cx.new(|cx| {
1299            let mut lsp_store = LspStore::new_remote(
1300                buffer_store.clone(),
1301                worktree_store.clone(),
1302                None,
1303                languages.clone(),
1304                client.clone().into(),
1305                remote_id,
1306                fs.clone(),
1307                cx,
1308            );
1309            lsp_store.set_language_server_statuses_from_proto(response.payload.language_servers);
1310            lsp_store
1311        })?;
1312
1313        let task_store = cx.new(|cx| {
1314            if run_tasks {
1315                TaskStore::remote(
1316                    buffer_store.downgrade(),
1317                    worktree_store.clone(),
1318                    Arc::new(EmptyToolchainStore),
1319                    client.clone().into(),
1320                    remote_id,
1321                    cx,
1322                )
1323            } else {
1324                TaskStore::Noop
1325            }
1326        })?;
1327
1328        let settings_observer = cx.new(|cx| {
1329            SettingsObserver::new_remote(fs.clone(), worktree_store.clone(), task_store.clone(), cx)
1330        })?;
1331
1332        let git_store = cx.new(|cx| {
1333            GitStore::remote(
1334                // In this remote case we pass None for the environment
1335                &worktree_store,
1336                buffer_store.clone(),
1337                client.clone().into(),
1338                ProjectId(remote_id),
1339                cx,
1340            )
1341        })?;
1342
1343        let this = cx.new(|cx| {
1344            let replica_id = response.payload.replica_id as ReplicaId;
1345
1346            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1347
1348            let mut worktrees = Vec::new();
1349            for worktree in response.payload.worktrees {
1350                let worktree =
1351                    Worktree::remote(remote_id, replica_id, worktree, client.clone().into(), cx);
1352                worktrees.push(worktree);
1353            }
1354
1355            let (tx, rx) = mpsc::unbounded();
1356            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1357                .detach();
1358
1359            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1360                .detach();
1361
1362            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1363                .detach();
1364            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1365            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1366                .detach();
1367
1368            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1369
1370            let mut this = Self {
1371                buffer_ordered_messages_tx: tx,
1372                buffer_store: buffer_store.clone(),
1373                image_store,
1374                worktree_store: worktree_store.clone(),
1375                lsp_store: lsp_store.clone(),
1376                context_server_store,
1377                active_entry: None,
1378                collaborators: Default::default(),
1379                join_project_response_message_id: response.message_id,
1380                languages,
1381                user_store: user_store.clone(),
1382                task_store,
1383                snippets,
1384                fs,
1385                ssh_client: None,
1386                settings_observer: settings_observer.clone(),
1387                client_subscriptions: Default::default(),
1388                _subscriptions: vec![cx.on_release(Self::release)],
1389                client: client.clone(),
1390                client_state: ProjectClientState::Remote {
1391                    sharing_has_stopped: false,
1392                    capability: Capability::ReadWrite,
1393                    remote_id,
1394                    replica_id,
1395                },
1396                breakpoint_store,
1397                dap_store: dap_store.clone(),
1398                git_store: git_store.clone(),
1399                buffers_needing_diff: Default::default(),
1400                git_diff_debouncer: DebouncedDelay::new(),
1401                terminals: Terminals {
1402                    local_handles: Vec::new(),
1403                },
1404                node: None,
1405                search_history: Self::new_search_history(),
1406                search_included_history: Self::new_search_history(),
1407                search_excluded_history: Self::new_search_history(),
1408                environment,
1409                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1410                toolchain_store: None,
1411                agent_location: None,
1412            };
1413            this.set_role(role, cx);
1414            for worktree in worktrees {
1415                this.add_worktree(&worktree, cx);
1416            }
1417            this
1418        })?;
1419
1420        let subscriptions = subscriptions
1421            .into_iter()
1422            .map(|s| match s {
1423                EntitySubscription::BufferStore(subscription) => {
1424                    subscription.set_entity(&buffer_store, &mut cx)
1425                }
1426                EntitySubscription::WorktreeStore(subscription) => {
1427                    subscription.set_entity(&worktree_store, &mut cx)
1428                }
1429                EntitySubscription::GitStore(subscription) => {
1430                    subscription.set_entity(&git_store, &mut cx)
1431                }
1432                EntitySubscription::SettingsObserver(subscription) => {
1433                    subscription.set_entity(&settings_observer, &mut cx)
1434                }
1435                EntitySubscription::Project(subscription) => {
1436                    subscription.set_entity(&this, &mut cx)
1437                }
1438                EntitySubscription::LspStore(subscription) => {
1439                    subscription.set_entity(&lsp_store, &mut cx)
1440                }
1441                EntitySubscription::DapStore(subscription) => {
1442                    subscription.set_entity(&dap_store, &mut cx)
1443                }
1444            })
1445            .collect::<Vec<_>>();
1446
1447        let user_ids = response
1448            .payload
1449            .collaborators
1450            .iter()
1451            .map(|peer| peer.user_id)
1452            .collect();
1453        user_store
1454            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))?
1455            .await?;
1456
1457        this.update(&mut cx, |this, cx| {
1458            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1459            this.client_subscriptions.extend(subscriptions);
1460            anyhow::Ok(())
1461        })??;
1462
1463        Ok(this)
1464    }
1465
1466    fn new_search_history() -> SearchHistory {
1467        SearchHistory::new(
1468            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1469            search_history::QueryInsertionBehavior::AlwaysInsert,
1470        )
1471    }
1472
1473    fn release(&mut self, cx: &mut App) {
1474        if let Some(client) = self.ssh_client.take() {
1475            let shutdown = client
1476                .read(cx)
1477                .shutdown_processes(Some(proto::ShutdownRemoteServer {}));
1478
1479            cx.background_spawn(async move {
1480                if let Some(shutdown) = shutdown {
1481                    shutdown.await;
1482                }
1483            })
1484            .detach()
1485        }
1486
1487        match &self.client_state {
1488            ProjectClientState::Local => {}
1489            ProjectClientState::Shared { .. } => {
1490                let _ = self.unshare_internal(cx);
1491            }
1492            ProjectClientState::Remote { remote_id, .. } => {
1493                let _ = self.client.send(proto::LeaveProject {
1494                    project_id: *remote_id,
1495                });
1496                self.disconnected_from_host_internal(cx);
1497            }
1498        }
1499    }
1500
1501    #[cfg(any(test, feature = "test-support"))]
1502    pub async fn example(
1503        root_paths: impl IntoIterator<Item = &Path>,
1504        cx: &mut AsyncApp,
1505    ) -> Entity<Project> {
1506        use clock::FakeSystemClock;
1507
1508        let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1509        let languages = LanguageRegistry::test(cx.background_executor().clone());
1510        let clock = Arc::new(FakeSystemClock::new());
1511        let http_client = http_client::FakeHttpClient::with_404_response();
1512        let client = cx
1513            .update(|cx| client::Client::new(clock, http_client.clone(), cx))
1514            .unwrap();
1515        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx)).unwrap();
1516        let project = cx
1517            .update(|cx| {
1518                Project::local(
1519                    client,
1520                    node_runtime::NodeRuntime::unavailable(),
1521                    user_store,
1522                    Arc::new(languages),
1523                    fs,
1524                    None,
1525                    cx,
1526                )
1527            })
1528            .unwrap();
1529        for path in root_paths {
1530            let (tree, _) = project
1531                .update(cx, |project, cx| {
1532                    project.find_or_create_worktree(path, true, cx)
1533                })
1534                .unwrap()
1535                .await
1536                .unwrap();
1537            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1538                .unwrap()
1539                .await;
1540        }
1541        project
1542    }
1543
1544    #[cfg(any(test, feature = "test-support"))]
1545    pub async fn test(
1546        fs: Arc<dyn Fs>,
1547        root_paths: impl IntoIterator<Item = &Path>,
1548        cx: &mut gpui::TestAppContext,
1549    ) -> Entity<Project> {
1550        use clock::FakeSystemClock;
1551
1552        let languages = LanguageRegistry::test(cx.executor());
1553        let clock = Arc::new(FakeSystemClock::new());
1554        let http_client = http_client::FakeHttpClient::with_404_response();
1555        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1556        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1557        let project = cx.update(|cx| {
1558            Project::local(
1559                client,
1560                node_runtime::NodeRuntime::unavailable(),
1561                user_store,
1562                Arc::new(languages),
1563                fs,
1564                None,
1565                cx,
1566            )
1567        });
1568        for path in root_paths {
1569            let (tree, _) = project
1570                .update(cx, |project, cx| {
1571                    project.find_or_create_worktree(path, true, cx)
1572                })
1573                .await
1574                .unwrap();
1575
1576            tree.update(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1577                .await;
1578        }
1579        project
1580    }
1581
1582    pub fn dap_store(&self) -> Entity<DapStore> {
1583        self.dap_store.clone()
1584    }
1585
1586    pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1587        self.breakpoint_store.clone()
1588    }
1589
1590    pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
1591        let active_position = self.breakpoint_store.read(cx).active_position()?;
1592        let session = self
1593            .dap_store
1594            .read(cx)
1595            .session_by_id(active_position.session_id)?;
1596        Some((session, active_position.clone()))
1597    }
1598
1599    pub fn lsp_store(&self) -> Entity<LspStore> {
1600        self.lsp_store.clone()
1601    }
1602
1603    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1604        self.worktree_store.clone()
1605    }
1606
1607    pub fn context_server_store(&self) -> Entity<ContextServerStore> {
1608        self.context_server_store.clone()
1609    }
1610
1611    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1612        self.buffer_store.read(cx).get(remote_id)
1613    }
1614
1615    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1616        &self.languages
1617    }
1618
1619    pub fn client(&self) -> Arc<Client> {
1620        self.client.clone()
1621    }
1622
1623    pub fn ssh_client(&self) -> Option<Entity<SshRemoteClient>> {
1624        self.ssh_client.clone()
1625    }
1626
1627    pub fn user_store(&self) -> Entity<UserStore> {
1628        self.user_store.clone()
1629    }
1630
1631    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
1632        self.node.as_ref()
1633    }
1634
1635    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
1636        self.buffer_store.read(cx).buffers().collect()
1637    }
1638
1639    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
1640        &self.environment
1641    }
1642
1643    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
1644        self.environment.read(cx).get_cli_environment()
1645    }
1646
1647    pub fn buffer_environment<'a>(
1648        &'a self,
1649        buffer: &Entity<Buffer>,
1650        worktree_store: &Entity<WorktreeStore>,
1651        cx: &'a mut App,
1652    ) -> Shared<Task<Option<HashMap<String, String>>>> {
1653        self.environment.update(cx, |environment, cx| {
1654            environment.get_buffer_environment(&buffer, &worktree_store, cx)
1655        })
1656    }
1657
1658    pub fn directory_environment(
1659        &self,
1660        abs_path: Arc<Path>,
1661        cx: &mut App,
1662    ) -> Shared<Task<Option<HashMap<String, String>>>> {
1663        self.environment.update(cx, |environment, cx| {
1664            environment.get_directory_environment(abs_path, cx)
1665        })
1666    }
1667
1668    pub fn shell_environment_errors<'a>(
1669        &'a self,
1670        cx: &'a App,
1671    ) -> impl Iterator<Item = (&'a Arc<Path>, &'a EnvironmentErrorMessage)> {
1672        self.environment.read(cx).environment_errors()
1673    }
1674
1675    pub fn remove_environment_error(&mut self, abs_path: &Path, cx: &mut Context<Self>) {
1676        self.environment.update(cx, |environment, cx| {
1677            environment.remove_environment_error(abs_path, cx);
1678        });
1679    }
1680
1681    #[cfg(any(test, feature = "test-support"))]
1682    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
1683        self.buffer_store
1684            .read(cx)
1685            .get_by_path(&path.into(), cx)
1686            .is_some()
1687    }
1688
1689    pub fn fs(&self) -> &Arc<dyn Fs> {
1690        &self.fs
1691    }
1692
1693    pub fn remote_id(&self) -> Option<u64> {
1694        match self.client_state {
1695            ProjectClientState::Local => None,
1696            ProjectClientState::Shared { remote_id, .. }
1697            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
1698        }
1699    }
1700
1701    pub fn supports_terminal(&self, _cx: &App) -> bool {
1702        if self.is_local() {
1703            return true;
1704        }
1705        if self.is_via_ssh() {
1706            return true;
1707        }
1708
1709        return false;
1710    }
1711
1712    pub fn ssh_connection_string(&self, cx: &App) -> Option<SharedString> {
1713        if let Some(ssh_state) = &self.ssh_client {
1714            return Some(ssh_state.read(cx).connection_string().into());
1715        }
1716
1717        return None;
1718    }
1719
1720    pub fn ssh_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
1721        self.ssh_client
1722            .as_ref()
1723            .map(|ssh| ssh.read(cx).connection_state())
1724    }
1725
1726    pub fn ssh_connection_options(&self, cx: &App) -> Option<SshConnectionOptions> {
1727        self.ssh_client
1728            .as_ref()
1729            .map(|ssh| ssh.read(cx).connection_options())
1730    }
1731
1732    pub fn replica_id(&self) -> ReplicaId {
1733        match self.client_state {
1734            ProjectClientState::Remote { replica_id, .. } => replica_id,
1735            _ => {
1736                if self.ssh_client.is_some() {
1737                    1
1738                } else {
1739                    0
1740                }
1741            }
1742        }
1743    }
1744
1745    pub fn task_store(&self) -> &Entity<TaskStore> {
1746        &self.task_store
1747    }
1748
1749    pub fn snippets(&self) -> &Entity<SnippetProvider> {
1750        &self.snippets
1751    }
1752
1753    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
1754        match kind {
1755            SearchInputKind::Query => &self.search_history,
1756            SearchInputKind::Include => &self.search_included_history,
1757            SearchInputKind::Exclude => &self.search_excluded_history,
1758        }
1759    }
1760
1761    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
1762        match kind {
1763            SearchInputKind::Query => &mut self.search_history,
1764            SearchInputKind::Include => &mut self.search_included_history,
1765            SearchInputKind::Exclude => &mut self.search_excluded_history,
1766        }
1767    }
1768
1769    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1770        &self.collaborators
1771    }
1772
1773    pub fn host(&self) -> Option<&Collaborator> {
1774        self.collaborators.values().find(|c| c.is_host)
1775    }
1776
1777    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
1778        self.worktree_store.update(cx, |store, _| {
1779            store.set_worktrees_reordered(worktrees_reordered);
1780        });
1781    }
1782
1783    /// Collect all worktrees, including ones that don't appear in the project panel
1784    pub fn worktrees<'a>(
1785        &self,
1786        cx: &'a App,
1787    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1788        self.worktree_store.read(cx).worktrees()
1789    }
1790
1791    /// Collect all user-visible worktrees, the ones that appear in the project panel.
1792    pub fn visible_worktrees<'a>(
1793        &'a self,
1794        cx: &'a App,
1795    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
1796        self.worktree_store.read(cx).visible_worktrees(cx)
1797    }
1798
1799    pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
1800        self.visible_worktrees(cx)
1801            .find(|tree| tree.read(cx).root_name() == root_name)
1802    }
1803
1804    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
1805        self.visible_worktrees(cx)
1806            .map(|tree| tree.read(cx).root_name())
1807    }
1808
1809    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
1810        self.worktree_store.read(cx).worktree_for_id(id, cx)
1811    }
1812
1813    pub fn worktree_for_entry(
1814        &self,
1815        entry_id: ProjectEntryId,
1816        cx: &App,
1817    ) -> Option<Entity<Worktree>> {
1818        self.worktree_store
1819            .read(cx)
1820            .worktree_for_entry(entry_id, cx)
1821    }
1822
1823    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
1824        self.worktree_for_entry(entry_id, cx)
1825            .map(|worktree| worktree.read(cx).id())
1826    }
1827
1828    /// Checks if the entry is the root of a worktree.
1829    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
1830        self.worktree_for_entry(entry_id, cx)
1831            .map(|worktree| {
1832                worktree
1833                    .read(cx)
1834                    .root_entry()
1835                    .is_some_and(|e| e.id == entry_id)
1836            })
1837            .unwrap_or(false)
1838    }
1839
1840    pub fn project_path_git_status(
1841        &self,
1842        project_path: &ProjectPath,
1843        cx: &App,
1844    ) -> Option<FileStatus> {
1845        self.git_store
1846            .read(cx)
1847            .project_path_git_status(project_path, cx)
1848    }
1849
1850    pub fn visibility_for_paths(
1851        &self,
1852        paths: &[PathBuf],
1853        metadatas: &[Metadata],
1854        exclude_sub_dirs: bool,
1855        cx: &App,
1856    ) -> Option<bool> {
1857        paths
1858            .iter()
1859            .zip(metadatas)
1860            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
1861            .max()
1862            .flatten()
1863    }
1864
1865    pub fn visibility_for_path(
1866        &self,
1867        path: &Path,
1868        metadata: &Metadata,
1869        exclude_sub_dirs: bool,
1870        cx: &App,
1871    ) -> Option<bool> {
1872        let sanitized_path = SanitizedPath::from(path);
1873        let path = sanitized_path.as_path();
1874        self.worktrees(cx)
1875            .filter_map(|worktree| {
1876                let worktree = worktree.read(cx);
1877                let abs_path = worktree.as_local()?.abs_path();
1878                let contains = path == abs_path
1879                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
1880                contains.then(|| worktree.is_visible())
1881            })
1882            .max()
1883    }
1884
1885    pub fn create_entry(
1886        &mut self,
1887        project_path: impl Into<ProjectPath>,
1888        is_directory: bool,
1889        cx: &mut Context<Self>,
1890    ) -> Task<Result<CreatedEntry>> {
1891        let project_path = project_path.into();
1892        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
1893            return Task::ready(Err(anyhow!(format!(
1894                "No worktree for path {project_path:?}"
1895            ))));
1896        };
1897        worktree.update(cx, |worktree, cx| {
1898            worktree.create_entry(project_path.path, is_directory, None, cx)
1899        })
1900    }
1901
1902    pub fn copy_entry(
1903        &mut self,
1904        entry_id: ProjectEntryId,
1905        relative_worktree_source_path: Option<PathBuf>,
1906        new_path: impl Into<Arc<Path>>,
1907        cx: &mut Context<Self>,
1908    ) -> Task<Result<Option<Entry>>> {
1909        let Some(worktree) = self.worktree_for_entry(entry_id, cx) else {
1910            return Task::ready(Ok(None));
1911        };
1912        worktree.update(cx, |worktree, cx| {
1913            worktree.copy_entry(entry_id, relative_worktree_source_path, new_path, cx)
1914        })
1915    }
1916
1917    /// Renames the project entry with given `entry_id`.
1918    ///
1919    /// `new_path` is a relative path to worktree root.
1920    /// If root entry is renamed then its new root name is used instead.
1921    pub fn rename_entry(
1922        &mut self,
1923        entry_id: ProjectEntryId,
1924        new_path: impl Into<Arc<Path>>,
1925        cx: &mut Context<Self>,
1926    ) -> Task<Result<CreatedEntry>> {
1927        let worktree_store = self.worktree_store.read(cx);
1928        let new_path = new_path.into();
1929        let Some((worktree, old_path, is_dir)) = worktree_store
1930            .worktree_and_entry_for_id(entry_id, cx)
1931            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
1932        else {
1933            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
1934        };
1935
1936        let worktree_id = worktree.read(cx).id();
1937        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
1938
1939        let lsp_store = self.lsp_store().downgrade();
1940        cx.spawn(async move |_, cx| {
1941            let (old_abs_path, new_abs_path) = {
1942                let root_path = worktree.update(cx, |this, _| this.abs_path())?;
1943                let new_abs_path = if is_root_entry {
1944                    root_path.parent().unwrap().join(&new_path)
1945                } else {
1946                    root_path.join(&new_path)
1947                };
1948                (root_path.join(&old_path), new_abs_path)
1949            };
1950            LspStore::will_rename_entry(
1951                lsp_store.clone(),
1952                worktree_id,
1953                &old_abs_path,
1954                &new_abs_path,
1955                is_dir,
1956                cx.clone(),
1957            )
1958            .await;
1959
1960            let entry = worktree
1961                .update(cx, |worktree, cx| {
1962                    worktree.rename_entry(entry_id, new_path.clone(), cx)
1963                })?
1964                .await?;
1965
1966            lsp_store
1967                .update(cx, |this, _| {
1968                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
1969                })
1970                .ok();
1971            Ok(entry)
1972        })
1973    }
1974
1975    pub fn delete_file(
1976        &mut self,
1977        path: ProjectPath,
1978        trash: bool,
1979        cx: &mut Context<Self>,
1980    ) -> Option<Task<Result<()>>> {
1981        let entry = self.entry_for_path(&path, cx)?;
1982        self.delete_entry(entry.id, trash, cx)
1983    }
1984
1985    pub fn delete_entry(
1986        &mut self,
1987        entry_id: ProjectEntryId,
1988        trash: bool,
1989        cx: &mut Context<Self>,
1990    ) -> Option<Task<Result<()>>> {
1991        let worktree = self.worktree_for_entry(entry_id, cx)?;
1992        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
1993        worktree.update(cx, |worktree, cx| {
1994            worktree.delete_entry(entry_id, trash, cx)
1995        })
1996    }
1997
1998    pub fn expand_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        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2006    }
2007
2008    pub fn expand_all_for_entry(
2009        &mut self,
2010        worktree_id: WorktreeId,
2011        entry_id: ProjectEntryId,
2012        cx: &mut Context<Self>,
2013    ) -> Option<Task<Result<()>>> {
2014        let worktree = self.worktree_for_id(worktree_id, cx)?;
2015        let task = worktree.update(cx, |worktree, cx| {
2016            worktree.expand_all_for_entry(entry_id, cx)
2017        });
2018        Some(cx.spawn(async move |this, cx| {
2019            task.ok_or_else(|| anyhow!("no task"))?.await?;
2020            this.update(cx, |_, cx| {
2021                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2022            })?;
2023            Ok(())
2024        }))
2025    }
2026
2027    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2028        if !matches!(self.client_state, ProjectClientState::Local) {
2029            return Err(anyhow!("project was already shared"));
2030        }
2031
2032        self.client_subscriptions.extend([
2033            self.client
2034                .subscribe_to_entity(project_id)?
2035                .set_entity(&cx.entity(), &mut cx.to_async()),
2036            self.client
2037                .subscribe_to_entity(project_id)?
2038                .set_entity(&self.worktree_store, &mut cx.to_async()),
2039            self.client
2040                .subscribe_to_entity(project_id)?
2041                .set_entity(&self.buffer_store, &mut cx.to_async()),
2042            self.client
2043                .subscribe_to_entity(project_id)?
2044                .set_entity(&self.lsp_store, &mut cx.to_async()),
2045            self.client
2046                .subscribe_to_entity(project_id)?
2047                .set_entity(&self.settings_observer, &mut cx.to_async()),
2048            self.client
2049                .subscribe_to_entity(project_id)?
2050                .set_entity(&self.dap_store, &mut cx.to_async()),
2051            self.client
2052                .subscribe_to_entity(project_id)?
2053                .set_entity(&self.breakpoint_store, &mut cx.to_async()),
2054            self.client
2055                .subscribe_to_entity(project_id)?
2056                .set_entity(&self.git_store, &mut cx.to_async()),
2057        ]);
2058
2059        self.buffer_store.update(cx, |buffer_store, cx| {
2060            buffer_store.shared(project_id, self.client.clone().into(), cx)
2061        });
2062        self.worktree_store.update(cx, |worktree_store, cx| {
2063            worktree_store.shared(project_id, self.client.clone().into(), cx);
2064        });
2065        self.lsp_store.update(cx, |lsp_store, cx| {
2066            lsp_store.shared(project_id, self.client.clone().into(), cx)
2067        });
2068        self.breakpoint_store.update(cx, |breakpoint_store, _| {
2069            breakpoint_store.shared(project_id, self.client.clone().into())
2070        });
2071        self.dap_store.update(cx, |dap_store, cx| {
2072            dap_store.shared(project_id, self.client.clone().into(), cx);
2073        });
2074        self.task_store.update(cx, |task_store, cx| {
2075            task_store.shared(project_id, self.client.clone().into(), cx);
2076        });
2077        self.settings_observer.update(cx, |settings_observer, cx| {
2078            settings_observer.shared(project_id, self.client.clone().into(), cx)
2079        });
2080        self.git_store.update(cx, |git_store, cx| {
2081            git_store.shared(project_id, self.client.clone().into(), cx)
2082        });
2083
2084        self.client_state = ProjectClientState::Shared {
2085            remote_id: project_id,
2086        };
2087
2088        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2089        Ok(())
2090    }
2091
2092    pub fn reshared(
2093        &mut self,
2094        message: proto::ResharedProject,
2095        cx: &mut Context<Self>,
2096    ) -> Result<()> {
2097        self.buffer_store
2098            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2099        self.set_collaborators_from_proto(message.collaborators, cx)?;
2100
2101        self.worktree_store.update(cx, |worktree_store, cx| {
2102            worktree_store.send_project_updates(cx);
2103        });
2104        if let Some(remote_id) = self.remote_id() {
2105            self.git_store.update(cx, |git_store, cx| {
2106                git_store.shared(remote_id, self.client.clone().into(), cx)
2107            });
2108        }
2109        cx.emit(Event::Reshared);
2110        Ok(())
2111    }
2112
2113    pub fn rejoined(
2114        &mut self,
2115        message: proto::RejoinedProject,
2116        message_id: u32,
2117        cx: &mut Context<Self>,
2118    ) -> Result<()> {
2119        cx.update_global::<SettingsStore, _>(|store, cx| {
2120            self.worktree_store.update(cx, |worktree_store, cx| {
2121                for worktree in worktree_store.worktrees() {
2122                    store
2123                        .clear_local_settings(worktree.read(cx).id(), cx)
2124                        .log_err();
2125                }
2126            });
2127        });
2128
2129        self.join_project_response_message_id = message_id;
2130        self.set_worktrees_from_proto(message.worktrees, cx)?;
2131        self.set_collaborators_from_proto(message.collaborators, cx)?;
2132        self.lsp_store.update(cx, |lsp_store, _| {
2133            lsp_store.set_language_server_statuses_from_proto(message.language_servers)
2134        });
2135        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2136            .unwrap();
2137        cx.emit(Event::Rejoined);
2138        Ok(())
2139    }
2140
2141    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2142        self.unshare_internal(cx)?;
2143        cx.emit(Event::RemoteIdChanged(None));
2144        Ok(())
2145    }
2146
2147    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2148        if self.is_via_collab() {
2149            return Err(anyhow!("attempted to unshare a remote project"));
2150        }
2151
2152        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2153            self.client_state = ProjectClientState::Local;
2154            self.collaborators.clear();
2155            self.client_subscriptions.clear();
2156            self.worktree_store.update(cx, |store, cx| {
2157                store.unshared(cx);
2158            });
2159            self.buffer_store.update(cx, |buffer_store, cx| {
2160                buffer_store.forget_shared_buffers();
2161                buffer_store.unshared(cx)
2162            });
2163            self.task_store.update(cx, |task_store, cx| {
2164                task_store.unshared(cx);
2165            });
2166            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2167                breakpoint_store.unshared(cx);
2168            });
2169            self.dap_store.update(cx, |dap_store, cx| {
2170                dap_store.unshared(cx);
2171            });
2172            self.settings_observer.update(cx, |settings_observer, cx| {
2173                settings_observer.unshared(cx);
2174            });
2175            self.git_store.update(cx, |git_store, cx| {
2176                git_store.unshared(cx);
2177            });
2178
2179            self.client
2180                .send(proto::UnshareProject {
2181                    project_id: remote_id,
2182                })
2183                .ok();
2184            Ok(())
2185        } else {
2186            Err(anyhow!("attempted to unshare an unshared project"))
2187        }
2188    }
2189
2190    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2191        if self.is_disconnected(cx) {
2192            return;
2193        }
2194        self.disconnected_from_host_internal(cx);
2195        cx.emit(Event::DisconnectedFromHost);
2196    }
2197
2198    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2199        let new_capability =
2200            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2201                Capability::ReadWrite
2202            } else {
2203                Capability::ReadOnly
2204            };
2205        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2206            if *capability == new_capability {
2207                return;
2208            }
2209
2210            *capability = new_capability;
2211            for buffer in self.opened_buffers(cx) {
2212                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2213            }
2214        }
2215    }
2216
2217    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2218        if let ProjectClientState::Remote {
2219            sharing_has_stopped,
2220            ..
2221        } = &mut self.client_state
2222        {
2223            *sharing_has_stopped = true;
2224            self.collaborators.clear();
2225            self.worktree_store.update(cx, |store, cx| {
2226                store.disconnected_from_host(cx);
2227            });
2228            self.buffer_store.update(cx, |buffer_store, cx| {
2229                buffer_store.disconnected_from_host(cx)
2230            });
2231            self.lsp_store
2232                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2233        }
2234    }
2235
2236    pub fn close(&mut self, cx: &mut Context<Self>) {
2237        cx.emit(Event::Closed);
2238    }
2239
2240    pub fn is_disconnected(&self, cx: &App) -> bool {
2241        match &self.client_state {
2242            ProjectClientState::Remote {
2243                sharing_has_stopped,
2244                ..
2245            } => *sharing_has_stopped,
2246            ProjectClientState::Local if self.is_via_ssh() => self.ssh_is_disconnected(cx),
2247            _ => false,
2248        }
2249    }
2250
2251    fn ssh_is_disconnected(&self, cx: &App) -> bool {
2252        self.ssh_client
2253            .as_ref()
2254            .map(|ssh| ssh.read(cx).is_disconnected())
2255            .unwrap_or(false)
2256    }
2257
2258    pub fn capability(&self) -> Capability {
2259        match &self.client_state {
2260            ProjectClientState::Remote { capability, .. } => *capability,
2261            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2262        }
2263    }
2264
2265    pub fn is_read_only(&self, cx: &App) -> bool {
2266        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2267    }
2268
2269    pub fn is_local(&self) -> bool {
2270        match &self.client_state {
2271            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2272                self.ssh_client.is_none()
2273            }
2274            ProjectClientState::Remote { .. } => false,
2275        }
2276    }
2277
2278    pub fn is_via_ssh(&self) -> bool {
2279        match &self.client_state {
2280            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2281                self.ssh_client.is_some()
2282            }
2283            ProjectClientState::Remote { .. } => false,
2284        }
2285    }
2286
2287    pub fn is_via_collab(&self) -> bool {
2288        match &self.client_state {
2289            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2290            ProjectClientState::Remote { .. } => true,
2291        }
2292    }
2293
2294    pub fn create_buffer(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
2295        self.buffer_store
2296            .update(cx, |buffer_store, cx| buffer_store.create_buffer(cx))
2297    }
2298
2299    pub fn create_local_buffer(
2300        &mut self,
2301        text: &str,
2302        language: Option<Arc<Language>>,
2303        cx: &mut Context<Self>,
2304    ) -> Entity<Buffer> {
2305        if self.is_via_collab() || self.is_via_ssh() {
2306            panic!("called create_local_buffer on a remote project")
2307        }
2308        self.buffer_store.update(cx, |buffer_store, cx| {
2309            buffer_store.create_local_buffer(text, language, cx)
2310        })
2311    }
2312
2313    pub fn open_path(
2314        &mut self,
2315        path: ProjectPath,
2316        cx: &mut Context<Self>,
2317    ) -> Task<Result<(Option<ProjectEntryId>, AnyEntity)>> {
2318        let task = self.open_buffer(path.clone(), cx);
2319        cx.spawn(async move |_project, cx| {
2320            let buffer = task.await?;
2321            let project_entry_id = buffer.read_with(cx, |buffer, cx| {
2322                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
2323            })?;
2324
2325            let buffer: &AnyEntity = &buffer;
2326            Ok((project_entry_id, buffer.clone()))
2327        })
2328    }
2329
2330    pub fn open_local_buffer(
2331        &mut self,
2332        abs_path: impl AsRef<Path>,
2333        cx: &mut Context<Self>,
2334    ) -> Task<Result<Entity<Buffer>>> {
2335        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2336            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
2337        } else {
2338            Task::ready(Err(anyhow!("no such path")))
2339        }
2340    }
2341
2342    #[cfg(any(test, feature = "test-support"))]
2343    pub fn open_local_buffer_with_lsp(
2344        &mut self,
2345        abs_path: impl AsRef<Path>,
2346        cx: &mut Context<Self>,
2347    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2348        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2349            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2350        } else {
2351            Task::ready(Err(anyhow!("no such path")))
2352        }
2353    }
2354
2355    pub fn open_buffer(
2356        &mut self,
2357        path: impl Into<ProjectPath>,
2358        cx: &mut App,
2359    ) -> Task<Result<Entity<Buffer>>> {
2360        if self.is_disconnected(cx) {
2361            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2362        }
2363
2364        self.buffer_store.update(cx, |buffer_store, cx| {
2365            buffer_store.open_buffer(path.into(), cx)
2366        })
2367    }
2368
2369    #[cfg(any(test, feature = "test-support"))]
2370    pub fn open_buffer_with_lsp(
2371        &mut self,
2372        path: impl Into<ProjectPath>,
2373        cx: &mut Context<Self>,
2374    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2375        let buffer = self.open_buffer(path, cx);
2376        cx.spawn(async move |this, cx| {
2377            let buffer = buffer.await?;
2378            let handle = this.update(cx, |project, cx| {
2379                project.register_buffer_with_language_servers(&buffer, cx)
2380            })?;
2381            Ok((buffer, handle))
2382        })
2383    }
2384
2385    pub fn register_buffer_with_language_servers(
2386        &self,
2387        buffer: &Entity<Buffer>,
2388        cx: &mut App,
2389    ) -> OpenLspBufferHandle {
2390        self.lsp_store.update(cx, |lsp_store, cx| {
2391            lsp_store.register_buffer_with_language_servers(&buffer, false, cx)
2392        })
2393    }
2394
2395    pub fn open_unstaged_diff(
2396        &mut self,
2397        buffer: Entity<Buffer>,
2398        cx: &mut Context<Self>,
2399    ) -> Task<Result<Entity<BufferDiff>>> {
2400        if self.is_disconnected(cx) {
2401            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2402        }
2403        self.git_store
2404            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2405    }
2406
2407    pub fn open_uncommitted_diff(
2408        &mut self,
2409        buffer: Entity<Buffer>,
2410        cx: &mut Context<Self>,
2411    ) -> Task<Result<Entity<BufferDiff>>> {
2412        if self.is_disconnected(cx) {
2413            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2414        }
2415        self.git_store.update(cx, |git_store, cx| {
2416            git_store.open_uncommitted_diff(buffer, cx)
2417        })
2418    }
2419
2420    pub fn open_buffer_by_id(
2421        &mut self,
2422        id: BufferId,
2423        cx: &mut Context<Self>,
2424    ) -> Task<Result<Entity<Buffer>>> {
2425        if let Some(buffer) = self.buffer_for_id(id, cx) {
2426            Task::ready(Ok(buffer))
2427        } else if self.is_local() || self.is_via_ssh() {
2428            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
2429        } else if let Some(project_id) = self.remote_id() {
2430            let request = self.client.request(proto::OpenBufferById {
2431                project_id,
2432                id: id.into(),
2433            });
2434            cx.spawn(async move |project, cx| {
2435                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2436                project
2437                    .update(cx, |project, cx| {
2438                        project.buffer_store.update(cx, |buffer_store, cx| {
2439                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2440                        })
2441                    })?
2442                    .await
2443            })
2444        } else {
2445            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2446        }
2447    }
2448
2449    pub fn save_buffers(
2450        &self,
2451        buffers: HashSet<Entity<Buffer>>,
2452        cx: &mut Context<Self>,
2453    ) -> Task<Result<()>> {
2454        cx.spawn(async move |this, cx| {
2455            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2456                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2457                    .ok()
2458            });
2459            try_join_all(save_tasks).await?;
2460            Ok(())
2461        })
2462    }
2463
2464    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2465        self.buffer_store
2466            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2467    }
2468
2469    pub fn save_buffer_as(
2470        &mut self,
2471        buffer: Entity<Buffer>,
2472        path: ProjectPath,
2473        cx: &mut Context<Self>,
2474    ) -> Task<Result<()>> {
2475        self.buffer_store.update(cx, |buffer_store, cx| {
2476            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2477        })
2478    }
2479
2480    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2481        self.buffer_store.read(cx).get_by_path(path, cx)
2482    }
2483
2484    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2485        {
2486            let mut remotely_created_models = self.remotely_created_models.lock();
2487            if remotely_created_models.retain_count > 0 {
2488                remotely_created_models.buffers.push(buffer.clone())
2489            }
2490        }
2491
2492        self.request_buffer_diff_recalculation(buffer, cx);
2493
2494        cx.subscribe(buffer, |this, buffer, event, cx| {
2495            this.on_buffer_event(buffer, event, cx);
2496        })
2497        .detach();
2498
2499        Ok(())
2500    }
2501
2502    pub fn open_image(
2503        &mut self,
2504        path: impl Into<ProjectPath>,
2505        cx: &mut Context<Self>,
2506    ) -> Task<Result<Entity<ImageItem>>> {
2507        if self.is_disconnected(cx) {
2508            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2509        }
2510
2511        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2512            image_store.open_image(path.into(), cx)
2513        });
2514
2515        let weak_project = cx.entity().downgrade();
2516        cx.spawn(async move |_, cx| {
2517            let image_item = open_image_task.await?;
2518            let project = weak_project
2519                .upgrade()
2520                .ok_or_else(|| anyhow!("Project dropped"))?;
2521
2522            let metadata = ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2523            image_item.update(cx, |image_item, cx| {
2524                image_item.image_metadata = Some(metadata);
2525                cx.emit(ImageItemEvent::MetadataUpdated);
2526            })?;
2527
2528            Ok(image_item)
2529        })
2530    }
2531
2532    async fn send_buffer_ordered_messages(
2533        this: WeakEntity<Self>,
2534        rx: UnboundedReceiver<BufferOrderedMessage>,
2535        cx: &mut AsyncApp,
2536    ) -> Result<()> {
2537        const MAX_BATCH_SIZE: usize = 128;
2538
2539        let mut operations_by_buffer_id = HashMap::default();
2540        async fn flush_operations(
2541            this: &WeakEntity<Project>,
2542            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2543            needs_resync_with_host: &mut bool,
2544            is_local: bool,
2545            cx: &mut AsyncApp,
2546        ) -> Result<()> {
2547            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2548                let request = this.update(cx, |this, _| {
2549                    let project_id = this.remote_id()?;
2550                    Some(this.client.request(proto::UpdateBuffer {
2551                        buffer_id: buffer_id.into(),
2552                        project_id,
2553                        operations,
2554                    }))
2555                })?;
2556                if let Some(request) = request {
2557                    if request.await.is_err() && !is_local {
2558                        *needs_resync_with_host = true;
2559                        break;
2560                    }
2561                }
2562            }
2563            Ok(())
2564        }
2565
2566        let mut needs_resync_with_host = false;
2567        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2568
2569        while let Some(changes) = changes.next().await {
2570            let is_local = this.update(cx, |this, _| this.is_local())?;
2571
2572            for change in changes {
2573                match change {
2574                    BufferOrderedMessage::Operation {
2575                        buffer_id,
2576                        operation,
2577                    } => {
2578                        if needs_resync_with_host {
2579                            continue;
2580                        }
2581
2582                        operations_by_buffer_id
2583                            .entry(buffer_id)
2584                            .or_insert(Vec::new())
2585                            .push(operation);
2586                    }
2587
2588                    BufferOrderedMessage::Resync => {
2589                        operations_by_buffer_id.clear();
2590                        if this
2591                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
2592                            .await
2593                            .is_ok()
2594                        {
2595                            needs_resync_with_host = false;
2596                        }
2597                    }
2598
2599                    BufferOrderedMessage::LanguageServerUpdate {
2600                        language_server_id,
2601                        message,
2602                    } => {
2603                        flush_operations(
2604                            &this,
2605                            &mut operations_by_buffer_id,
2606                            &mut needs_resync_with_host,
2607                            is_local,
2608                            cx,
2609                        )
2610                        .await?;
2611
2612                        this.update(cx, |this, _| {
2613                            if let Some(project_id) = this.remote_id() {
2614                                this.client
2615                                    .send(proto::UpdateLanguageServer {
2616                                        project_id,
2617                                        language_server_id: language_server_id.0 as u64,
2618                                        variant: Some(message),
2619                                    })
2620                                    .log_err();
2621                            }
2622                        })?;
2623                    }
2624                }
2625            }
2626
2627            flush_operations(
2628                &this,
2629                &mut operations_by_buffer_id,
2630                &mut needs_resync_with_host,
2631                is_local,
2632                cx,
2633            )
2634            .await?;
2635        }
2636
2637        Ok(())
2638    }
2639
2640    fn on_buffer_store_event(
2641        &mut self,
2642        _: Entity<BufferStore>,
2643        event: &BufferStoreEvent,
2644        cx: &mut Context<Self>,
2645    ) {
2646        match event {
2647            BufferStoreEvent::BufferAdded(buffer) => {
2648                self.register_buffer(buffer, cx).log_err();
2649            }
2650            BufferStoreEvent::BufferDropped(buffer_id) => {
2651                if let Some(ref ssh_client) = self.ssh_client {
2652                    ssh_client
2653                        .read(cx)
2654                        .proto_client()
2655                        .send(proto::CloseBuffer {
2656                            project_id: 0,
2657                            buffer_id: buffer_id.to_proto(),
2658                        })
2659                        .log_err();
2660                }
2661            }
2662            _ => {}
2663        }
2664    }
2665
2666    fn on_image_store_event(
2667        &mut self,
2668        _: Entity<ImageStore>,
2669        event: &ImageStoreEvent,
2670        cx: &mut Context<Self>,
2671    ) {
2672        match event {
2673            ImageStoreEvent::ImageAdded(image) => {
2674                cx.subscribe(image, |this, image, event, cx| {
2675                    this.on_image_event(image, event, cx);
2676                })
2677                .detach();
2678            }
2679        }
2680    }
2681
2682    fn on_dap_store_event(
2683        &mut self,
2684        _: Entity<DapStore>,
2685        event: &DapStoreEvent,
2686        cx: &mut Context<Self>,
2687    ) {
2688        match event {
2689            DapStoreEvent::Notification(message) => {
2690                cx.emit(Event::Toast {
2691                    notification_id: "dap".into(),
2692                    message: message.clone(),
2693                });
2694            }
2695            _ => {}
2696        }
2697    }
2698
2699    fn on_lsp_store_event(
2700        &mut self,
2701        _: Entity<LspStore>,
2702        event: &LspStoreEvent,
2703        cx: &mut Context<Self>,
2704    ) {
2705        match event {
2706            LspStoreEvent::DiagnosticsUpdated {
2707                language_server_id,
2708                path,
2709            } => cx.emit(Event::DiagnosticsUpdated {
2710                path: path.clone(),
2711                language_server_id: *language_server_id,
2712            }),
2713            LspStoreEvent::LanguageServerAdded(language_server_id, name, worktree_id) => cx.emit(
2714                Event::LanguageServerAdded(*language_server_id, name.clone(), *worktree_id),
2715            ),
2716            LspStoreEvent::LanguageServerRemoved(language_server_id) => {
2717                cx.emit(Event::LanguageServerRemoved(*language_server_id))
2718            }
2719            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
2720                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
2721            ),
2722            LspStoreEvent::LanguageDetected {
2723                buffer,
2724                new_language,
2725            } => {
2726                let Some(_) = new_language else {
2727                    cx.emit(Event::LanguageNotFound(buffer.clone()));
2728                    return;
2729                };
2730            }
2731            LspStoreEvent::RefreshInlayHints => cx.emit(Event::RefreshInlayHints),
2732            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
2733            LspStoreEvent::LanguageServerPrompt(prompt) => {
2734                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
2735            }
2736            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
2737                cx.emit(Event::DiskBasedDiagnosticsStarted {
2738                    language_server_id: *language_server_id,
2739                });
2740            }
2741            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
2742                cx.emit(Event::DiskBasedDiagnosticsFinished {
2743                    language_server_id: *language_server_id,
2744                });
2745            }
2746            LspStoreEvent::LanguageServerUpdate {
2747                language_server_id,
2748                message,
2749            } => {
2750                if self.is_local() {
2751                    self.enqueue_buffer_ordered_message(
2752                        BufferOrderedMessage::LanguageServerUpdate {
2753                            language_server_id: *language_server_id,
2754                            message: message.clone(),
2755                        },
2756                    )
2757                    .ok();
2758                }
2759            }
2760            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
2761                notification_id: "lsp".into(),
2762                message: message.clone(),
2763            }),
2764            LspStoreEvent::SnippetEdit {
2765                buffer_id,
2766                edits,
2767                most_recent_edit,
2768            } => {
2769                if most_recent_edit.replica_id == self.replica_id() {
2770                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
2771                }
2772            }
2773        }
2774    }
2775
2776    fn on_ssh_event(
2777        &mut self,
2778        _: Entity<SshRemoteClient>,
2779        event: &remote::SshRemoteEvent,
2780        cx: &mut Context<Self>,
2781    ) {
2782        match event {
2783            remote::SshRemoteEvent::Disconnected => {
2784                // if self.is_via_ssh() {
2785                // self.collaborators.clear();
2786                self.worktree_store.update(cx, |store, cx| {
2787                    store.disconnected_from_host(cx);
2788                });
2789                self.buffer_store.update(cx, |buffer_store, cx| {
2790                    buffer_store.disconnected_from_host(cx)
2791                });
2792                self.lsp_store.update(cx, |lsp_store, _cx| {
2793                    lsp_store.disconnected_from_ssh_remote()
2794                });
2795                cx.emit(Event::DisconnectedFromSshRemote);
2796            }
2797        }
2798    }
2799
2800    fn on_settings_observer_event(
2801        &mut self,
2802        _: Entity<SettingsObserver>,
2803        event: &SettingsObserverEvent,
2804        cx: &mut Context<Self>,
2805    ) {
2806        match event {
2807            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
2808                Err(InvalidSettingsError::LocalSettings { message, path }) => {
2809                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
2810                    cx.emit(Event::Toast {
2811                        notification_id: format!("local-settings-{path:?}").into(),
2812                        message,
2813                    });
2814                }
2815                Ok(path) => cx.emit(Event::HideToast {
2816                    notification_id: format!("local-settings-{path:?}").into(),
2817                }),
2818                Err(_) => {}
2819            },
2820            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
2821                Err(InvalidSettingsError::Tasks { message, path }) => {
2822                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
2823                    cx.emit(Event::Toast {
2824                        notification_id: format!("local-tasks-{path:?}").into(),
2825                        message,
2826                    });
2827                }
2828                Ok(path) => cx.emit(Event::HideToast {
2829                    notification_id: format!("local-tasks-{path:?}").into(),
2830                }),
2831                Err(_) => {}
2832            },
2833        }
2834    }
2835
2836    fn on_worktree_store_event(
2837        &mut self,
2838        _: Entity<WorktreeStore>,
2839        event: &WorktreeStoreEvent,
2840        cx: &mut Context<Self>,
2841    ) {
2842        match event {
2843            WorktreeStoreEvent::WorktreeAdded(worktree) => {
2844                self.on_worktree_added(worktree, cx);
2845                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
2846            }
2847            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
2848                cx.emit(Event::WorktreeRemoved(*id));
2849            }
2850            WorktreeStoreEvent::WorktreeReleased(_, id) => {
2851                self.on_worktree_released(*id, cx);
2852            }
2853            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
2854            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
2855            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
2856                self.client()
2857                    .telemetry()
2858                    .report_discovered_project_events(*worktree_id, changes);
2859                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
2860            }
2861            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
2862                cx.emit(Event::DeletedEntry(*worktree_id, *id))
2863            }
2864            // Listen to the GitStore instead.
2865            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
2866        }
2867    }
2868
2869    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
2870        let mut remotely_created_models = self.remotely_created_models.lock();
2871        if remotely_created_models.retain_count > 0 {
2872            remotely_created_models.worktrees.push(worktree.clone())
2873        }
2874    }
2875
2876    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
2877        if let Some(ssh) = &self.ssh_client {
2878            ssh.read(cx)
2879                .proto_client()
2880                .send(proto::RemoveWorktree {
2881                    worktree_id: id_to_remove.to_proto(),
2882                })
2883                .log_err();
2884        }
2885    }
2886
2887    fn on_buffer_event(
2888        &mut self,
2889        buffer: Entity<Buffer>,
2890        event: &BufferEvent,
2891        cx: &mut Context<Self>,
2892    ) -> Option<()> {
2893        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
2894            self.request_buffer_diff_recalculation(&buffer, cx);
2895        }
2896
2897        let buffer_id = buffer.read(cx).remote_id();
2898        match event {
2899            BufferEvent::ReloadNeeded => {
2900                if !self.is_via_collab() {
2901                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
2902                        .detach_and_log_err(cx);
2903                }
2904            }
2905            BufferEvent::Operation {
2906                operation,
2907                is_local: true,
2908            } => {
2909                let operation = language::proto::serialize_operation(operation);
2910
2911                if let Some(ssh) = &self.ssh_client {
2912                    ssh.read(cx)
2913                        .proto_client()
2914                        .send(proto::UpdateBuffer {
2915                            project_id: 0,
2916                            buffer_id: buffer_id.to_proto(),
2917                            operations: vec![operation.clone()],
2918                        })
2919                        .ok();
2920                }
2921
2922                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
2923                    buffer_id,
2924                    operation,
2925                })
2926                .ok();
2927            }
2928
2929            _ => {}
2930        }
2931
2932        None
2933    }
2934
2935    fn on_image_event(
2936        &mut self,
2937        image: Entity<ImageItem>,
2938        event: &ImageItemEvent,
2939        cx: &mut Context<Self>,
2940    ) -> Option<()> {
2941        match event {
2942            ImageItemEvent::ReloadNeeded => {
2943                if !self.is_via_collab() {
2944                    self.reload_images([image.clone()].into_iter().collect(), cx)
2945                        .detach_and_log_err(cx);
2946                }
2947            }
2948            _ => {}
2949        }
2950
2951        None
2952    }
2953
2954    fn request_buffer_diff_recalculation(
2955        &mut self,
2956        buffer: &Entity<Buffer>,
2957        cx: &mut Context<Self>,
2958    ) {
2959        self.buffers_needing_diff.insert(buffer.downgrade());
2960        let first_insertion = self.buffers_needing_diff.len() == 1;
2961
2962        let settings = ProjectSettings::get_global(cx);
2963        let delay = if let Some(delay) = settings.git.gutter_debounce {
2964            delay
2965        } else {
2966            if first_insertion {
2967                let this = cx.weak_entity();
2968                cx.defer(move |cx| {
2969                    if let Some(this) = this.upgrade() {
2970                        this.update(cx, |this, cx| {
2971                            this.recalculate_buffer_diffs(cx).detach();
2972                        });
2973                    }
2974                });
2975            }
2976            return;
2977        };
2978
2979        const MIN_DELAY: u64 = 50;
2980        let delay = delay.max(MIN_DELAY);
2981        let duration = Duration::from_millis(delay);
2982
2983        self.git_diff_debouncer
2984            .fire_new(duration, cx, move |this, cx| {
2985                this.recalculate_buffer_diffs(cx)
2986            });
2987    }
2988
2989    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
2990        cx.spawn(async move |this, cx| {
2991            loop {
2992                let task = this
2993                    .update(cx, |this, cx| {
2994                        let buffers = this
2995                            .buffers_needing_diff
2996                            .drain()
2997                            .filter_map(|buffer| buffer.upgrade())
2998                            .collect::<Vec<_>>();
2999                        if buffers.is_empty() {
3000                            None
3001                        } else {
3002                            Some(this.git_store.update(cx, |git_store, cx| {
3003                                git_store.recalculate_buffer_diffs(buffers, cx)
3004                            }))
3005                        }
3006                    })
3007                    .ok()
3008                    .flatten();
3009
3010                if let Some(task) = task {
3011                    task.await;
3012                } else {
3013                    break;
3014                }
3015            }
3016        })
3017    }
3018
3019    pub fn set_language_for_buffer(
3020        &mut self,
3021        buffer: &Entity<Buffer>,
3022        new_language: Arc<Language>,
3023        cx: &mut Context<Self>,
3024    ) {
3025        self.lsp_store.update(cx, |lsp_store, cx| {
3026            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3027        })
3028    }
3029
3030    pub fn restart_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.restart_language_servers_for_buffers(buffers, cx)
3037        })
3038    }
3039
3040    pub fn stop_language_servers_for_buffers(
3041        &mut self,
3042        buffers: Vec<Entity<Buffer>>,
3043        cx: &mut Context<Self>,
3044    ) {
3045        self.lsp_store.update(cx, |lsp_store, cx| {
3046            lsp_store.stop_language_servers_for_buffers(buffers, cx)
3047        })
3048    }
3049
3050    pub fn cancel_language_server_work_for_buffers(
3051        &mut self,
3052        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3053        cx: &mut Context<Self>,
3054    ) {
3055        self.lsp_store.update(cx, |lsp_store, cx| {
3056            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3057        })
3058    }
3059
3060    pub fn cancel_language_server_work(
3061        &mut self,
3062        server_id: LanguageServerId,
3063        token_to_cancel: Option<String>,
3064        cx: &mut Context<Self>,
3065    ) {
3066        self.lsp_store.update(cx, |lsp_store, cx| {
3067            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3068        })
3069    }
3070
3071    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3072        self.buffer_ordered_messages_tx
3073            .unbounded_send(message)
3074            .map_err(|e| anyhow!(e))
3075    }
3076
3077    pub fn available_toolchains(
3078        &self,
3079        path: ProjectPath,
3080        language_name: LanguageName,
3081        cx: &App,
3082    ) -> Task<Option<ToolchainList>> {
3083        if let Some(toolchain_store) = self.toolchain_store.clone() {
3084            cx.spawn(async move |cx| {
3085                cx.update(|cx| {
3086                    toolchain_store
3087                        .read(cx)
3088                        .list_toolchains(path, language_name, cx)
3089                })
3090                .ok()?
3091                .await
3092            })
3093        } else {
3094            Task::ready(None)
3095        }
3096    }
3097
3098    pub async fn toolchain_term(
3099        languages: Arc<LanguageRegistry>,
3100        language_name: LanguageName,
3101    ) -> Option<SharedString> {
3102        languages
3103            .language_for_name(language_name.as_ref())
3104            .await
3105            .ok()?
3106            .toolchain_lister()
3107            .map(|lister| lister.term())
3108    }
3109
3110    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3111        self.toolchain_store.clone()
3112    }
3113    pub fn activate_toolchain(
3114        &self,
3115        path: ProjectPath,
3116        toolchain: Toolchain,
3117        cx: &mut App,
3118    ) -> Task<Option<()>> {
3119        let Some(toolchain_store) = self.toolchain_store.clone() else {
3120            return Task::ready(None);
3121        };
3122        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3123    }
3124    pub fn active_toolchain(
3125        &self,
3126        path: ProjectPath,
3127        language_name: LanguageName,
3128        cx: &App,
3129    ) -> Task<Option<Toolchain>> {
3130        let Some(toolchain_store) = self.toolchain_store.clone() else {
3131            return Task::ready(None);
3132        };
3133        toolchain_store
3134            .read(cx)
3135            .active_toolchain(path, language_name, cx)
3136    }
3137    pub fn language_server_statuses<'a>(
3138        &'a self,
3139        cx: &'a App,
3140    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3141        self.lsp_store.read(cx).language_server_statuses()
3142    }
3143
3144    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3145        self.lsp_store.read(cx).last_formatting_failure()
3146    }
3147
3148    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3149        self.lsp_store
3150            .update(cx, |store, _| store.reset_last_formatting_failure());
3151    }
3152
3153    pub fn reload_buffers(
3154        &self,
3155        buffers: HashSet<Entity<Buffer>>,
3156        push_to_history: bool,
3157        cx: &mut Context<Self>,
3158    ) -> Task<Result<ProjectTransaction>> {
3159        self.buffer_store.update(cx, |buffer_store, cx| {
3160            buffer_store.reload_buffers(buffers, push_to_history, cx)
3161        })
3162    }
3163
3164    pub fn reload_images(
3165        &self,
3166        images: HashSet<Entity<ImageItem>>,
3167        cx: &mut Context<Self>,
3168    ) -> Task<Result<()>> {
3169        self.image_store
3170            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3171    }
3172
3173    pub fn format(
3174        &mut self,
3175        buffers: HashSet<Entity<Buffer>>,
3176        target: LspFormatTarget,
3177        push_to_history: bool,
3178        trigger: lsp_store::FormatTrigger,
3179        cx: &mut Context<Project>,
3180    ) -> Task<anyhow::Result<ProjectTransaction>> {
3181        self.lsp_store.update(cx, |lsp_store, cx| {
3182            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3183        })
3184    }
3185
3186    #[inline(never)]
3187    fn definition_impl(
3188        &mut self,
3189        buffer: &Entity<Buffer>,
3190        position: PointUtf16,
3191        cx: &mut Context<Self>,
3192    ) -> Task<Result<Vec<LocationLink>>> {
3193        self.request_lsp(
3194            buffer.clone(),
3195            LanguageServerToQuery::FirstCapable,
3196            GetDefinition { position },
3197            cx,
3198        )
3199    }
3200    pub fn definition<T: ToPointUtf16>(
3201        &mut self,
3202        buffer: &Entity<Buffer>,
3203        position: T,
3204        cx: &mut Context<Self>,
3205    ) -> Task<Result<Vec<LocationLink>>> {
3206        let position = position.to_point_utf16(buffer.read(cx));
3207        self.definition_impl(buffer, position, cx)
3208    }
3209
3210    fn declaration_impl(
3211        &mut self,
3212        buffer: &Entity<Buffer>,
3213        position: PointUtf16,
3214        cx: &mut Context<Self>,
3215    ) -> Task<Result<Vec<LocationLink>>> {
3216        self.request_lsp(
3217            buffer.clone(),
3218            LanguageServerToQuery::FirstCapable,
3219            GetDeclaration { position },
3220            cx,
3221        )
3222    }
3223
3224    pub fn declaration<T: ToPointUtf16>(
3225        &mut self,
3226        buffer: &Entity<Buffer>,
3227        position: T,
3228        cx: &mut Context<Self>,
3229    ) -> Task<Result<Vec<LocationLink>>> {
3230        let position = position.to_point_utf16(buffer.read(cx));
3231        self.declaration_impl(buffer, position, cx)
3232    }
3233
3234    fn type_definition_impl(
3235        &mut self,
3236        buffer: &Entity<Buffer>,
3237        position: PointUtf16,
3238        cx: &mut Context<Self>,
3239    ) -> Task<Result<Vec<LocationLink>>> {
3240        self.request_lsp(
3241            buffer.clone(),
3242            LanguageServerToQuery::FirstCapable,
3243            GetTypeDefinition { position },
3244            cx,
3245        )
3246    }
3247
3248    pub fn type_definition<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.type_definition_impl(buffer, position, cx)
3256    }
3257
3258    pub fn implementation<T: ToPointUtf16>(
3259        &mut self,
3260        buffer: &Entity<Buffer>,
3261        position: T,
3262        cx: &mut Context<Self>,
3263    ) -> Task<Result<Vec<LocationLink>>> {
3264        let position = position.to_point_utf16(buffer.read(cx));
3265        self.request_lsp(
3266            buffer.clone(),
3267            LanguageServerToQuery::FirstCapable,
3268            GetImplementation { position },
3269            cx,
3270        )
3271    }
3272
3273    pub fn references<T: ToPointUtf16>(
3274        &mut self,
3275        buffer: &Entity<Buffer>,
3276        position: T,
3277        cx: &mut Context<Self>,
3278    ) -> Task<Result<Vec<Location>>> {
3279        let position = position.to_point_utf16(buffer.read(cx));
3280        self.request_lsp(
3281            buffer.clone(),
3282            LanguageServerToQuery::FirstCapable,
3283            GetReferences { position },
3284            cx,
3285        )
3286    }
3287
3288    fn document_highlights_impl(
3289        &mut self,
3290        buffer: &Entity<Buffer>,
3291        position: PointUtf16,
3292        cx: &mut Context<Self>,
3293    ) -> Task<Result<Vec<DocumentHighlight>>> {
3294        self.request_lsp(
3295            buffer.clone(),
3296            LanguageServerToQuery::FirstCapable,
3297            GetDocumentHighlights { position },
3298            cx,
3299        )
3300    }
3301
3302    pub fn document_highlights<T: ToPointUtf16>(
3303        &mut self,
3304        buffer: &Entity<Buffer>,
3305        position: T,
3306        cx: &mut Context<Self>,
3307    ) -> Task<Result<Vec<DocumentHighlight>>> {
3308        let position = position.to_point_utf16(buffer.read(cx));
3309        self.document_highlights_impl(buffer, position, cx)
3310    }
3311
3312    pub fn document_symbols(
3313        &mut self,
3314        buffer: &Entity<Buffer>,
3315        cx: &mut Context<Self>,
3316    ) -> Task<Result<Vec<DocumentSymbol>>> {
3317        self.request_lsp(
3318            buffer.clone(),
3319            LanguageServerToQuery::FirstCapable,
3320            GetDocumentSymbols,
3321            cx,
3322        )
3323    }
3324
3325    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3326        self.lsp_store
3327            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3328    }
3329
3330    pub fn open_buffer_for_symbol(
3331        &mut self,
3332        symbol: &Symbol,
3333        cx: &mut Context<Self>,
3334    ) -> Task<Result<Entity<Buffer>>> {
3335        self.lsp_store.update(cx, |lsp_store, cx| {
3336            lsp_store.open_buffer_for_symbol(symbol, cx)
3337        })
3338    }
3339
3340    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3341        let guard = self.retain_remotely_created_models(cx);
3342        let Some(ssh_client) = self.ssh_client.as_ref() else {
3343            return Task::ready(Err(anyhow!("not an ssh project")));
3344        };
3345
3346        let proto_client = ssh_client.read(cx).proto_client();
3347
3348        cx.spawn(async move |project, cx| {
3349            let buffer = proto_client
3350                .request(proto::OpenServerSettings {
3351                    project_id: SSH_PROJECT_ID,
3352                })
3353                .await?;
3354
3355            let buffer = project
3356                .update(cx, |project, cx| {
3357                    project.buffer_store.update(cx, |buffer_store, cx| {
3358                        anyhow::Ok(
3359                            buffer_store
3360                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3361                        )
3362                    })
3363                })??
3364                .await;
3365
3366            drop(guard);
3367            buffer
3368        })
3369    }
3370
3371    pub fn open_local_buffer_via_lsp(
3372        &mut self,
3373        abs_path: lsp::Url,
3374        language_server_id: LanguageServerId,
3375        language_server_name: LanguageServerName,
3376        cx: &mut Context<Self>,
3377    ) -> Task<Result<Entity<Buffer>>> {
3378        self.lsp_store.update(cx, |lsp_store, cx| {
3379            lsp_store.open_local_buffer_via_lsp(
3380                abs_path,
3381                language_server_id,
3382                language_server_name,
3383                cx,
3384            )
3385        })
3386    }
3387
3388    pub fn signature_help<T: ToPointUtf16>(
3389        &self,
3390        buffer: &Entity<Buffer>,
3391        position: T,
3392        cx: &mut Context<Self>,
3393    ) -> Task<Vec<SignatureHelp>> {
3394        self.lsp_store.update(cx, |lsp_store, cx| {
3395            lsp_store.signature_help(buffer, position, cx)
3396        })
3397    }
3398
3399    pub fn hover<T: ToPointUtf16>(
3400        &self,
3401        buffer: &Entity<Buffer>,
3402        position: T,
3403        cx: &mut Context<Self>,
3404    ) -> Task<Vec<Hover>> {
3405        let position = position.to_point_utf16(buffer.read(cx));
3406        self.lsp_store
3407            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3408    }
3409
3410    pub fn linked_edit(
3411        &self,
3412        buffer: &Entity<Buffer>,
3413        position: Anchor,
3414        cx: &mut Context<Self>,
3415    ) -> Task<Result<Vec<Range<Anchor>>>> {
3416        self.lsp_store.update(cx, |lsp_store, cx| {
3417            lsp_store.linked_edit(buffer, position, cx)
3418        })
3419    }
3420
3421    pub fn completions<T: ToOffset + ToPointUtf16>(
3422        &self,
3423        buffer: &Entity<Buffer>,
3424        position: T,
3425        context: CompletionContext,
3426        cx: &mut Context<Self>,
3427    ) -> Task<Result<Option<Vec<Completion>>>> {
3428        let position = position.to_point_utf16(buffer.read(cx));
3429        self.lsp_store.update(cx, |lsp_store, cx| {
3430            lsp_store.completions(buffer, position, context, cx)
3431        })
3432    }
3433
3434    pub fn code_actions<T: Clone + ToOffset>(
3435        &mut self,
3436        buffer_handle: &Entity<Buffer>,
3437        range: Range<T>,
3438        kinds: Option<Vec<CodeActionKind>>,
3439        cx: &mut Context<Self>,
3440    ) -> Task<Result<Vec<CodeAction>>> {
3441        let buffer = buffer_handle.read(cx);
3442        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3443        self.lsp_store.update(cx, |lsp_store, cx| {
3444            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3445        })
3446    }
3447
3448    pub fn code_lens<T: Clone + ToOffset>(
3449        &mut self,
3450        buffer_handle: &Entity<Buffer>,
3451        range: Range<T>,
3452        cx: &mut Context<Self>,
3453    ) -> Task<Result<Vec<CodeAction>>> {
3454        let snapshot = buffer_handle.read(cx).snapshot();
3455        let range = snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end);
3456        let code_lens_actions = self
3457            .lsp_store
3458            .update(cx, |lsp_store, cx| lsp_store.code_lens(buffer_handle, cx));
3459
3460        cx.background_spawn(async move {
3461            let mut code_lens_actions = code_lens_actions.await?;
3462            code_lens_actions.retain(|code_lens_action| {
3463                range
3464                    .start
3465                    .cmp(&code_lens_action.range.start, &snapshot)
3466                    .is_ge()
3467                    && range
3468                        .end
3469                        .cmp(&code_lens_action.range.end, &snapshot)
3470                        .is_le()
3471            });
3472            Ok(code_lens_actions)
3473        })
3474    }
3475
3476    pub fn apply_code_action(
3477        &self,
3478        buffer_handle: Entity<Buffer>,
3479        action: CodeAction,
3480        push_to_history: bool,
3481        cx: &mut Context<Self>,
3482    ) -> Task<Result<ProjectTransaction>> {
3483        self.lsp_store.update(cx, |lsp_store, cx| {
3484            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
3485        })
3486    }
3487
3488    pub fn apply_code_action_kind(
3489        &self,
3490        buffers: HashSet<Entity<Buffer>>,
3491        kind: CodeActionKind,
3492        push_to_history: bool,
3493        cx: &mut Context<Self>,
3494    ) -> Task<Result<ProjectTransaction>> {
3495        self.lsp_store.update(cx, |lsp_store, cx| {
3496            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
3497        })
3498    }
3499
3500    fn prepare_rename_impl(
3501        &mut self,
3502        buffer: Entity<Buffer>,
3503        position: PointUtf16,
3504        cx: &mut Context<Self>,
3505    ) -> Task<Result<PrepareRenameResponse>> {
3506        self.request_lsp(
3507            buffer,
3508            LanguageServerToQuery::FirstCapable,
3509            PrepareRename { position },
3510            cx,
3511        )
3512    }
3513    pub fn prepare_rename<T: ToPointUtf16>(
3514        &mut self,
3515        buffer: Entity<Buffer>,
3516        position: T,
3517        cx: &mut Context<Self>,
3518    ) -> Task<Result<PrepareRenameResponse>> {
3519        let position = position.to_point_utf16(buffer.read(cx));
3520        self.prepare_rename_impl(buffer, position, cx)
3521    }
3522
3523    pub fn perform_rename<T: ToPointUtf16>(
3524        &mut self,
3525        buffer: Entity<Buffer>,
3526        position: T,
3527        new_name: String,
3528        cx: &mut Context<Self>,
3529    ) -> Task<Result<ProjectTransaction>> {
3530        let push_to_history = true;
3531        let position = position.to_point_utf16(buffer.read(cx));
3532        self.request_lsp(
3533            buffer,
3534            LanguageServerToQuery::FirstCapable,
3535            PerformRename {
3536                position,
3537                new_name,
3538                push_to_history,
3539            },
3540            cx,
3541        )
3542    }
3543
3544    pub fn on_type_format<T: ToPointUtf16>(
3545        &mut self,
3546        buffer: Entity<Buffer>,
3547        position: T,
3548        trigger: String,
3549        push_to_history: bool,
3550        cx: &mut Context<Self>,
3551    ) -> Task<Result<Option<Transaction>>> {
3552        self.lsp_store.update(cx, |lsp_store, cx| {
3553            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
3554        })
3555    }
3556
3557    pub fn inline_values(
3558        &mut self,
3559        session: Entity<Session>,
3560        active_stack_frame: ActiveStackFrame,
3561        buffer_handle: Entity<Buffer>,
3562        range: Range<text::Anchor>,
3563        cx: &mut Context<Self>,
3564    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
3565        let language_name = buffer_handle
3566            .read(cx)
3567            .language()
3568            .map(|language| language.name().to_string());
3569
3570        let Some(inline_value_provider) = language_name
3571            .and_then(|language| DapRegistry::global(cx).inline_value_provider(&language))
3572        else {
3573            return Task::ready(Err(anyhow::anyhow!("Inline value provider not found")));
3574        };
3575
3576        let snapshot = buffer_handle.read(cx).snapshot();
3577
3578        let root_node = snapshot.syntax_root_ancestor(range.end).unwrap();
3579
3580        let row = snapshot
3581            .summary_for_anchor::<text::PointUtf16>(&range.end)
3582            .row as usize;
3583
3584        let inline_value_locations = inline_value_provider.provide(
3585            root_node,
3586            snapshot
3587                .text_for_range(Anchor::MIN..range.end)
3588                .collect::<String>()
3589                .as_str(),
3590            row,
3591        );
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_value_locations(
3598                        session,
3599                        stack_frame_id,
3600                        buffer_handle,
3601                        inline_value_locations,
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(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
3908        if self.is_local() {
3909            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
3910            let fs = self.fs.clone();
3911            cx.background_spawn(async move {
3912                let path = expanded.as_path();
3913                let metadata = fs.metadata(path).await.ok().flatten();
3914
3915                metadata.map(|metadata| ResolvedPath::AbsPath {
3916                    path: expanded,
3917                    is_dir: metadata.is_dir,
3918                })
3919            })
3920        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
3921            let request_path = Path::new(path);
3922            let request = ssh_client
3923                .read(cx)
3924                .proto_client()
3925                .request(proto::GetPathMetadata {
3926                    project_id: SSH_PROJECT_ID,
3927                    path: request_path.to_proto(),
3928                });
3929            cx.background_spawn(async move {
3930                let response = request.await.log_err()?;
3931                if response.exists {
3932                    Some(ResolvedPath::AbsPath {
3933                        path: PathBuf::from_proto(response.path),
3934                        is_dir: response.is_dir,
3935                    })
3936                } else {
3937                    None
3938                }
3939            })
3940        } else {
3941            return Task::ready(None);
3942        }
3943    }
3944
3945    fn resolve_path_in_worktrees(
3946        &self,
3947        path: PathBuf,
3948        buffer: &Entity<Buffer>,
3949        cx: &mut Context<Self>,
3950    ) -> Task<Option<ResolvedPath>> {
3951        let mut candidates = vec![path.clone()];
3952
3953        if let Some(file) = buffer.read(cx).file() {
3954            if let Some(dir) = file.path().parent() {
3955                let joined = dir.to_path_buf().join(path);
3956                candidates.push(joined);
3957            }
3958        }
3959
3960        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
3961        let worktrees_with_ids: Vec<_> = self
3962            .worktrees(cx)
3963            .map(|worktree| {
3964                let id = worktree.read(cx).id();
3965                (worktree, id)
3966            })
3967            .collect();
3968
3969        cx.spawn(async move |_, mut cx| {
3970            if let Some(buffer_worktree_id) = buffer_worktree_id {
3971                if let Some((worktree, _)) = worktrees_with_ids
3972                    .iter()
3973                    .find(|(_, id)| *id == buffer_worktree_id)
3974                {
3975                    for candidate in candidates.iter() {
3976                        if let Some(path) =
3977                            Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3978                        {
3979                            return Some(path);
3980                        }
3981                    }
3982                }
3983            }
3984            for (worktree, id) in worktrees_with_ids {
3985                if Some(id) == buffer_worktree_id {
3986                    continue;
3987                }
3988                for candidate in candidates.iter() {
3989                    if let Some(path) =
3990                        Self::resolve_path_in_worktree(&worktree, candidate, &mut cx)
3991                    {
3992                        return Some(path);
3993                    }
3994                }
3995            }
3996            None
3997        })
3998    }
3999
4000    fn resolve_path_in_worktree(
4001        worktree: &Entity<Worktree>,
4002        path: &PathBuf,
4003        cx: &mut AsyncApp,
4004    ) -> Option<ResolvedPath> {
4005        worktree
4006            .update(cx, |worktree, _| {
4007                let root_entry_path = &worktree.root_entry()?.path;
4008                let resolved = resolve_path(root_entry_path, path);
4009                let stripped = resolved.strip_prefix(root_entry_path).unwrap_or(&resolved);
4010                worktree.entry_for_path(stripped).map(|entry| {
4011                    let project_path = ProjectPath {
4012                        worktree_id: worktree.id(),
4013                        path: entry.path.clone(),
4014                    };
4015                    ResolvedPath::ProjectPath {
4016                        project_path,
4017                        is_dir: entry.is_dir(),
4018                    }
4019                })
4020            })
4021            .ok()?
4022    }
4023
4024    pub fn list_directory(
4025        &self,
4026        query: String,
4027        cx: &mut Context<Self>,
4028    ) -> Task<Result<Vec<DirectoryItem>>> {
4029        if self.is_local() {
4030            DirectoryLister::Local(self.fs.clone()).list_directory(query, cx)
4031        } else if let Some(session) = self.ssh_client.as_ref() {
4032            let path_buf = PathBuf::from(query);
4033            let request = proto::ListRemoteDirectory {
4034                dev_server_id: SSH_PROJECT_ID,
4035                path: path_buf.to_proto(),
4036                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4037            };
4038
4039            let response = session.read(cx).proto_client().request(request);
4040            cx.background_spawn(async move {
4041                let proto::ListRemoteDirectoryResponse {
4042                    entries,
4043                    entry_info,
4044                } = response.await?;
4045                Ok(entries
4046                    .into_iter()
4047                    .zip(entry_info)
4048                    .map(|(entry, info)| DirectoryItem {
4049                        path: PathBuf::from(entry),
4050                        is_dir: info.is_dir,
4051                    })
4052                    .collect())
4053            })
4054        } else {
4055            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4056        }
4057    }
4058
4059    pub fn create_worktree(
4060        &mut self,
4061        abs_path: impl AsRef<Path>,
4062        visible: bool,
4063        cx: &mut Context<Self>,
4064    ) -> Task<Result<Entity<Worktree>>> {
4065        self.worktree_store.update(cx, |worktree_store, cx| {
4066            worktree_store.create_worktree(abs_path, visible, cx)
4067        })
4068    }
4069
4070    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4071        self.worktree_store.update(cx, |worktree_store, cx| {
4072            worktree_store.remove_worktree(id_to_remove, cx);
4073        });
4074    }
4075
4076    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4077        self.worktree_store.update(cx, |worktree_store, cx| {
4078            worktree_store.add(worktree, cx);
4079        });
4080    }
4081
4082    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4083        let new_active_entry = entry.and_then(|project_path| {
4084            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4085            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
4086            Some(entry.id)
4087        });
4088        if new_active_entry != self.active_entry {
4089            self.active_entry = new_active_entry;
4090            self.lsp_store.update(cx, |lsp_store, _| {
4091                lsp_store.set_active_entry(new_active_entry);
4092            });
4093            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4094        }
4095    }
4096
4097    pub fn language_servers_running_disk_based_diagnostics<'a>(
4098        &'a self,
4099        cx: &'a App,
4100    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4101        self.lsp_store
4102            .read(cx)
4103            .language_servers_running_disk_based_diagnostics()
4104    }
4105
4106    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4107        self.lsp_store
4108            .read(cx)
4109            .diagnostic_summary(include_ignored, cx)
4110    }
4111
4112    pub fn diagnostic_summaries<'a>(
4113        &'a self,
4114        include_ignored: bool,
4115        cx: &'a App,
4116    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4117        self.lsp_store
4118            .read(cx)
4119            .diagnostic_summaries(include_ignored, cx)
4120    }
4121
4122    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4123        self.active_entry
4124    }
4125
4126    pub fn entry_for_path(&self, path: &ProjectPath, cx: &App) -> Option<Entry> {
4127        self.worktree_store.read(cx).entry_for_path(path, cx)
4128    }
4129
4130    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4131        let worktree = self.worktree_for_entry(entry_id, cx)?;
4132        let worktree = worktree.read(cx);
4133        let worktree_id = worktree.id();
4134        let path = worktree.entry_for_id(entry_id)?.path.clone();
4135        Some(ProjectPath { worktree_id, path })
4136    }
4137
4138    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4139        self.worktree_for_id(project_path.worktree_id, cx)?
4140            .read(cx)
4141            .absolutize(&project_path.path)
4142            .ok()
4143    }
4144
4145    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4146    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4147    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4148    /// the first visible worktree that has an entry for that relative path.
4149    ///
4150    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4151    /// root name from paths.
4152    ///
4153    /// # Arguments
4154    ///
4155    /// * `path` - A full path that starts with a worktree root name, or alternatively a
4156    ///            relative path within a visible worktree.
4157    /// * `cx` - A reference to the `AppContext`.
4158    ///
4159    /// # Returns
4160    ///
4161    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4162    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4163        let path = path.as_ref();
4164        let worktree_store = self.worktree_store.read(cx);
4165
4166        for worktree in worktree_store.visible_worktrees(cx) {
4167            let worktree_root_name = worktree.read(cx).root_name();
4168            if let Ok(relative_path) = path.strip_prefix(worktree_root_name) {
4169                return Some(ProjectPath {
4170                    worktree_id: worktree.read(cx).id(),
4171                    path: relative_path.into(),
4172                });
4173            }
4174        }
4175
4176        for worktree in worktree_store.visible_worktrees(cx) {
4177            let worktree = worktree.read(cx);
4178            if let Some(entry) = worktree.entry_for_path(path) {
4179                return Some(ProjectPath {
4180                    worktree_id: worktree.id(),
4181                    path: entry.path.clone(),
4182                });
4183            }
4184        }
4185
4186        None
4187    }
4188
4189    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4190        self.find_worktree(abs_path, cx)
4191            .map(|(worktree, relative_path)| ProjectPath {
4192                worktree_id: worktree.read(cx).id(),
4193                path: relative_path.into(),
4194            })
4195    }
4196
4197    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4198        Some(
4199            self.worktree_for_id(project_path.worktree_id, cx)?
4200                .read(cx)
4201                .abs_path()
4202                .to_path_buf(),
4203        )
4204    }
4205
4206    pub fn blame_buffer(
4207        &self,
4208        buffer: &Entity<Buffer>,
4209        version: Option<clock::Global>,
4210        cx: &mut App,
4211    ) -> Task<Result<Option<Blame>>> {
4212        self.git_store.update(cx, |git_store, cx| {
4213            git_store.blame_buffer(buffer, version, cx)
4214        })
4215    }
4216
4217    pub fn get_permalink_to_line(
4218        &self,
4219        buffer: &Entity<Buffer>,
4220        selection: Range<u32>,
4221        cx: &mut App,
4222    ) -> Task<Result<url::Url>> {
4223        self.git_store.update(cx, |git_store, cx| {
4224            git_store.get_permalink_to_line(buffer, selection, cx)
4225        })
4226    }
4227
4228    // RPC message handlers
4229
4230    async fn handle_unshare_project(
4231        this: Entity<Self>,
4232        _: TypedEnvelope<proto::UnshareProject>,
4233        mut cx: AsyncApp,
4234    ) -> Result<()> {
4235        this.update(&mut cx, |this, cx| {
4236            if this.is_local() || this.is_via_ssh() {
4237                this.unshare(cx)?;
4238            } else {
4239                this.disconnected_from_host(cx);
4240            }
4241            Ok(())
4242        })?
4243    }
4244
4245    async fn handle_add_collaborator(
4246        this: Entity<Self>,
4247        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4248        mut cx: AsyncApp,
4249    ) -> Result<()> {
4250        let collaborator = envelope
4251            .payload
4252            .collaborator
4253            .take()
4254            .ok_or_else(|| anyhow!("empty collaborator"))?;
4255
4256        let collaborator = Collaborator::from_proto(collaborator)?;
4257        this.update(&mut cx, |this, cx| {
4258            this.buffer_store.update(cx, |buffer_store, _| {
4259                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4260            });
4261            this.breakpoint_store.read(cx).broadcast();
4262            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4263            this.collaborators
4264                .insert(collaborator.peer_id, collaborator);
4265        })?;
4266
4267        Ok(())
4268    }
4269
4270    async fn handle_update_project_collaborator(
4271        this: Entity<Self>,
4272        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4273        mut cx: AsyncApp,
4274    ) -> Result<()> {
4275        let old_peer_id = envelope
4276            .payload
4277            .old_peer_id
4278            .ok_or_else(|| anyhow!("missing old peer id"))?;
4279        let new_peer_id = envelope
4280            .payload
4281            .new_peer_id
4282            .ok_or_else(|| anyhow!("missing new peer id"))?;
4283        this.update(&mut cx, |this, cx| {
4284            let collaborator = this
4285                .collaborators
4286                .remove(&old_peer_id)
4287                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
4288            let is_host = collaborator.is_host;
4289            this.collaborators.insert(new_peer_id, collaborator);
4290
4291            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4292            this.buffer_store.update(cx, |buffer_store, _| {
4293                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4294            });
4295
4296            if is_host {
4297                this.buffer_store
4298                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4299                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4300                    .unwrap();
4301                cx.emit(Event::HostReshared);
4302            }
4303
4304            cx.emit(Event::CollaboratorUpdated {
4305                old_peer_id,
4306                new_peer_id,
4307            });
4308            Ok(())
4309        })?
4310    }
4311
4312    async fn handle_remove_collaborator(
4313        this: Entity<Self>,
4314        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4315        mut cx: AsyncApp,
4316    ) -> Result<()> {
4317        this.update(&mut cx, |this, cx| {
4318            let peer_id = envelope
4319                .payload
4320                .peer_id
4321                .ok_or_else(|| anyhow!("invalid peer id"))?;
4322            let replica_id = this
4323                .collaborators
4324                .remove(&peer_id)
4325                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
4326                .replica_id;
4327            this.buffer_store.update(cx, |buffer_store, cx| {
4328                buffer_store.forget_shared_buffers_for(&peer_id);
4329                for buffer in buffer_store.buffers() {
4330                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4331                }
4332            });
4333            this.git_store.update(cx, |git_store, _| {
4334                git_store.forget_shared_diffs_for(&peer_id);
4335            });
4336
4337            cx.emit(Event::CollaboratorLeft(peer_id));
4338            Ok(())
4339        })?
4340    }
4341
4342    async fn handle_update_project(
4343        this: Entity<Self>,
4344        envelope: TypedEnvelope<proto::UpdateProject>,
4345        mut cx: AsyncApp,
4346    ) -> Result<()> {
4347        this.update(&mut cx, |this, cx| {
4348            // Don't handle messages that were sent before the response to us joining the project
4349            if envelope.message_id > this.join_project_response_message_id {
4350                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4351            }
4352            Ok(())
4353        })?
4354    }
4355
4356    async fn handle_toast(
4357        this: Entity<Self>,
4358        envelope: TypedEnvelope<proto::Toast>,
4359        mut cx: AsyncApp,
4360    ) -> Result<()> {
4361        this.update(&mut cx, |_, cx| {
4362            cx.emit(Event::Toast {
4363                notification_id: envelope.payload.notification_id.into(),
4364                message: envelope.payload.message,
4365            });
4366            Ok(())
4367        })?
4368    }
4369
4370    async fn handle_language_server_prompt_request(
4371        this: Entity<Self>,
4372        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4373        mut cx: AsyncApp,
4374    ) -> Result<proto::LanguageServerPromptResponse> {
4375        let (tx, mut rx) = smol::channel::bounded(1);
4376        let actions: Vec<_> = envelope
4377            .payload
4378            .actions
4379            .into_iter()
4380            .map(|action| MessageActionItem {
4381                title: action,
4382                properties: Default::default(),
4383            })
4384            .collect();
4385        this.update(&mut cx, |_, cx| {
4386            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4387                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4388                message: envelope.payload.message,
4389                actions: actions.clone(),
4390                lsp_name: envelope.payload.lsp_name,
4391                response_channel: tx,
4392            }));
4393
4394            anyhow::Ok(())
4395        })??;
4396
4397        // We drop `this` to avoid holding a reference in this future for too
4398        // long.
4399        // If we keep the reference, we might not drop the `Project` early
4400        // enough when closing a window and it will only get releases on the
4401        // next `flush_effects()` call.
4402        drop(this);
4403
4404        let mut rx = pin!(rx);
4405        let answer = rx.next().await;
4406
4407        Ok(LanguageServerPromptResponse {
4408            action_response: answer.and_then(|answer| {
4409                actions
4410                    .iter()
4411                    .position(|action| *action == answer)
4412                    .map(|index| index as u64)
4413            }),
4414        })
4415    }
4416
4417    async fn handle_hide_toast(
4418        this: Entity<Self>,
4419        envelope: TypedEnvelope<proto::HideToast>,
4420        mut cx: AsyncApp,
4421    ) -> Result<()> {
4422        this.update(&mut cx, |_, cx| {
4423            cx.emit(Event::HideToast {
4424                notification_id: envelope.payload.notification_id.into(),
4425            });
4426            Ok(())
4427        })?
4428    }
4429
4430    // Collab sends UpdateWorktree protos as messages
4431    async fn handle_update_worktree(
4432        this: Entity<Self>,
4433        envelope: TypedEnvelope<proto::UpdateWorktree>,
4434        mut cx: AsyncApp,
4435    ) -> Result<()> {
4436        this.update(&mut cx, |this, cx| {
4437            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4438            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4439                worktree.update(cx, |worktree, _| {
4440                    let worktree = worktree.as_remote_mut().unwrap();
4441                    worktree.update_from_remote(envelope.payload);
4442                });
4443            }
4444            Ok(())
4445        })?
4446    }
4447
4448    async fn handle_update_buffer_from_ssh(
4449        this: Entity<Self>,
4450        envelope: TypedEnvelope<proto::UpdateBuffer>,
4451        cx: AsyncApp,
4452    ) -> Result<proto::Ack> {
4453        let buffer_store = this.read_with(&cx, |this, cx| {
4454            if let Some(remote_id) = this.remote_id() {
4455                let mut payload = envelope.payload.clone();
4456                payload.project_id = remote_id;
4457                cx.background_spawn(this.client.request(payload))
4458                    .detach_and_log_err(cx);
4459            }
4460            this.buffer_store.clone()
4461        })?;
4462        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4463    }
4464
4465    async fn handle_update_buffer(
4466        this: Entity<Self>,
4467        envelope: TypedEnvelope<proto::UpdateBuffer>,
4468        cx: AsyncApp,
4469    ) -> Result<proto::Ack> {
4470        let buffer_store = this.read_with(&cx, |this, cx| {
4471            if let Some(ssh) = &this.ssh_client {
4472                let mut payload = envelope.payload.clone();
4473                payload.project_id = SSH_PROJECT_ID;
4474                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4475                    .detach_and_log_err(cx);
4476            }
4477            this.buffer_store.clone()
4478        })?;
4479        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4480    }
4481
4482    fn retain_remotely_created_models(
4483        &mut self,
4484        cx: &mut Context<Self>,
4485    ) -> RemotelyCreatedModelGuard {
4486        {
4487            let mut remotely_create_models = self.remotely_created_models.lock();
4488            if remotely_create_models.retain_count == 0 {
4489                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4490                remotely_create_models.worktrees =
4491                    self.worktree_store.read(cx).worktrees().collect();
4492            }
4493            remotely_create_models.retain_count += 1;
4494        }
4495        RemotelyCreatedModelGuard {
4496            remote_models: Arc::downgrade(&self.remotely_created_models),
4497        }
4498    }
4499
4500    async fn handle_create_buffer_for_peer(
4501        this: Entity<Self>,
4502        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4503        mut cx: AsyncApp,
4504    ) -> Result<()> {
4505        this.update(&mut cx, |this, cx| {
4506            this.buffer_store.update(cx, |buffer_store, cx| {
4507                buffer_store.handle_create_buffer_for_peer(
4508                    envelope,
4509                    this.replica_id(),
4510                    this.capability(),
4511                    cx,
4512                )
4513            })
4514        })?
4515    }
4516
4517    async fn handle_synchronize_buffers(
4518        this: Entity<Self>,
4519        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4520        mut cx: AsyncApp,
4521    ) -> Result<proto::SynchronizeBuffersResponse> {
4522        let response = this.update(&mut cx, |this, cx| {
4523            let client = this.client.clone();
4524            this.buffer_store.update(cx, |this, cx| {
4525                this.handle_synchronize_buffers(envelope, cx, client)
4526            })
4527        })??;
4528
4529        Ok(response)
4530    }
4531
4532    async fn handle_search_candidate_buffers(
4533        this: Entity<Self>,
4534        envelope: TypedEnvelope<proto::FindSearchCandidates>,
4535        mut cx: AsyncApp,
4536    ) -> Result<proto::FindSearchCandidatesResponse> {
4537        let peer_id = envelope.original_sender_id()?;
4538        let message = envelope.payload;
4539        let query = SearchQuery::from_proto(
4540            message
4541                .query
4542                .ok_or_else(|| anyhow!("missing query field"))?,
4543        )?;
4544        let results = this.update(&mut cx, |this, cx| {
4545            this.find_search_candidate_buffers(&query, message.limit as _, cx)
4546        })?;
4547
4548        let mut response = proto::FindSearchCandidatesResponse {
4549            buffer_ids: Vec::new(),
4550        };
4551
4552        while let Ok(buffer) = results.recv().await {
4553            this.update(&mut cx, |this, cx| {
4554                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4555                response.buffer_ids.push(buffer_id.to_proto());
4556            })?;
4557        }
4558
4559        Ok(response)
4560    }
4561
4562    async fn handle_open_buffer_by_id(
4563        this: Entity<Self>,
4564        envelope: TypedEnvelope<proto::OpenBufferById>,
4565        mut cx: AsyncApp,
4566    ) -> Result<proto::OpenBufferResponse> {
4567        let peer_id = envelope.original_sender_id()?;
4568        let buffer_id = BufferId::new(envelope.payload.id)?;
4569        let buffer = this
4570            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4571            .await?;
4572        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4573    }
4574
4575    async fn handle_open_buffer_by_path(
4576        this: Entity<Self>,
4577        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4578        mut cx: AsyncApp,
4579    ) -> Result<proto::OpenBufferResponse> {
4580        let peer_id = envelope.original_sender_id()?;
4581        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4582        let open_buffer = this.update(&mut cx, |this, cx| {
4583            this.open_buffer(
4584                ProjectPath {
4585                    worktree_id,
4586                    path: Arc::<Path>::from_proto(envelope.payload.path),
4587                },
4588                cx,
4589            )
4590        })?;
4591
4592        let buffer = open_buffer.await?;
4593        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4594    }
4595
4596    async fn handle_open_new_buffer(
4597        this: Entity<Self>,
4598        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4599        mut cx: AsyncApp,
4600    ) -> Result<proto::OpenBufferResponse> {
4601        let buffer = this
4602            .update(&mut cx, |this, cx| this.create_buffer(cx))?
4603            .await?;
4604        let peer_id = envelope.original_sender_id()?;
4605
4606        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4607    }
4608
4609    fn respond_to_open_buffer_request(
4610        this: Entity<Self>,
4611        buffer: Entity<Buffer>,
4612        peer_id: proto::PeerId,
4613        cx: &mut AsyncApp,
4614    ) -> Result<proto::OpenBufferResponse> {
4615        this.update(cx, |this, cx| {
4616            let is_private = buffer
4617                .read(cx)
4618                .file()
4619                .map(|f| f.is_private())
4620                .unwrap_or_default();
4621            if is_private {
4622                Err(anyhow!(ErrorCode::UnsharedItem))
4623            } else {
4624                Ok(proto::OpenBufferResponse {
4625                    buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4626                })
4627            }
4628        })?
4629    }
4630
4631    fn create_buffer_for_peer(
4632        &mut self,
4633        buffer: &Entity<Buffer>,
4634        peer_id: proto::PeerId,
4635        cx: &mut App,
4636    ) -> BufferId {
4637        self.buffer_store
4638            .update(cx, |buffer_store, cx| {
4639                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4640            })
4641            .detach_and_log_err(cx);
4642        buffer.read(cx).remote_id()
4643    }
4644
4645    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4646        let project_id = match self.client_state {
4647            ProjectClientState::Remote {
4648                sharing_has_stopped,
4649                remote_id,
4650                ..
4651            } => {
4652                if sharing_has_stopped {
4653                    return Task::ready(Err(anyhow!(
4654                        "can't synchronize remote buffers on a readonly project"
4655                    )));
4656                } else {
4657                    remote_id
4658                }
4659            }
4660            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4661                return Task::ready(Err(anyhow!(
4662                    "can't synchronize remote buffers on a local project"
4663                )));
4664            }
4665        };
4666
4667        let client = self.client.clone();
4668        cx.spawn(async move |this, cx| {
4669            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4670                this.buffer_store.read(cx).buffer_version_info(cx)
4671            })?;
4672            let response = client
4673                .request(proto::SynchronizeBuffers {
4674                    project_id,
4675                    buffers,
4676                })
4677                .await?;
4678
4679            let send_updates_for_buffers = this.update(cx, |this, cx| {
4680                response
4681                    .buffers
4682                    .into_iter()
4683                    .map(|buffer| {
4684                        let client = client.clone();
4685                        let buffer_id = match BufferId::new(buffer.id) {
4686                            Ok(id) => id,
4687                            Err(e) => {
4688                                return Task::ready(Err(e));
4689                            }
4690                        };
4691                        let remote_version = language::proto::deserialize_version(&buffer.version);
4692                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
4693                            let operations =
4694                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
4695                            cx.background_spawn(async move {
4696                                let operations = operations.await;
4697                                for chunk in split_operations(operations) {
4698                                    client
4699                                        .request(proto::UpdateBuffer {
4700                                            project_id,
4701                                            buffer_id: buffer_id.into(),
4702                                            operations: chunk,
4703                                        })
4704                                        .await?;
4705                                }
4706                                anyhow::Ok(())
4707                            })
4708                        } else {
4709                            Task::ready(Ok(()))
4710                        }
4711                    })
4712                    .collect::<Vec<_>>()
4713            })?;
4714
4715            // Any incomplete buffers have open requests waiting. Request that the host sends
4716            // creates these buffers for us again to unblock any waiting futures.
4717            for id in incomplete_buffer_ids {
4718                cx.background_spawn(client.request(proto::OpenBufferById {
4719                    project_id,
4720                    id: id.into(),
4721                }))
4722                .detach();
4723            }
4724
4725            futures::future::join_all(send_updates_for_buffers)
4726                .await
4727                .into_iter()
4728                .collect()
4729        })
4730    }
4731
4732    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
4733        self.worktree_store.read(cx).worktree_metadata_protos(cx)
4734    }
4735
4736    /// Iterator of all open buffers that have unsaved changes
4737    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
4738        self.buffer_store.read(cx).buffers().filter_map(|buf| {
4739            let buf = buf.read(cx);
4740            if buf.is_dirty() {
4741                buf.project_path(cx)
4742            } else {
4743                None
4744            }
4745        })
4746    }
4747
4748    fn set_worktrees_from_proto(
4749        &mut self,
4750        worktrees: Vec<proto::WorktreeMetadata>,
4751        cx: &mut Context<Project>,
4752    ) -> Result<()> {
4753        self.worktree_store.update(cx, |worktree_store, cx| {
4754            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
4755        })
4756    }
4757
4758    fn set_collaborators_from_proto(
4759        &mut self,
4760        messages: Vec<proto::Collaborator>,
4761        cx: &mut Context<Self>,
4762    ) -> Result<()> {
4763        let mut collaborators = HashMap::default();
4764        for message in messages {
4765            let collaborator = Collaborator::from_proto(message)?;
4766            collaborators.insert(collaborator.peer_id, collaborator);
4767        }
4768        for old_peer_id in self.collaborators.keys() {
4769            if !collaborators.contains_key(old_peer_id) {
4770                cx.emit(Event::CollaboratorLeft(*old_peer_id));
4771            }
4772        }
4773        self.collaborators = collaborators;
4774        Ok(())
4775    }
4776
4777    pub fn supplementary_language_servers<'a>(
4778        &'a self,
4779        cx: &'a App,
4780    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
4781        self.lsp_store.read(cx).supplementary_language_servers()
4782    }
4783
4784    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
4785        self.lsp_store.update(cx, |this, cx| {
4786            this.language_servers_for_local_buffer(buffer, cx)
4787                .any(
4788                    |(_, server)| match server.capabilities().inlay_hint_provider {
4789                        Some(lsp::OneOf::Left(enabled)) => enabled,
4790                        Some(lsp::OneOf::Right(_)) => true,
4791                        None => false,
4792                    },
4793                )
4794        })
4795    }
4796
4797    pub fn language_server_id_for_name(
4798        &self,
4799        buffer: &Buffer,
4800        name: &str,
4801        cx: &mut App,
4802    ) -> Task<Option<LanguageServerId>> {
4803        if self.is_local() {
4804            Task::ready(self.lsp_store.update(cx, |lsp_store, cx| {
4805                lsp_store
4806                    .language_servers_for_local_buffer(buffer, cx)
4807                    .find_map(|(adapter, server)| {
4808                        if adapter.name.0 == name {
4809                            Some(server.server_id())
4810                        } else {
4811                            None
4812                        }
4813                    })
4814            }))
4815        } else if let Some(project_id) = self.remote_id() {
4816            let request = self.client.request(proto::LanguageServerIdForName {
4817                project_id,
4818                buffer_id: buffer.remote_id().to_proto(),
4819                name: name.to_string(),
4820            });
4821            cx.background_spawn(async move {
4822                let response = request.await.log_err()?;
4823                response.server_id.map(LanguageServerId::from_proto)
4824            })
4825        } else if let Some(ssh_client) = self.ssh_client.as_ref() {
4826            let request =
4827                ssh_client
4828                    .read(cx)
4829                    .proto_client()
4830                    .request(proto::LanguageServerIdForName {
4831                        project_id: SSH_PROJECT_ID,
4832                        buffer_id: buffer.remote_id().to_proto(),
4833                        name: name.to_string(),
4834                    });
4835            cx.background_spawn(async move {
4836                let response = request.await.log_err()?;
4837                response.server_id.map(LanguageServerId::from_proto)
4838            })
4839        } else {
4840            Task::ready(None)
4841        }
4842    }
4843
4844    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
4845        self.lsp_store.update(cx, |this, cx| {
4846            this.language_servers_for_local_buffer(buffer, cx)
4847                .next()
4848                .is_some()
4849        })
4850    }
4851
4852    pub fn git_init(
4853        &self,
4854        path: Arc<Path>,
4855        fallback_branch_name: String,
4856        cx: &App,
4857    ) -> Task<Result<()>> {
4858        self.git_store
4859            .read(cx)
4860            .git_init(path, fallback_branch_name, cx)
4861    }
4862
4863    pub fn buffer_store(&self) -> &Entity<BufferStore> {
4864        &self.buffer_store
4865    }
4866
4867    pub fn git_store(&self) -> &Entity<GitStore> {
4868        &self.git_store
4869    }
4870
4871    #[cfg(test)]
4872    fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
4873        cx.spawn(async move |this, cx| {
4874            let scans_complete = this
4875                .read_with(cx, |this, cx| {
4876                    this.worktrees(cx)
4877                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
4878                        .collect::<Vec<_>>()
4879                })
4880                .unwrap();
4881            join_all(scans_complete).await;
4882            let barriers = this
4883                .update(cx, |this, cx| {
4884                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
4885                    repos
4886                        .into_iter()
4887                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
4888                        .collect::<Vec<_>>()
4889                })
4890                .unwrap();
4891            join_all(barriers).await;
4892        })
4893    }
4894
4895    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
4896        self.git_store.read(cx).active_repository()
4897    }
4898
4899    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
4900        self.git_store.read(cx).repositories()
4901    }
4902
4903    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
4904        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
4905    }
4906
4907    pub fn set_agent_location(
4908        &mut self,
4909        new_location: Option<AgentLocation>,
4910        cx: &mut Context<Self>,
4911    ) {
4912        if let Some(old_location) = self.agent_location.as_ref() {
4913            old_location
4914                .buffer
4915                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
4916                .ok();
4917        }
4918
4919        if let Some(location) = new_location.as_ref() {
4920            location
4921                .buffer
4922                .update(cx, |buffer, cx| {
4923                    buffer.set_agent_selections(
4924                        Arc::from([language::Selection {
4925                            id: 0,
4926                            start: location.position,
4927                            end: location.position,
4928                            reversed: false,
4929                            goal: language::SelectionGoal::None,
4930                        }]),
4931                        false,
4932                        CursorShape::Hollow,
4933                        cx,
4934                    )
4935                })
4936                .ok();
4937        }
4938
4939        self.agent_location = new_location;
4940        cx.emit(Event::AgentLocationChanged);
4941    }
4942
4943    pub fn agent_location(&self) -> Option<AgentLocation> {
4944        self.agent_location.clone()
4945    }
4946}
4947
4948pub struct PathMatchCandidateSet {
4949    pub snapshot: Snapshot,
4950    pub include_ignored: bool,
4951    pub include_root_name: bool,
4952    pub candidates: Candidates,
4953}
4954
4955pub enum Candidates {
4956    /// Only consider directories.
4957    Directories,
4958    /// Only consider files.
4959    Files,
4960    /// Consider directories and files.
4961    Entries,
4962}
4963
4964impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
4965    type Candidates = PathMatchCandidateSetIter<'a>;
4966
4967    fn id(&self) -> usize {
4968        self.snapshot.id().to_usize()
4969    }
4970
4971    fn len(&self) -> usize {
4972        match self.candidates {
4973            Candidates::Files => {
4974                if self.include_ignored {
4975                    self.snapshot.file_count()
4976                } else {
4977                    self.snapshot.visible_file_count()
4978                }
4979            }
4980
4981            Candidates::Directories => {
4982                if self.include_ignored {
4983                    self.snapshot.dir_count()
4984                } else {
4985                    self.snapshot.visible_dir_count()
4986                }
4987            }
4988
4989            Candidates::Entries => {
4990                if self.include_ignored {
4991                    self.snapshot.entry_count()
4992                } else {
4993                    self.snapshot.visible_entry_count()
4994                }
4995            }
4996        }
4997    }
4998
4999    fn prefix(&self) -> Arc<str> {
5000        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
5001            self.snapshot.root_name().into()
5002        } else if self.include_root_name {
5003            format!("{}{}", self.snapshot.root_name(), std::path::MAIN_SEPARATOR).into()
5004        } else {
5005            Arc::default()
5006        }
5007    }
5008
5009    fn candidates(&'a self, start: usize) -> Self::Candidates {
5010        PathMatchCandidateSetIter {
5011            traversal: match self.candidates {
5012                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5013                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5014                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5015            },
5016        }
5017    }
5018}
5019
5020pub struct PathMatchCandidateSetIter<'a> {
5021    traversal: Traversal<'a>,
5022}
5023
5024impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5025    type Item = fuzzy::PathMatchCandidate<'a>;
5026
5027    fn next(&mut self) -> Option<Self::Item> {
5028        self.traversal
5029            .next()
5030            .map(|entry| fuzzy::PathMatchCandidate {
5031                is_dir: entry.kind.is_dir(),
5032                path: &entry.path,
5033                char_bag: entry.char_bag,
5034            })
5035    }
5036}
5037
5038impl EventEmitter<Event> for Project {}
5039
5040impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5041    fn from(val: &'a ProjectPath) -> Self {
5042        SettingsLocation {
5043            worktree_id: val.worktree_id,
5044            path: val.path.as_ref(),
5045        }
5046    }
5047}
5048
5049impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
5050    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5051        Self {
5052            worktree_id,
5053            path: path.as_ref().into(),
5054        }
5055    }
5056}
5057
5058pub fn relativize_path(base: &Path, path: &Path) -> PathBuf {
5059    let mut path_components = path.components();
5060    let mut base_components = base.components();
5061    let mut components: Vec<Component> = Vec::new();
5062    loop {
5063        match (path_components.next(), base_components.next()) {
5064            (None, None) => break,
5065            (Some(a), None) => {
5066                components.push(a);
5067                components.extend(path_components.by_ref());
5068                break;
5069            }
5070            (None, _) => components.push(Component::ParentDir),
5071            (Some(a), Some(b)) if components.is_empty() && a == b => (),
5072            (Some(a), Some(Component::CurDir)) => components.push(a),
5073            (Some(a), Some(_)) => {
5074                components.push(Component::ParentDir);
5075                for _ in base_components {
5076                    components.push(Component::ParentDir);
5077                }
5078                components.push(a);
5079                components.extend(path_components.by_ref());
5080                break;
5081            }
5082        }
5083    }
5084    components.iter().map(|c| c.as_os_str()).collect()
5085}
5086
5087fn resolve_path(base: &Path, path: &Path) -> PathBuf {
5088    let mut result = base.to_path_buf();
5089    for component in path.components() {
5090        match component {
5091            Component::ParentDir => {
5092                result.pop();
5093            }
5094            Component::CurDir => (),
5095            _ => result.push(component),
5096        }
5097    }
5098    result
5099}
5100
5101/// ResolvedPath is a path that has been resolved to either a ProjectPath
5102/// or an AbsPath and that *exists*.
5103#[derive(Debug, Clone)]
5104pub enum ResolvedPath {
5105    ProjectPath {
5106        project_path: ProjectPath,
5107        is_dir: bool,
5108    },
5109    AbsPath {
5110        path: PathBuf,
5111        is_dir: bool,
5112    },
5113}
5114
5115impl ResolvedPath {
5116    pub fn abs_path(&self) -> Option<&Path> {
5117        match self {
5118            Self::AbsPath { path, .. } => Some(path.as_path()),
5119            _ => None,
5120        }
5121    }
5122
5123    pub fn into_abs_path(self) -> Option<PathBuf> {
5124        match self {
5125            Self::AbsPath { path, .. } => Some(path),
5126            _ => None,
5127        }
5128    }
5129
5130    pub fn project_path(&self) -> Option<&ProjectPath> {
5131        match self {
5132            Self::ProjectPath { project_path, .. } => Some(&project_path),
5133            _ => None,
5134        }
5135    }
5136
5137    pub fn is_file(&self) -> bool {
5138        !self.is_dir()
5139    }
5140
5141    pub fn is_dir(&self) -> bool {
5142        match self {
5143            Self::ProjectPath { is_dir, .. } => *is_dir,
5144            Self::AbsPath { is_dir, .. } => *is_dir,
5145        }
5146    }
5147}
5148
5149impl ProjectItem for Buffer {
5150    fn try_open(
5151        project: &Entity<Project>,
5152        path: &ProjectPath,
5153        cx: &mut App,
5154    ) -> Option<Task<Result<Entity<Self>>>> {
5155        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5156    }
5157
5158    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId> {
5159        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
5160    }
5161
5162    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5163        self.file().map(|file| ProjectPath {
5164            worktree_id: file.worktree_id(cx),
5165            path: file.path().clone(),
5166        })
5167    }
5168
5169    fn is_dirty(&self) -> bool {
5170        self.is_dirty()
5171    }
5172}
5173
5174impl Completion {
5175    /// A key that can be used to sort completions when displaying
5176    /// them to the user.
5177    pub fn sort_key(&self) -> (usize, &str) {
5178        const DEFAULT_KIND_KEY: usize = 3;
5179        let kind_key = self
5180            .source
5181            // `lsp::CompletionListItemDefaults` has no `kind` field
5182            .lsp_completion(false)
5183            .and_then(|lsp_completion| lsp_completion.kind)
5184            .and_then(|lsp_completion_kind| match lsp_completion_kind {
5185                lsp::CompletionItemKind::KEYWORD => Some(0),
5186                lsp::CompletionItemKind::VARIABLE => Some(1),
5187                lsp::CompletionItemKind::CONSTANT => Some(2),
5188                _ => None,
5189            })
5190            .unwrap_or(DEFAULT_KIND_KEY);
5191        (kind_key, &self.label.text[self.label.filter_range.clone()])
5192    }
5193
5194    /// Whether this completion is a snippet.
5195    pub fn is_snippet(&self) -> bool {
5196        self.source
5197            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5198            .lsp_completion(true)
5199            .map_or(false, |lsp_completion| {
5200                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5201            })
5202    }
5203
5204    /// Returns the corresponding color for this completion.
5205    ///
5206    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5207    pub fn color(&self) -> Option<Hsla> {
5208        // `lsp::CompletionListItemDefaults` has no `kind` field
5209        let lsp_completion = self.source.lsp_completion(false)?;
5210        if lsp_completion.kind? == CompletionItemKind::COLOR {
5211            return color_extractor::extract_color(&lsp_completion);
5212        }
5213        None
5214    }
5215}
5216
5217pub fn sort_worktree_entries(entries: &mut [impl AsRef<Entry>]) {
5218    entries.sort_by(|entry_a, entry_b| {
5219        let entry_a = entry_a.as_ref();
5220        let entry_b = entry_b.as_ref();
5221        compare_paths(
5222            (&entry_a.path, entry_a.is_file()),
5223            (&entry_b.path, entry_b.is_file()),
5224        )
5225    });
5226}
5227
5228fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5229    match level {
5230        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5231        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5232        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5233    }
5234}