project.rs

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