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