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