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