project.rs

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