project.rs

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