project.rs

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