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