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