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