project.rs

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