project.rs

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