project.rs

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