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