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