project.rs

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