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