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