project.rs

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