project.rs

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