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_candidates_remote(
4028        &mut self,
4029        query: &SearchQuery,
4030        limit: usize,
4031        cx: &mut Context<Project>,
4032    ) -> Receiver<Entity<Buffer>> {
4033        let (tx, rx) = smol::channel::unbounded();
4034
4035        let (client, remote_id): (AnyProtoClient, _) = if let Some(ssh_client) = &self.remote_client
4036        {
4037            (ssh_client.read(cx).proto_client(), 0)
4038        } else if let Some(remote_id) = self.remote_id() {
4039            (self.collab_client.clone().into(), remote_id)
4040        } else {
4041            return rx;
4042        };
4043
4044        let request = client.request(proto::FindSearchCandidates {
4045            project_id: remote_id,
4046            query: Some(query.to_proto()),
4047            limit: limit as _,
4048        });
4049        let guard = self.retain_remotely_created_models(cx);
4050
4051        cx.spawn(async move |project, cx| {
4052            let response = request.await?;
4053            for buffer_id in response.buffer_ids {
4054                let buffer_id = BufferId::new(buffer_id)?;
4055                let buffer = project
4056                    .update(cx, |project, cx| {
4057                        project.buffer_store.update(cx, |buffer_store, cx| {
4058                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
4059                        })
4060                    })?
4061                    .await?;
4062                let _ = tx.send(buffer).await;
4063            }
4064
4065            drop(guard);
4066            anyhow::Ok(())
4067        })
4068        .detach_and_log_err(cx);
4069        rx
4070    }
4071
4072    pub fn request_lsp<R: LspCommand>(
4073        &mut self,
4074        buffer_handle: Entity<Buffer>,
4075        server: LanguageServerToQuery,
4076        request: R,
4077        cx: &mut Context<Self>,
4078    ) -> Task<Result<R::Response>>
4079    where
4080        <R::LspRequest as lsp::request::Request>::Result: Send,
4081        <R::LspRequest as lsp::request::Request>::Params: Send,
4082    {
4083        let guard = self.retain_remotely_created_models(cx);
4084        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4085            lsp_store.request_lsp(buffer_handle, server, request, cx)
4086        });
4087        cx.background_spawn(async move {
4088            let result = task.await;
4089            drop(guard);
4090            result
4091        })
4092    }
4093
4094    /// Move a worktree to a new position in the worktree order.
4095    ///
4096    /// The worktree will moved to the opposite side of the destination worktree.
4097    ///
4098    /// # Example
4099    ///
4100    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4101    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4102    ///
4103    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4104    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4105    ///
4106    /// # Errors
4107    ///
4108    /// An error will be returned if the worktree or destination worktree are not found.
4109    pub fn move_worktree(
4110        &mut self,
4111        source: WorktreeId,
4112        destination: WorktreeId,
4113        cx: &mut Context<Self>,
4114    ) -> Result<()> {
4115        self.worktree_store.update(cx, |worktree_store, cx| {
4116            worktree_store.move_worktree(source, destination, cx)
4117        })
4118    }
4119
4120    pub fn find_or_create_worktree(
4121        &mut self,
4122        abs_path: impl AsRef<Path>,
4123        visible: bool,
4124        cx: &mut Context<Self>,
4125    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4126        self.worktree_store.update(cx, |worktree_store, cx| {
4127            worktree_store.find_or_create_worktree(abs_path, visible, cx)
4128        })
4129    }
4130
4131    pub fn find_worktree(
4132        &self,
4133        abs_path: &Path,
4134        cx: &App,
4135    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4136        self.worktree_store.read(cx).find_worktree(abs_path, cx)
4137    }
4138
4139    pub fn is_shared(&self) -> bool {
4140        match &self.client_state {
4141            ProjectClientState::Shared { .. } => true,
4142            ProjectClientState::Local => false,
4143            ProjectClientState::Remote { .. } => true,
4144        }
4145    }
4146
4147    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4148    pub fn resolve_path_in_buffer(
4149        &self,
4150        path: &str,
4151        buffer: &Entity<Buffer>,
4152        cx: &mut Context<Self>,
4153    ) -> Task<Option<ResolvedPath>> {
4154        if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4155            self.resolve_abs_path(path, cx)
4156        } else {
4157            self.resolve_path_in_worktrees(path, buffer, cx)
4158        }
4159    }
4160
4161    pub fn resolve_abs_file_path(
4162        &self,
4163        path: &str,
4164        cx: &mut Context<Self>,
4165    ) -> Task<Option<ResolvedPath>> {
4166        let resolve_task = self.resolve_abs_path(path, cx);
4167        cx.background_spawn(async move {
4168            let resolved_path = resolve_task.await;
4169            resolved_path.filter(|path| path.is_file())
4170        })
4171    }
4172
4173    pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4174        if self.is_local() {
4175            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4176            let fs = self.fs.clone();
4177            cx.background_spawn(async move {
4178                let metadata = fs.metadata(&expanded).await.ok().flatten();
4179
4180                metadata.map(|metadata| ResolvedPath::AbsPath {
4181                    path: expanded.to_string_lossy().into_owned(),
4182                    is_dir: metadata.is_dir,
4183                })
4184            })
4185        } else if let Some(ssh_client) = self.remote_client.as_ref() {
4186            let request = ssh_client
4187                .read(cx)
4188                .proto_client()
4189                .request(proto::GetPathMetadata {
4190                    project_id: REMOTE_SERVER_PROJECT_ID,
4191                    path: path.into(),
4192                });
4193            cx.background_spawn(async move {
4194                let response = request.await.log_err()?;
4195                if response.exists {
4196                    Some(ResolvedPath::AbsPath {
4197                        path: response.path,
4198                        is_dir: response.is_dir,
4199                    })
4200                } else {
4201                    None
4202                }
4203            })
4204        } else {
4205            Task::ready(None)
4206        }
4207    }
4208
4209    fn resolve_path_in_worktrees(
4210        &self,
4211        path: &str,
4212        buffer: &Entity<Buffer>,
4213        cx: &mut Context<Self>,
4214    ) -> Task<Option<ResolvedPath>> {
4215        let mut candidates = vec![];
4216        let path_style = self.path_style(cx);
4217        if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4218            candidates.push(path.into_arc());
4219        }
4220
4221        if let Some(file) = buffer.read(cx).file()
4222            && let Some(dir) = file.path().parent()
4223        {
4224            if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4225                && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4226            {
4227                candidates.push(joined.into_arc());
4228            }
4229        }
4230
4231        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4232        let worktrees_with_ids: Vec<_> = self
4233            .worktrees(cx)
4234            .map(|worktree| {
4235                let id = worktree.read(cx).id();
4236                (worktree, id)
4237            })
4238            .collect();
4239
4240        cx.spawn(async move |_, cx| {
4241            if let Some(buffer_worktree_id) = buffer_worktree_id
4242                && let Some((worktree, _)) = worktrees_with_ids
4243                    .iter()
4244                    .find(|(_, id)| *id == buffer_worktree_id)
4245            {
4246                for candidate in candidates.iter() {
4247                    if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4248                        return Some(path);
4249                    }
4250                }
4251            }
4252            for (worktree, id) in worktrees_with_ids {
4253                if Some(id) == buffer_worktree_id {
4254                    continue;
4255                }
4256                for candidate in candidates.iter() {
4257                    if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4258                        return Some(path);
4259                    }
4260                }
4261            }
4262            None
4263        })
4264    }
4265
4266    fn resolve_path_in_worktree(
4267        worktree: &Entity<Worktree>,
4268        path: &RelPath,
4269        cx: &mut AsyncApp,
4270    ) -> Option<ResolvedPath> {
4271        worktree
4272            .read_with(cx, |worktree, _| {
4273                worktree.entry_for_path(path).map(|entry| {
4274                    let project_path = ProjectPath {
4275                        worktree_id: worktree.id(),
4276                        path: entry.path.clone(),
4277                    };
4278                    ResolvedPath::ProjectPath {
4279                        project_path,
4280                        is_dir: entry.is_dir(),
4281                    }
4282                })
4283            })
4284            .ok()?
4285    }
4286
4287    pub fn list_directory(
4288        &self,
4289        query: String,
4290        cx: &mut Context<Self>,
4291    ) -> Task<Result<Vec<DirectoryItem>>> {
4292        if self.is_local() {
4293            DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4294        } else if let Some(session) = self.remote_client.as_ref() {
4295            let request = proto::ListRemoteDirectory {
4296                dev_server_id: REMOTE_SERVER_PROJECT_ID,
4297                path: query,
4298                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4299            };
4300
4301            let response = session.read(cx).proto_client().request(request);
4302            cx.background_spawn(async move {
4303                let proto::ListRemoteDirectoryResponse {
4304                    entries,
4305                    entry_info,
4306                } = response.await?;
4307                Ok(entries
4308                    .into_iter()
4309                    .zip(entry_info)
4310                    .map(|(entry, info)| DirectoryItem {
4311                        path: PathBuf::from(entry),
4312                        is_dir: info.is_dir,
4313                    })
4314                    .collect())
4315            })
4316        } else {
4317            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4318        }
4319    }
4320
4321    pub fn create_worktree(
4322        &mut self,
4323        abs_path: impl AsRef<Path>,
4324        visible: bool,
4325        cx: &mut Context<Self>,
4326    ) -> Task<Result<Entity<Worktree>>> {
4327        self.worktree_store.update(cx, |worktree_store, cx| {
4328            worktree_store.create_worktree(abs_path, visible, cx)
4329        })
4330    }
4331
4332    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4333        self.worktree_store.update(cx, |worktree_store, cx| {
4334            worktree_store.remove_worktree(id_to_remove, cx);
4335        });
4336    }
4337
4338    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4339        self.worktree_store.update(cx, |worktree_store, cx| {
4340            worktree_store.add(worktree, cx);
4341        });
4342    }
4343
4344    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4345        let new_active_entry = entry.and_then(|project_path| {
4346            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4347            let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4348            Some(entry.id)
4349        });
4350        if new_active_entry != self.active_entry {
4351            self.active_entry = new_active_entry;
4352            self.lsp_store.update(cx, |lsp_store, _| {
4353                lsp_store.set_active_entry(new_active_entry);
4354            });
4355            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4356        }
4357    }
4358
4359    pub fn language_servers_running_disk_based_diagnostics<'a>(
4360        &'a self,
4361        cx: &'a App,
4362    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4363        self.lsp_store
4364            .read(cx)
4365            .language_servers_running_disk_based_diagnostics()
4366    }
4367
4368    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4369        self.lsp_store
4370            .read(cx)
4371            .diagnostic_summary(include_ignored, cx)
4372    }
4373
4374    /// Returns a summary of the diagnostics for the provided project path only.
4375    pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4376        self.lsp_store
4377            .read(cx)
4378            .diagnostic_summary_for_path(path, cx)
4379    }
4380
4381    pub fn diagnostic_summaries<'a>(
4382        &'a self,
4383        include_ignored: bool,
4384        cx: &'a App,
4385    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4386        self.lsp_store
4387            .read(cx)
4388            .diagnostic_summaries(include_ignored, cx)
4389    }
4390
4391    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4392        self.active_entry
4393    }
4394
4395    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4396        self.worktree_store.read(cx).entry_for_path(path, cx)
4397    }
4398
4399    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4400        let worktree = self.worktree_for_entry(entry_id, cx)?;
4401        let worktree = worktree.read(cx);
4402        let worktree_id = worktree.id();
4403        let path = worktree.entry_for_id(entry_id)?.path.clone();
4404        Some(ProjectPath { worktree_id, path })
4405    }
4406
4407    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4408        Some(
4409            self.worktree_for_id(project_path.worktree_id, cx)?
4410                .read(cx)
4411                .absolutize(&project_path.path),
4412        )
4413    }
4414
4415    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4416    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4417    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4418    /// the first visible worktree that has an entry for that relative path.
4419    ///
4420    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4421    /// root name from paths.
4422    ///
4423    /// # Arguments
4424    ///
4425    /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4426    ///   relative path within a visible worktree.
4427    /// * `cx` - A reference to the `AppContext`.
4428    ///
4429    /// # Returns
4430    ///
4431    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4432    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4433        let path_style = self.path_style(cx);
4434        let path = path.as_ref();
4435        let worktree_store = self.worktree_store.read(cx);
4436
4437        if is_absolute(&path.to_string_lossy(), path_style) {
4438            for worktree in worktree_store.visible_worktrees(cx) {
4439                let worktree_abs_path = worktree.read(cx).abs_path();
4440
4441                if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4442                    && let Ok(path) = RelPath::new(relative_path, path_style)
4443                {
4444                    return Some(ProjectPath {
4445                        worktree_id: worktree.read(cx).id(),
4446                        path: path.into_arc(),
4447                    });
4448                }
4449            }
4450        } else {
4451            for worktree in worktree_store.visible_worktrees(cx) {
4452                let worktree_root_name = worktree.read(cx).root_name();
4453                if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4454                    && let Ok(path) = RelPath::new(relative_path, path_style)
4455                {
4456                    return Some(ProjectPath {
4457                        worktree_id: worktree.read(cx).id(),
4458                        path: path.into_arc(),
4459                    });
4460                }
4461            }
4462
4463            for worktree in worktree_store.visible_worktrees(cx) {
4464                let worktree = worktree.read(cx);
4465                if let Ok(path) = RelPath::new(path, path_style)
4466                    && let Some(entry) = worktree.entry_for_path(&path)
4467                {
4468                    return Some(ProjectPath {
4469                        worktree_id: worktree.id(),
4470                        path: entry.path.clone(),
4471                    });
4472                }
4473            }
4474        }
4475
4476        None
4477    }
4478
4479    /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4480    ///
4481    /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4482    pub fn short_full_path_for_project_path(
4483        &self,
4484        project_path: &ProjectPath,
4485        cx: &App,
4486    ) -> Option<String> {
4487        let path_style = self.path_style(cx);
4488        if self.visible_worktrees(cx).take(2).count() < 2 {
4489            return Some(project_path.path.display(path_style).to_string());
4490        }
4491        self.worktree_for_id(project_path.worktree_id, cx)
4492            .map(|worktree| {
4493                let worktree_name = worktree.read(cx).root_name();
4494                worktree_name
4495                    .join(&project_path.path)
4496                    .display(path_style)
4497                    .to_string()
4498            })
4499    }
4500
4501    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4502        self.find_worktree(abs_path, cx)
4503            .map(|(worktree, relative_path)| ProjectPath {
4504                worktree_id: worktree.read(cx).id(),
4505                path: relative_path,
4506            })
4507    }
4508
4509    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4510        Some(
4511            self.worktree_for_id(project_path.worktree_id, cx)?
4512                .read(cx)
4513                .abs_path()
4514                .to_path_buf(),
4515        )
4516    }
4517
4518    pub fn blame_buffer(
4519        &self,
4520        buffer: &Entity<Buffer>,
4521        version: Option<clock::Global>,
4522        cx: &mut App,
4523    ) -> Task<Result<Option<Blame>>> {
4524        self.git_store.update(cx, |git_store, cx| {
4525            git_store.blame_buffer(buffer, version, cx)
4526        })
4527    }
4528
4529    pub fn get_permalink_to_line(
4530        &self,
4531        buffer: &Entity<Buffer>,
4532        selection: Range<u32>,
4533        cx: &mut App,
4534    ) -> Task<Result<url::Url>> {
4535        self.git_store.update(cx, |git_store, cx| {
4536            git_store.get_permalink_to_line(buffer, selection, cx)
4537        })
4538    }
4539
4540    // RPC message handlers
4541
4542    async fn handle_unshare_project(
4543        this: Entity<Self>,
4544        _: TypedEnvelope<proto::UnshareProject>,
4545        mut cx: AsyncApp,
4546    ) -> Result<()> {
4547        this.update(&mut cx, |this, cx| {
4548            if this.is_local() || this.is_via_remote_server() {
4549                this.unshare(cx)?;
4550            } else {
4551                this.disconnected_from_host(cx);
4552            }
4553            Ok(())
4554        })?
4555    }
4556
4557    async fn handle_add_collaborator(
4558        this: Entity<Self>,
4559        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4560        mut cx: AsyncApp,
4561    ) -> Result<()> {
4562        let collaborator = envelope
4563            .payload
4564            .collaborator
4565            .take()
4566            .context("empty collaborator")?;
4567
4568        let collaborator = Collaborator::from_proto(collaborator)?;
4569        this.update(&mut cx, |this, cx| {
4570            this.buffer_store.update(cx, |buffer_store, _| {
4571                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4572            });
4573            this.breakpoint_store.read(cx).broadcast();
4574            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4575            this.collaborators
4576                .insert(collaborator.peer_id, collaborator);
4577        })?;
4578
4579        Ok(())
4580    }
4581
4582    async fn handle_update_project_collaborator(
4583        this: Entity<Self>,
4584        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4585        mut cx: AsyncApp,
4586    ) -> Result<()> {
4587        let old_peer_id = envelope
4588            .payload
4589            .old_peer_id
4590            .context("missing old peer id")?;
4591        let new_peer_id = envelope
4592            .payload
4593            .new_peer_id
4594            .context("missing new peer id")?;
4595        this.update(&mut cx, |this, cx| {
4596            let collaborator = this
4597                .collaborators
4598                .remove(&old_peer_id)
4599                .context("received UpdateProjectCollaborator for unknown peer")?;
4600            let is_host = collaborator.is_host;
4601            this.collaborators.insert(new_peer_id, collaborator);
4602
4603            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4604            this.buffer_store.update(cx, |buffer_store, _| {
4605                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4606            });
4607
4608            if is_host {
4609                this.buffer_store
4610                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4611                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4612                    .unwrap();
4613                cx.emit(Event::HostReshared);
4614            }
4615
4616            cx.emit(Event::CollaboratorUpdated {
4617                old_peer_id,
4618                new_peer_id,
4619            });
4620            Ok(())
4621        })?
4622    }
4623
4624    async fn handle_remove_collaborator(
4625        this: Entity<Self>,
4626        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4627        mut cx: AsyncApp,
4628    ) -> Result<()> {
4629        this.update(&mut cx, |this, cx| {
4630            let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4631            let replica_id = this
4632                .collaborators
4633                .remove(&peer_id)
4634                .with_context(|| format!("unknown peer {peer_id:?}"))?
4635                .replica_id;
4636            this.buffer_store.update(cx, |buffer_store, cx| {
4637                buffer_store.forget_shared_buffers_for(&peer_id);
4638                for buffer in buffer_store.buffers() {
4639                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4640                }
4641            });
4642            this.git_store.update(cx, |git_store, _| {
4643                git_store.forget_shared_diffs_for(&peer_id);
4644            });
4645
4646            cx.emit(Event::CollaboratorLeft(peer_id));
4647            Ok(())
4648        })?
4649    }
4650
4651    async fn handle_update_project(
4652        this: Entity<Self>,
4653        envelope: TypedEnvelope<proto::UpdateProject>,
4654        mut cx: AsyncApp,
4655    ) -> Result<()> {
4656        this.update(&mut cx, |this, cx| {
4657            // Don't handle messages that were sent before the response to us joining the project
4658            if envelope.message_id > this.join_project_response_message_id {
4659                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4660            }
4661            Ok(())
4662        })?
4663    }
4664
4665    async fn handle_toast(
4666        this: Entity<Self>,
4667        envelope: TypedEnvelope<proto::Toast>,
4668        mut cx: AsyncApp,
4669    ) -> Result<()> {
4670        this.update(&mut cx, |_, cx| {
4671            cx.emit(Event::Toast {
4672                notification_id: envelope.payload.notification_id.into(),
4673                message: envelope.payload.message,
4674            });
4675            Ok(())
4676        })?
4677    }
4678
4679    async fn handle_language_server_prompt_request(
4680        this: Entity<Self>,
4681        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4682        mut cx: AsyncApp,
4683    ) -> Result<proto::LanguageServerPromptResponse> {
4684        let (tx, rx) = smol::channel::bounded(1);
4685        let actions: Vec<_> = envelope
4686            .payload
4687            .actions
4688            .into_iter()
4689            .map(|action| MessageActionItem {
4690                title: action,
4691                properties: Default::default(),
4692            })
4693            .collect();
4694        this.update(&mut cx, |_, cx| {
4695            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4696                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4697                message: envelope.payload.message,
4698                actions: actions.clone(),
4699                lsp_name: envelope.payload.lsp_name,
4700                response_channel: tx,
4701            }));
4702
4703            anyhow::Ok(())
4704        })??;
4705
4706        // We drop `this` to avoid holding a reference in this future for too
4707        // long.
4708        // If we keep the reference, we might not drop the `Project` early
4709        // enough when closing a window and it will only get releases on the
4710        // next `flush_effects()` call.
4711        drop(this);
4712
4713        let mut rx = pin!(rx);
4714        let answer = rx.next().await;
4715
4716        Ok(LanguageServerPromptResponse {
4717            action_response: answer.and_then(|answer| {
4718                actions
4719                    .iter()
4720                    .position(|action| *action == answer)
4721                    .map(|index| index as u64)
4722            }),
4723        })
4724    }
4725
4726    async fn handle_hide_toast(
4727        this: Entity<Self>,
4728        envelope: TypedEnvelope<proto::HideToast>,
4729        mut cx: AsyncApp,
4730    ) -> Result<()> {
4731        this.update(&mut cx, |_, cx| {
4732            cx.emit(Event::HideToast {
4733                notification_id: envelope.payload.notification_id.into(),
4734            });
4735            Ok(())
4736        })?
4737    }
4738
4739    // Collab sends UpdateWorktree protos as messages
4740    async fn handle_update_worktree(
4741        this: Entity<Self>,
4742        envelope: TypedEnvelope<proto::UpdateWorktree>,
4743        mut cx: AsyncApp,
4744    ) -> Result<()> {
4745        this.update(&mut cx, |this, cx| {
4746            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4747            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
4748                worktree.update(cx, |worktree, _| {
4749                    let worktree = worktree.as_remote_mut().unwrap();
4750                    worktree.update_from_remote(envelope.payload);
4751                });
4752            }
4753            Ok(())
4754        })?
4755    }
4756
4757    async fn handle_update_buffer_from_remote_server(
4758        this: Entity<Self>,
4759        envelope: TypedEnvelope<proto::UpdateBuffer>,
4760        cx: AsyncApp,
4761    ) -> Result<proto::Ack> {
4762        let buffer_store = this.read_with(&cx, |this, cx| {
4763            if let Some(remote_id) = this.remote_id() {
4764                let mut payload = envelope.payload.clone();
4765                payload.project_id = remote_id;
4766                cx.background_spawn(this.collab_client.request(payload))
4767                    .detach_and_log_err(cx);
4768            }
4769            this.buffer_store.clone()
4770        })?;
4771        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4772    }
4773
4774    async fn handle_update_buffer(
4775        this: Entity<Self>,
4776        envelope: TypedEnvelope<proto::UpdateBuffer>,
4777        cx: AsyncApp,
4778    ) -> Result<proto::Ack> {
4779        let buffer_store = this.read_with(&cx, |this, cx| {
4780            if let Some(ssh) = &this.remote_client {
4781                let mut payload = envelope.payload.clone();
4782                payload.project_id = REMOTE_SERVER_PROJECT_ID;
4783                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4784                    .detach_and_log_err(cx);
4785            }
4786            this.buffer_store.clone()
4787        })?;
4788        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4789    }
4790
4791    fn retain_remotely_created_models(
4792        &mut self,
4793        cx: &mut Context<Self>,
4794    ) -> RemotelyCreatedModelGuard {
4795        {
4796            let mut remotely_create_models = self.remotely_created_models.lock();
4797            if remotely_create_models.retain_count == 0 {
4798                remotely_create_models.buffers = self.buffer_store.read(cx).buffers().collect();
4799                remotely_create_models.worktrees =
4800                    self.worktree_store.read(cx).worktrees().collect();
4801            }
4802            remotely_create_models.retain_count += 1;
4803        }
4804        RemotelyCreatedModelGuard {
4805            remote_models: Arc::downgrade(&self.remotely_created_models),
4806        }
4807    }
4808
4809    async fn handle_create_buffer_for_peer(
4810        this: Entity<Self>,
4811        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4812        mut cx: AsyncApp,
4813    ) -> Result<()> {
4814        this.update(&mut cx, |this, cx| {
4815            this.buffer_store.update(cx, |buffer_store, cx| {
4816                buffer_store.handle_create_buffer_for_peer(
4817                    envelope,
4818                    this.replica_id(),
4819                    this.capability(),
4820                    cx,
4821                )
4822            })
4823        })?
4824    }
4825
4826    async fn handle_toggle_lsp_logs(
4827        project: Entity<Self>,
4828        envelope: TypedEnvelope<proto::ToggleLspLogs>,
4829        mut cx: AsyncApp,
4830    ) -> Result<()> {
4831        let toggled_log_kind =
4832            match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
4833                .context("invalid log type")?
4834            {
4835                proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
4836                proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
4837                proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
4838            };
4839        project.update(&mut cx, |_, cx| {
4840            cx.emit(Event::ToggleLspLogs {
4841                server_id: LanguageServerId::from_proto(envelope.payload.server_id),
4842                enabled: envelope.payload.enabled,
4843                toggled_log_kind,
4844            })
4845        })?;
4846        Ok(())
4847    }
4848
4849    async fn handle_synchronize_buffers(
4850        this: Entity<Self>,
4851        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4852        mut cx: AsyncApp,
4853    ) -> Result<proto::SynchronizeBuffersResponse> {
4854        let response = this.update(&mut cx, |this, cx| {
4855            let client = this.collab_client.clone();
4856            this.buffer_store.update(cx, |this, cx| {
4857                this.handle_synchronize_buffers(envelope, cx, client)
4858            })
4859        })??;
4860
4861        Ok(response)
4862    }
4863
4864    async fn handle_search_candidate_buffers(
4865        this: Entity<Self>,
4866        envelope: TypedEnvelope<proto::FindSearchCandidates>,
4867        mut cx: AsyncApp,
4868    ) -> Result<proto::FindSearchCandidatesResponse> {
4869        let peer_id = envelope.original_sender_id()?;
4870        let message = envelope.payload;
4871        let path_style = this.read_with(&cx, |this, cx| this.path_style(cx))?;
4872        let query =
4873            SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
4874        let results = this.update(&mut cx, |this, cx| {
4875            this.search_impl(query, cx).matching_buffers(cx)
4876        })?;
4877
4878        let mut response = proto::FindSearchCandidatesResponse {
4879            buffer_ids: Vec::new(),
4880        };
4881
4882        while let Ok(buffer) = results.recv().await {
4883            this.update(&mut cx, |this, cx| {
4884                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
4885                response.buffer_ids.push(buffer_id.to_proto());
4886            })?;
4887        }
4888
4889        Ok(response)
4890    }
4891
4892    async fn handle_open_buffer_by_id(
4893        this: Entity<Self>,
4894        envelope: TypedEnvelope<proto::OpenBufferById>,
4895        mut cx: AsyncApp,
4896    ) -> Result<proto::OpenBufferResponse> {
4897        let peer_id = envelope.original_sender_id()?;
4898        let buffer_id = BufferId::new(envelope.payload.id)?;
4899        let buffer = this
4900            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
4901            .await?;
4902        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4903    }
4904
4905    async fn handle_open_buffer_by_path(
4906        this: Entity<Self>,
4907        envelope: TypedEnvelope<proto::OpenBufferByPath>,
4908        mut cx: AsyncApp,
4909    ) -> Result<proto::OpenBufferResponse> {
4910        let peer_id = envelope.original_sender_id()?;
4911        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4912        let path = RelPath::from_proto(&envelope.payload.path)?;
4913        let open_buffer = this
4914            .update(&mut cx, |this, cx| {
4915                this.open_buffer(ProjectPath { worktree_id, path }, cx)
4916            })?
4917            .await?;
4918        Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
4919    }
4920
4921    async fn handle_open_new_buffer(
4922        this: Entity<Self>,
4923        envelope: TypedEnvelope<proto::OpenNewBuffer>,
4924        mut cx: AsyncApp,
4925    ) -> Result<proto::OpenBufferResponse> {
4926        let buffer = this
4927            .update(&mut cx, |this, cx| this.create_buffer(true, cx))?
4928            .await?;
4929        let peer_id = envelope.original_sender_id()?;
4930
4931        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
4932    }
4933
4934    fn respond_to_open_buffer_request(
4935        this: Entity<Self>,
4936        buffer: Entity<Buffer>,
4937        peer_id: proto::PeerId,
4938        cx: &mut AsyncApp,
4939    ) -> Result<proto::OpenBufferResponse> {
4940        this.update(cx, |this, cx| {
4941            let is_private = buffer
4942                .read(cx)
4943                .file()
4944                .map(|f| f.is_private())
4945                .unwrap_or_default();
4946            anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
4947            Ok(proto::OpenBufferResponse {
4948                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
4949            })
4950        })?
4951    }
4952
4953    fn create_buffer_for_peer(
4954        &mut self,
4955        buffer: &Entity<Buffer>,
4956        peer_id: proto::PeerId,
4957        cx: &mut App,
4958    ) -> BufferId {
4959        self.buffer_store
4960            .update(cx, |buffer_store, cx| {
4961                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
4962            })
4963            .detach_and_log_err(cx);
4964        buffer.read(cx).remote_id()
4965    }
4966
4967    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
4968        let project_id = match self.client_state {
4969            ProjectClientState::Remote {
4970                sharing_has_stopped,
4971                remote_id,
4972                ..
4973            } => {
4974                if sharing_has_stopped {
4975                    return Task::ready(Err(anyhow!(
4976                        "can't synchronize remote buffers on a readonly project"
4977                    )));
4978                } else {
4979                    remote_id
4980                }
4981            }
4982            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
4983                return Task::ready(Err(anyhow!(
4984                    "can't synchronize remote buffers on a local project"
4985                )));
4986            }
4987        };
4988
4989        let client = self.collab_client.clone();
4990        cx.spawn(async move |this, cx| {
4991            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
4992                this.buffer_store.read(cx).buffer_version_info(cx)
4993            })?;
4994            let response = client
4995                .request(proto::SynchronizeBuffers {
4996                    project_id,
4997                    buffers,
4998                })
4999                .await?;
5000
5001            let send_updates_for_buffers = this.update(cx, |this, cx| {
5002                response
5003                    .buffers
5004                    .into_iter()
5005                    .map(|buffer| {
5006                        let client = client.clone();
5007                        let buffer_id = match BufferId::new(buffer.id) {
5008                            Ok(id) => id,
5009                            Err(e) => {
5010                                return Task::ready(Err(e));
5011                            }
5012                        };
5013                        let remote_version = language::proto::deserialize_version(&buffer.version);
5014                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5015                            let operations =
5016                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
5017                            cx.background_spawn(async move {
5018                                let operations = operations.await;
5019                                for chunk in split_operations(operations) {
5020                                    client
5021                                        .request(proto::UpdateBuffer {
5022                                            project_id,
5023                                            buffer_id: buffer_id.into(),
5024                                            operations: chunk,
5025                                        })
5026                                        .await?;
5027                                }
5028                                anyhow::Ok(())
5029                            })
5030                        } else {
5031                            Task::ready(Ok(()))
5032                        }
5033                    })
5034                    .collect::<Vec<_>>()
5035            })?;
5036
5037            // Any incomplete buffers have open requests waiting. Request that the host sends
5038            // creates these buffers for us again to unblock any waiting futures.
5039            for id in incomplete_buffer_ids {
5040                cx.background_spawn(client.request(proto::OpenBufferById {
5041                    project_id,
5042                    id: id.into(),
5043                }))
5044                .detach();
5045            }
5046
5047            futures::future::join_all(send_updates_for_buffers)
5048                .await
5049                .into_iter()
5050                .collect()
5051        })
5052    }
5053
5054    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5055        self.worktree_store.read(cx).worktree_metadata_protos(cx)
5056    }
5057
5058    /// Iterator of all open buffers that have unsaved changes
5059    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5060        self.buffer_store.read(cx).buffers().filter_map(|buf| {
5061            let buf = buf.read(cx);
5062            if buf.is_dirty() {
5063                buf.project_path(cx)
5064            } else {
5065                None
5066            }
5067        })
5068    }
5069
5070    fn set_worktrees_from_proto(
5071        &mut self,
5072        worktrees: Vec<proto::WorktreeMetadata>,
5073        cx: &mut Context<Project>,
5074    ) -> Result<()> {
5075        self.worktree_store.update(cx, |worktree_store, cx| {
5076            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5077        })
5078    }
5079
5080    fn set_collaborators_from_proto(
5081        &mut self,
5082        messages: Vec<proto::Collaborator>,
5083        cx: &mut Context<Self>,
5084    ) -> Result<()> {
5085        let mut collaborators = HashMap::default();
5086        for message in messages {
5087            let collaborator = Collaborator::from_proto(message)?;
5088            collaborators.insert(collaborator.peer_id, collaborator);
5089        }
5090        for old_peer_id in self.collaborators.keys() {
5091            if !collaborators.contains_key(old_peer_id) {
5092                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5093            }
5094        }
5095        self.collaborators = collaborators;
5096        Ok(())
5097    }
5098
5099    pub fn supplementary_language_servers<'a>(
5100        &'a self,
5101        cx: &'a App,
5102    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5103        self.lsp_store.read(cx).supplementary_language_servers()
5104    }
5105
5106    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5107        let Some(language) = buffer.language().cloned() else {
5108            return false;
5109        };
5110        self.lsp_store.update(cx, |lsp_store, _| {
5111            let relevant_language_servers = lsp_store
5112                .languages
5113                .lsp_adapters(&language.name())
5114                .into_iter()
5115                .map(|lsp_adapter| lsp_adapter.name())
5116                .collect::<HashSet<_>>();
5117            lsp_store
5118                .language_server_statuses()
5119                .filter_map(|(server_id, server_status)| {
5120                    relevant_language_servers
5121                        .contains(&server_status.name)
5122                        .then_some(server_id)
5123                })
5124                .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5125                .any(InlayHints::check_capabilities)
5126        })
5127    }
5128
5129    pub fn language_server_id_for_name(
5130        &self,
5131        buffer: &Buffer,
5132        name: &LanguageServerName,
5133        cx: &App,
5134    ) -> Option<LanguageServerId> {
5135        let language = buffer.language()?;
5136        let relevant_language_servers = self
5137            .languages
5138            .lsp_adapters(&language.name())
5139            .into_iter()
5140            .map(|lsp_adapter| lsp_adapter.name())
5141            .collect::<HashSet<_>>();
5142        if !relevant_language_servers.contains(name) {
5143            return None;
5144        }
5145        self.language_server_statuses(cx)
5146            .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5147            .find_map(|(server_id, server_status)| {
5148                if &server_status.name == name {
5149                    Some(server_id)
5150                } else {
5151                    None
5152                }
5153            })
5154    }
5155
5156    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5157        self.lsp_store.update(cx, |this, cx| {
5158            this.language_servers_for_local_buffer(buffer, cx)
5159                .next()
5160                .is_some()
5161        })
5162    }
5163
5164    pub fn git_init(
5165        &self,
5166        path: Arc<Path>,
5167        fallback_branch_name: String,
5168        cx: &App,
5169    ) -> Task<Result<()>> {
5170        self.git_store
5171            .read(cx)
5172            .git_init(path, fallback_branch_name, cx)
5173    }
5174
5175    pub fn buffer_store(&self) -> &Entity<BufferStore> {
5176        &self.buffer_store
5177    }
5178
5179    pub fn git_store(&self) -> &Entity<GitStore> {
5180        &self.git_store
5181    }
5182
5183    pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5184        &self.agent_server_store
5185    }
5186
5187    #[cfg(test)]
5188    fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5189        cx.spawn(async move |this, cx| {
5190            let scans_complete = this
5191                .read_with(cx, |this, cx| {
5192                    this.worktrees(cx)
5193                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5194                        .collect::<Vec<_>>()
5195                })
5196                .unwrap();
5197            join_all(scans_complete).await;
5198            let barriers = this
5199                .update(cx, |this, cx| {
5200                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5201                    repos
5202                        .into_iter()
5203                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5204                        .collect::<Vec<_>>()
5205                })
5206                .unwrap();
5207            join_all(barriers).await;
5208        })
5209    }
5210
5211    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5212        self.git_store.read(cx).active_repository()
5213    }
5214
5215    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5216        self.git_store.read(cx).repositories()
5217    }
5218
5219    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5220        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5221    }
5222
5223    pub fn set_agent_location(
5224        &mut self,
5225        new_location: Option<AgentLocation>,
5226        cx: &mut Context<Self>,
5227    ) {
5228        if let Some(old_location) = self.agent_location.as_ref() {
5229            old_location
5230                .buffer
5231                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5232                .ok();
5233        }
5234
5235        if let Some(location) = new_location.as_ref() {
5236            location
5237                .buffer
5238                .update(cx, |buffer, cx| {
5239                    buffer.set_agent_selections(
5240                        Arc::from([language::Selection {
5241                            id: 0,
5242                            start: location.position,
5243                            end: location.position,
5244                            reversed: false,
5245                            goal: language::SelectionGoal::None,
5246                        }]),
5247                        false,
5248                        CursorShape::Hollow,
5249                        cx,
5250                    )
5251                })
5252                .ok();
5253        }
5254
5255        self.agent_location = new_location;
5256        cx.emit(Event::AgentLocationChanged);
5257    }
5258
5259    pub fn agent_location(&self) -> Option<AgentLocation> {
5260        self.agent_location.clone()
5261    }
5262
5263    pub fn path_style(&self, cx: &App) -> PathStyle {
5264        self.worktree_store.read(cx).path_style()
5265    }
5266
5267    pub fn contains_local_settings_file(
5268        &self,
5269        worktree_id: WorktreeId,
5270        rel_path: &RelPath,
5271        cx: &App,
5272    ) -> bool {
5273        self.worktree_for_id(worktree_id, cx)
5274            .map_or(false, |worktree| {
5275                worktree.read(cx).entry_for_path(rel_path).is_some()
5276            })
5277    }
5278
5279    pub fn update_local_settings_file(
5280        &self,
5281        worktree_id: WorktreeId,
5282        rel_path: Arc<RelPath>,
5283        cx: &mut App,
5284        update: impl 'static + Send + FnOnce(&mut settings::SettingsContent, &App),
5285    ) {
5286        let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
5287            // todo(settings_ui) error?
5288            return;
5289        };
5290        cx.spawn(async move |cx| {
5291            let file = worktree
5292                .update(cx, |worktree, cx| worktree.load_file(&rel_path, cx))?
5293                .await
5294                .context("Failed to load settings file")?;
5295
5296            let new_text = cx.read_global::<SettingsStore, _>(|store, cx| {
5297                store.new_text_for_update(file.text, move |settings| update(settings, cx))
5298            })?;
5299            worktree
5300                .update(cx, |worktree, cx| {
5301                    let line_ending = text::LineEnding::detect(&new_text);
5302                    worktree.write_file(rel_path.clone(), new_text.into(), line_ending, cx)
5303                })?
5304                .await
5305                .context("Failed to write settings file")?;
5306
5307            anyhow::Ok(())
5308        })
5309        .detach_and_log_err(cx);
5310    }
5311}
5312
5313pub struct PathMatchCandidateSet {
5314    pub snapshot: Snapshot,
5315    pub include_ignored: bool,
5316    pub include_root_name: bool,
5317    pub candidates: Candidates,
5318}
5319
5320pub enum Candidates {
5321    /// Only consider directories.
5322    Directories,
5323    /// Only consider files.
5324    Files,
5325    /// Consider directories and files.
5326    Entries,
5327}
5328
5329impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5330    type Candidates = PathMatchCandidateSetIter<'a>;
5331
5332    fn id(&self) -> usize {
5333        self.snapshot.id().to_usize()
5334    }
5335
5336    fn len(&self) -> usize {
5337        match self.candidates {
5338            Candidates::Files => {
5339                if self.include_ignored {
5340                    self.snapshot.file_count()
5341                } else {
5342                    self.snapshot.visible_file_count()
5343                }
5344            }
5345
5346            Candidates::Directories => {
5347                if self.include_ignored {
5348                    self.snapshot.dir_count()
5349                } else {
5350                    self.snapshot.visible_dir_count()
5351                }
5352            }
5353
5354            Candidates::Entries => {
5355                if self.include_ignored {
5356                    self.snapshot.entry_count()
5357                } else {
5358                    self.snapshot.visible_entry_count()
5359                }
5360            }
5361        }
5362    }
5363
5364    fn prefix(&self) -> Arc<RelPath> {
5365        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5366            self.snapshot.root_name().into()
5367        } else {
5368            RelPath::empty().into()
5369        }
5370    }
5371
5372    fn root_is_file(&self) -> bool {
5373        self.snapshot.root_entry().is_some_and(|f| f.is_file())
5374    }
5375
5376    fn path_style(&self) -> PathStyle {
5377        self.snapshot.path_style()
5378    }
5379
5380    fn candidates(&'a self, start: usize) -> Self::Candidates {
5381        PathMatchCandidateSetIter {
5382            traversal: match self.candidates {
5383                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5384                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5385                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5386            },
5387        }
5388    }
5389}
5390
5391pub struct PathMatchCandidateSetIter<'a> {
5392    traversal: Traversal<'a>,
5393}
5394
5395impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5396    type Item = fuzzy::PathMatchCandidate<'a>;
5397
5398    fn next(&mut self) -> Option<Self::Item> {
5399        self.traversal
5400            .next()
5401            .map(|entry| fuzzy::PathMatchCandidate {
5402                is_dir: entry.kind.is_dir(),
5403                path: &entry.path,
5404                char_bag: entry.char_bag,
5405            })
5406    }
5407}
5408
5409impl EventEmitter<Event> for Project {}
5410
5411impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5412    fn from(val: &'a ProjectPath) -> Self {
5413        SettingsLocation {
5414            worktree_id: val.worktree_id,
5415            path: val.path.as_ref(),
5416        }
5417    }
5418}
5419
5420impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5421    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5422        Self {
5423            worktree_id,
5424            path: path.into(),
5425        }
5426    }
5427}
5428
5429/// ResolvedPath is a path that has been resolved to either a ProjectPath
5430/// or an AbsPath and that *exists*.
5431#[derive(Debug, Clone)]
5432pub enum ResolvedPath {
5433    ProjectPath {
5434        project_path: ProjectPath,
5435        is_dir: bool,
5436    },
5437    AbsPath {
5438        path: String,
5439        is_dir: bool,
5440    },
5441}
5442
5443impl ResolvedPath {
5444    pub fn abs_path(&self) -> Option<&str> {
5445        match self {
5446            Self::AbsPath { path, .. } => Some(path),
5447            _ => None,
5448        }
5449    }
5450
5451    pub fn into_abs_path(self) -> Option<String> {
5452        match self {
5453            Self::AbsPath { path, .. } => Some(path),
5454            _ => None,
5455        }
5456    }
5457
5458    pub fn project_path(&self) -> Option<&ProjectPath> {
5459        match self {
5460            Self::ProjectPath { project_path, .. } => Some(project_path),
5461            _ => None,
5462        }
5463    }
5464
5465    pub fn is_file(&self) -> bool {
5466        !self.is_dir()
5467    }
5468
5469    pub fn is_dir(&self) -> bool {
5470        match self {
5471            Self::ProjectPath { is_dir, .. } => *is_dir,
5472            Self::AbsPath { is_dir, .. } => *is_dir,
5473        }
5474    }
5475}
5476
5477impl ProjectItem for Buffer {
5478    fn try_open(
5479        project: &Entity<Project>,
5480        path: &ProjectPath,
5481        cx: &mut App,
5482    ) -> Option<Task<Result<Entity<Self>>>> {
5483        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5484    }
5485
5486    fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
5487        File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
5488    }
5489
5490    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5491        self.file().map(|file| ProjectPath {
5492            worktree_id: file.worktree_id(cx),
5493            path: file.path().clone(),
5494        })
5495    }
5496
5497    fn is_dirty(&self) -> bool {
5498        self.is_dirty()
5499    }
5500}
5501
5502impl Completion {
5503    pub fn kind(&self) -> Option<CompletionItemKind> {
5504        self.source
5505            // `lsp::CompletionListItemDefaults` has no `kind` field
5506            .lsp_completion(false)
5507            .and_then(|lsp_completion| lsp_completion.kind)
5508    }
5509
5510    pub fn label(&self) -> Option<String> {
5511        self.source
5512            .lsp_completion(false)
5513            .map(|lsp_completion| lsp_completion.label.clone())
5514    }
5515
5516    /// A key that can be used to sort completions when displaying
5517    /// them to the user.
5518    pub fn sort_key(&self) -> (usize, &str) {
5519        const DEFAULT_KIND_KEY: usize = 4;
5520        let kind_key = self
5521            .kind()
5522            .and_then(|lsp_completion_kind| match lsp_completion_kind {
5523                lsp::CompletionItemKind::KEYWORD => Some(0),
5524                lsp::CompletionItemKind::VARIABLE => Some(1),
5525                lsp::CompletionItemKind::CONSTANT => Some(2),
5526                lsp::CompletionItemKind::PROPERTY => Some(3),
5527                _ => None,
5528            })
5529            .unwrap_or(DEFAULT_KIND_KEY);
5530        (kind_key, self.label.filter_text())
5531    }
5532
5533    /// Whether this completion is a snippet.
5534    pub fn is_snippet(&self) -> bool {
5535        self.source
5536            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5537            .lsp_completion(true)
5538            .is_some_and(|lsp_completion| {
5539                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5540            })
5541    }
5542
5543    /// Returns the corresponding color for this completion.
5544    ///
5545    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5546    pub fn color(&self) -> Option<Hsla> {
5547        // `lsp::CompletionListItemDefaults` has no `kind` field
5548        let lsp_completion = self.source.lsp_completion(false)?;
5549        if lsp_completion.kind? == CompletionItemKind::COLOR {
5550            return color_extractor::extract_color(&lsp_completion);
5551        }
5552        None
5553    }
5554}
5555
5556fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5557    match level {
5558        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5559        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5560        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5561    }
5562}
5563
5564fn provide_inline_values(
5565    captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5566    snapshot: &language::BufferSnapshot,
5567    max_row: usize,
5568) -> Vec<InlineValueLocation> {
5569    let mut variables = Vec::new();
5570    let mut variable_position = HashSet::default();
5571    let mut scopes = Vec::new();
5572
5573    let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5574
5575    for (capture_range, capture_kind) in captures {
5576        match capture_kind {
5577            language::DebuggerTextObject::Variable => {
5578                let variable_name = snapshot
5579                    .text_for_range(capture_range.clone())
5580                    .collect::<String>();
5581                let point = snapshot.offset_to_point(capture_range.end);
5582
5583                while scopes
5584                    .last()
5585                    .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5586                {
5587                    scopes.pop();
5588                }
5589
5590                if point.row as usize > max_row {
5591                    break;
5592                }
5593
5594                let scope = if scopes
5595                    .last()
5596                    .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5597                {
5598                    VariableScope::Global
5599                } else {
5600                    VariableScope::Local
5601                };
5602
5603                if variable_position.insert(capture_range.end) {
5604                    variables.push(InlineValueLocation {
5605                        variable_name,
5606                        scope,
5607                        lookup: VariableLookupKind::Variable,
5608                        row: point.row as usize,
5609                        column: point.column as usize,
5610                    });
5611                }
5612            }
5613            language::DebuggerTextObject::Scope => {
5614                while scopes.last().map_or_else(
5615                    || false,
5616                    |scope: &Range<usize>| {
5617                        !(scope.contains(&capture_range.start)
5618                            && scope.contains(&capture_range.end))
5619                    },
5620                ) {
5621                    scopes.pop();
5622                }
5623                scopes.push(capture_range);
5624            }
5625        }
5626    }
5627
5628    variables
5629}
5630
5631#[cfg(test)]
5632mod disable_ai_settings_tests {
5633    use super::*;
5634    use gpui::TestAppContext;
5635    use settings::Settings;
5636
5637    #[gpui::test]
5638    async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5639        cx.update(|cx| {
5640            settings::init(cx);
5641            Project::init_settings(cx);
5642
5643            // Test 1: Default is false (AI enabled)
5644            assert!(
5645                !DisableAiSettings::get_global(cx).disable_ai,
5646                "Default should allow AI"
5647            );
5648        });
5649
5650        let disable_true = serde_json::json!({
5651            "disable_ai": true
5652        })
5653        .to_string();
5654        let disable_false = serde_json::json!({
5655            "disable_ai": false
5656        })
5657        .to_string();
5658
5659        cx.update_global::<SettingsStore, _>(|store, cx| {
5660            store.set_user_settings(&disable_false, cx).unwrap();
5661            store.set_global_settings(&disable_true, cx).unwrap();
5662        });
5663        cx.update(|cx| {
5664            assert!(
5665                DisableAiSettings::get_global(cx).disable_ai,
5666                "Local false cannot override global true"
5667            );
5668        });
5669
5670        cx.update_global::<SettingsStore, _>(|store, cx| {
5671            store.set_global_settings(&disable_false, cx).unwrap();
5672            store.set_user_settings(&disable_true, cx).unwrap();
5673        });
5674
5675        cx.update(|cx| {
5676            assert!(
5677                DisableAiSettings::get_global(cx).disable_ai,
5678                "Local false cannot override global true"
5679            );
5680        });
5681    }
5682}