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