project.rs

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