worktree_store.rs

   1use std::{
   2    io::{BufRead, BufReader},
   3    path::{Path, PathBuf},
   4    pin::pin,
   5    sync::{Arc, atomic::AtomicUsize},
   6};
   7
   8use anyhow::{Context as _, Result, anyhow, bail};
   9use collections::{HashMap, HashSet};
  10use fs::{Fs, copy_recursive};
  11use futures::{FutureExt, SinkExt, future::Shared};
  12use gpui::{
  13    App, AppContext as _, AsyncApp, Context, Entity, EntityId, EventEmitter, Task, WeakEntity,
  14};
  15use postage::oneshot;
  16use rpc::{
  17    AnyProtoClient, ErrorExt, TypedEnvelope,
  18    proto::{self, REMOTE_SERVER_PROJECT_ID},
  19};
  20use smol::{
  21    channel::{Receiver, Sender},
  22    stream::StreamExt,
  23};
  24use text::ReplicaId;
  25use util::{
  26    ResultExt,
  27    paths::{PathStyle, RemotePathBuf, SanitizedPath},
  28    rel_path::RelPath,
  29};
  30use worktree::{
  31    CreatedEntry, Entry, ProjectEntryId, UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree,
  32    WorktreeId, WorktreeSettings,
  33};
  34
  35use crate::{ProjectPath, search::SearchQuery};
  36
  37struct MatchingEntry {
  38    worktree_root: Arc<Path>,
  39    path: ProjectPath,
  40    respond: oneshot::Sender<ProjectPath>,
  41}
  42
  43enum WorktreeStoreState {
  44    Local {
  45        fs: Arc<dyn Fs>,
  46    },
  47    Remote {
  48        upstream_client: AnyProtoClient,
  49        upstream_project_id: u64,
  50        path_style: PathStyle,
  51    },
  52}
  53
  54pub struct WorktreeStore {
  55    next_entry_id: Arc<AtomicUsize>,
  56    downstream_client: Option<(AnyProtoClient, u64)>,
  57    retain_worktrees: bool,
  58    worktrees: Vec<WorktreeHandle>,
  59    worktrees_reordered: bool,
  60    scanning_enabled: bool,
  61    #[allow(clippy::type_complexity)]
  62    loading_worktrees:
  63        HashMap<Arc<SanitizedPath>, Shared<Task<Result<Entity<Worktree>, Arc<anyhow::Error>>>>>,
  64    state: WorktreeStoreState,
  65}
  66
  67#[derive(Debug)]
  68pub enum WorktreeStoreEvent {
  69    WorktreeAdded(Entity<Worktree>),
  70    WorktreeRemoved(EntityId, WorktreeId),
  71    WorktreeReleased(EntityId, WorktreeId),
  72    WorktreeOrderChanged,
  73    WorktreeUpdateSent(Entity<Worktree>),
  74    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
  75    WorktreeUpdatedGitRepositories(WorktreeId, UpdatedGitRepositoriesSet),
  76    WorktreeDeletedEntry(WorktreeId, ProjectEntryId),
  77}
  78
  79impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
  80
  81impl WorktreeStore {
  82    pub fn init(client: &AnyProtoClient) {
  83        client.add_entity_request_handler(Self::handle_create_project_entry);
  84        client.add_entity_request_handler(Self::handle_copy_project_entry);
  85        client.add_entity_request_handler(Self::handle_delete_project_entry);
  86        client.add_entity_request_handler(Self::handle_expand_project_entry);
  87        client.add_entity_request_handler(Self::handle_expand_all_for_project_entry);
  88    }
  89
  90    pub fn local(retain_worktrees: bool, fs: Arc<dyn Fs>) -> Self {
  91        Self {
  92            next_entry_id: Default::default(),
  93            loading_worktrees: Default::default(),
  94            downstream_client: None,
  95            worktrees: Vec::new(),
  96            worktrees_reordered: false,
  97            scanning_enabled: true,
  98            retain_worktrees,
  99            state: WorktreeStoreState::Local { fs },
 100        }
 101    }
 102
 103    pub fn remote(
 104        retain_worktrees: bool,
 105        upstream_client: AnyProtoClient,
 106        upstream_project_id: u64,
 107        path_style: PathStyle,
 108    ) -> Self {
 109        Self {
 110            next_entry_id: Default::default(),
 111            loading_worktrees: Default::default(),
 112            downstream_client: None,
 113            worktrees: Vec::new(),
 114            worktrees_reordered: false,
 115            scanning_enabled: true,
 116            retain_worktrees,
 117            state: WorktreeStoreState::Remote {
 118                upstream_client,
 119                upstream_project_id,
 120                path_style,
 121            },
 122        }
 123    }
 124
 125    pub fn disable_scanner(&mut self) {
 126        self.scanning_enabled = false;
 127    }
 128
 129    /// Iterates through all worktrees, including ones that don't appear in the project panel
 130    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Entity<Worktree>> {
 131        self.worktrees
 132            .iter()
 133            .filter_map(move |worktree| worktree.upgrade())
 134    }
 135
 136    /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
 137    pub fn visible_worktrees<'a>(
 138        &'a self,
 139        cx: &'a App,
 140    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
 141        self.worktrees()
 142            .filter(|worktree| worktree.read(cx).is_visible())
 143    }
 144
 145    /// Iterates through all user-visible worktrees (directories and files that appear in the project panel) and other, invisible single files that could appear e.g. due to drag and drop.
 146    pub fn visible_worktrees_and_single_files<'a>(
 147        &'a self,
 148        cx: &'a App,
 149    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
 150        self.worktrees()
 151            .filter(|worktree| worktree.read(cx).is_visible() || worktree.read(cx).is_single_file())
 152    }
 153
 154    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
 155        self.worktrees()
 156            .find(|worktree| worktree.read(cx).id() == id)
 157    }
 158
 159    pub fn worktree_for_entry(
 160        &self,
 161        entry_id: ProjectEntryId,
 162        cx: &App,
 163    ) -> Option<Entity<Worktree>> {
 164        self.worktrees()
 165            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
 166    }
 167
 168    pub fn find_worktree(
 169        &self,
 170        abs_path: impl AsRef<Path>,
 171        cx: &App,
 172    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
 173        let abs_path = SanitizedPath::new(abs_path.as_ref());
 174        for tree in self.worktrees() {
 175            let path_style = tree.read(cx).path_style();
 176            if let Ok(relative_path) = abs_path.as_ref().strip_prefix(tree.read(cx).abs_path())
 177                && let Ok(relative_path) = RelPath::new(relative_path, path_style)
 178            {
 179                return Some((tree.clone(), relative_path.into_arc()));
 180            }
 181        }
 182        None
 183    }
 184
 185    pub fn absolutize(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
 186        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
 187        Some(worktree.read(cx).absolutize(&project_path.path))
 188    }
 189
 190    pub fn path_style(&self) -> PathStyle {
 191        match &self.state {
 192            WorktreeStoreState::Local { .. } => PathStyle::local(),
 193            WorktreeStoreState::Remote { path_style, .. } => *path_style,
 194        }
 195    }
 196
 197    pub fn find_or_create_worktree(
 198        &mut self,
 199        abs_path: impl AsRef<Path>,
 200        visible: bool,
 201        cx: &mut Context<Self>,
 202    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
 203        let abs_path = abs_path.as_ref();
 204        if let Some((tree, relative_path)) = self.find_worktree(abs_path, cx) {
 205            Task::ready(Ok((tree, relative_path)))
 206        } else {
 207            let worktree = self.create_worktree(abs_path, visible, cx);
 208            cx.background_spawn(async move { Ok((worktree.await?, RelPath::empty().into())) })
 209        }
 210    }
 211
 212    pub fn entry_for_id<'a>(&'a self, entry_id: ProjectEntryId, cx: &'a App) -> Option<&'a Entry> {
 213        self.worktrees()
 214            .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
 215    }
 216
 217    pub fn worktree_and_entry_for_id<'a>(
 218        &'a self,
 219        entry_id: ProjectEntryId,
 220        cx: &'a App,
 221    ) -> Option<(Entity<Worktree>, &'a Entry)> {
 222        self.worktrees().find_map(|worktree| {
 223            worktree
 224                .read(cx)
 225                .entry_for_id(entry_id)
 226                .map(|e| (worktree.clone(), e))
 227        })
 228    }
 229
 230    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
 231        self.worktree_for_id(path.worktree_id, cx)?
 232            .read(cx)
 233            .entry_for_path(&path.path)
 234    }
 235
 236    pub fn copy_entry(
 237        &mut self,
 238        entry_id: ProjectEntryId,
 239        new_project_path: ProjectPath,
 240        cx: &mut Context<Self>,
 241    ) -> Task<Result<Option<Entry>>> {
 242        let Some(old_worktree) = self.worktree_for_entry(entry_id, cx) else {
 243            return Task::ready(Err(anyhow!("no such worktree")));
 244        };
 245        let Some(old_entry) = old_worktree.read(cx).entry_for_id(entry_id) else {
 246            return Task::ready(Err(anyhow!("no such entry")));
 247        };
 248        let Some(new_worktree) = self.worktree_for_id(new_project_path.worktree_id, cx) else {
 249            return Task::ready(Err(anyhow!("no such worktree")));
 250        };
 251
 252        match &self.state {
 253            WorktreeStoreState::Local { fs } => {
 254                let old_abs_path = old_worktree.read(cx).absolutize(&old_entry.path);
 255                let new_abs_path = new_worktree.read(cx).absolutize(&new_project_path.path);
 256                let fs = fs.clone();
 257                let copy = cx.background_spawn(async move {
 258                    copy_recursive(
 259                        fs.as_ref(),
 260                        &old_abs_path,
 261                        &new_abs_path,
 262                        Default::default(),
 263                    )
 264                    .await
 265                });
 266
 267                cx.spawn(async move |_, cx| {
 268                    copy.await?;
 269                    new_worktree
 270                        .update(cx, |this, cx| {
 271                            this.as_local_mut().unwrap().refresh_entry(
 272                                new_project_path.path,
 273                                None,
 274                                cx,
 275                            )
 276                        })?
 277                        .await
 278                })
 279            }
 280            WorktreeStoreState::Remote {
 281                upstream_client,
 282                upstream_project_id,
 283                ..
 284            } => {
 285                let response = upstream_client.request(proto::CopyProjectEntry {
 286                    project_id: *upstream_project_id,
 287                    entry_id: entry_id.to_proto(),
 288                    new_path: new_project_path.path.to_proto(),
 289                    new_worktree_id: new_project_path.worktree_id.to_proto(),
 290                });
 291                cx.spawn(async move |_, cx| {
 292                    let response = response.await?;
 293                    match response.entry {
 294                        Some(entry) => new_worktree
 295                            .update(cx, |worktree, cx| {
 296                                worktree.as_remote_mut().unwrap().insert_entry(
 297                                    entry,
 298                                    response.worktree_scan_id as usize,
 299                                    cx,
 300                                )
 301                            })?
 302                            .await
 303                            .map(Some),
 304                        None => Ok(None),
 305                    }
 306                })
 307            }
 308        }
 309    }
 310
 311    pub fn rename_entry(
 312        &mut self,
 313        entry_id: ProjectEntryId,
 314        new_project_path: ProjectPath,
 315        cx: &mut Context<Self>,
 316    ) -> Task<Result<CreatedEntry>> {
 317        let Some(old_worktree) = self.worktree_for_entry(entry_id, cx) else {
 318            return Task::ready(Err(anyhow!("no such worktree")));
 319        };
 320        let Some(old_entry) = old_worktree.read(cx).entry_for_id(entry_id).cloned() else {
 321            return Task::ready(Err(anyhow!("no such entry")));
 322        };
 323        let Some(new_worktree) = self.worktree_for_id(new_project_path.worktree_id, cx) else {
 324            return Task::ready(Err(anyhow!("no such worktree")));
 325        };
 326
 327        match &self.state {
 328            WorktreeStoreState::Local { fs } => {
 329                let abs_old_path = old_worktree.read(cx).absolutize(&old_entry.path);
 330                let new_worktree_ref = new_worktree.read(cx);
 331                let is_root_entry = new_worktree_ref
 332                    .root_entry()
 333                    .is_some_and(|e| e.id == entry_id);
 334                let abs_new_path = if is_root_entry {
 335                    let abs_path = new_worktree_ref.abs_path();
 336                    let Some(root_parent_path) = abs_path.parent() else {
 337                        return Task::ready(Err(anyhow!("no parent for path {:?}", abs_path)));
 338                    };
 339                    root_parent_path.join(new_project_path.path.as_std_path())
 340                } else {
 341                    new_worktree_ref.absolutize(&new_project_path.path)
 342                };
 343
 344                let fs = fs.clone();
 345                let case_sensitive = new_worktree
 346                    .read(cx)
 347                    .as_local()
 348                    .unwrap()
 349                    .fs_is_case_sensitive();
 350
 351                let do_rename =
 352                    async move |fs: &dyn Fs, old_path: &Path, new_path: &Path, overwrite| {
 353                        fs.rename(
 354                            &old_path,
 355                            &new_path,
 356                            fs::RenameOptions {
 357                                overwrite,
 358                                ..fs::RenameOptions::default()
 359                            },
 360                        )
 361                        .await
 362                        .with_context(|| format!("renaming {old_path:?} into {new_path:?}"))
 363                    };
 364
 365                let rename = cx.background_spawn({
 366                    let abs_new_path = abs_new_path.clone();
 367                    async move {
 368                        // If we're on a case-insensitive FS and we're doing a case-only rename (i.e. `foobar` to `FOOBAR`)
 369                        // we want to overwrite, because otherwise we run into a file-already-exists error.
 370                        let overwrite = !case_sensitive
 371                            && abs_old_path != abs_new_path
 372                            && abs_old_path.to_str().map(|p| p.to_lowercase())
 373                                == abs_new_path.to_str().map(|p| p.to_lowercase());
 374
 375                        // The directory we're renaming into might not exist yet
 376                        if let Err(e) =
 377                            do_rename(fs.as_ref(), &abs_old_path, &abs_new_path, overwrite).await
 378                        {
 379                            if let Some(err) = e.downcast_ref::<std::io::Error>()
 380                                && err.kind() == std::io::ErrorKind::NotFound
 381                            {
 382                                if let Some(parent) = abs_new_path.parent() {
 383                                    fs.create_dir(parent).await.with_context(|| {
 384                                        format!("creating parent directory {parent:?}")
 385                                    })?;
 386                                    return do_rename(
 387                                        fs.as_ref(),
 388                                        &abs_old_path,
 389                                        &abs_new_path,
 390                                        overwrite,
 391                                    )
 392                                    .await;
 393                                }
 394                            }
 395                            return Err(e);
 396                        }
 397                        Ok(())
 398                    }
 399                });
 400
 401                cx.spawn(async move |_, cx| {
 402                    rename.await?;
 403                    Ok(new_worktree
 404                        .update(cx, |this, cx| {
 405                            let local = this.as_local_mut().unwrap();
 406                            if is_root_entry {
 407                                // We eagerly update `abs_path` and refresh this worktree.
 408                                // Otherwise, the FS watcher would do it on the `RootUpdated` event,
 409                                // but with a noticeable delay, so we handle it proactively.
 410                                local.update_abs_path_and_refresh(
 411                                    SanitizedPath::new_arc(&abs_new_path),
 412                                    cx,
 413                                );
 414                                Task::ready(Ok(this.root_entry().cloned()))
 415                            } else {
 416                                // First refresh the parent directory (in case it was newly created)
 417                                if let Some(parent) = new_project_path.path.parent() {
 418                                    let _ = local.refresh_entries_for_paths(vec![parent.into()]);
 419                                }
 420                                // Then refresh the new path
 421                                local.refresh_entry(
 422                                    new_project_path.path.clone(),
 423                                    Some(old_entry.path),
 424                                    cx,
 425                                )
 426                            }
 427                        })?
 428                        .await?
 429                        .map(CreatedEntry::Included)
 430                        .unwrap_or_else(|| CreatedEntry::Excluded {
 431                            abs_path: abs_new_path,
 432                        }))
 433                })
 434            }
 435            WorktreeStoreState::Remote {
 436                upstream_client,
 437                upstream_project_id,
 438                ..
 439            } => {
 440                let response = upstream_client.request(proto::RenameProjectEntry {
 441                    project_id: *upstream_project_id,
 442                    entry_id: entry_id.to_proto(),
 443                    new_path: new_project_path.path.to_proto(),
 444                    new_worktree_id: new_project_path.worktree_id.to_proto(),
 445                });
 446                cx.spawn(async move |_, cx| {
 447                    let response = response.await?;
 448                    match response.entry {
 449                        Some(entry) => new_worktree
 450                            .update(cx, |worktree, cx| {
 451                                worktree.as_remote_mut().unwrap().insert_entry(
 452                                    entry,
 453                                    response.worktree_scan_id as usize,
 454                                    cx,
 455                                )
 456                            })?
 457                            .await
 458                            .map(CreatedEntry::Included),
 459                        None => {
 460                            let abs_path = new_worktree.read_with(cx, |worktree, _| {
 461                                worktree.absolutize(&new_project_path.path)
 462                            })?;
 463                            Ok(CreatedEntry::Excluded { abs_path })
 464                        }
 465                    }
 466                })
 467            }
 468        }
 469    }
 470    pub fn create_worktree(
 471        &mut self,
 472        abs_path: impl AsRef<Path>,
 473        visible: bool,
 474        cx: &mut Context<Self>,
 475    ) -> Task<Result<Entity<Worktree>>> {
 476        let abs_path: Arc<SanitizedPath> = SanitizedPath::new_arc(&abs_path);
 477        if !self.loading_worktrees.contains_key(&abs_path) {
 478            let task = match &self.state {
 479                WorktreeStoreState::Remote {
 480                    upstream_client,
 481                    path_style,
 482                    ..
 483                } => {
 484                    if upstream_client.is_via_collab() {
 485                        Task::ready(Err(Arc::new(anyhow!("cannot create worktrees via collab"))))
 486                    } else {
 487                        let abs_path = RemotePathBuf::new(abs_path.to_string(), *path_style);
 488                        self.create_remote_worktree(upstream_client.clone(), abs_path, visible, cx)
 489                    }
 490                }
 491                WorktreeStoreState::Local { fs } => {
 492                    self.create_local_worktree(fs.clone(), abs_path.clone(), visible, cx)
 493                }
 494            };
 495
 496            self.loading_worktrees
 497                .insert(abs_path.clone(), task.shared());
 498        }
 499        let task = self.loading_worktrees.get(&abs_path).unwrap().clone();
 500        cx.spawn(async move |this, cx| {
 501            let result = task.await;
 502            this.update(cx, |this, _| this.loading_worktrees.remove(&abs_path))
 503                .ok();
 504            match result {
 505                Ok(worktree) => Ok(worktree),
 506                Err(err) => Err((*err).cloned()),
 507            }
 508        })
 509    }
 510
 511    fn create_remote_worktree(
 512        &mut self,
 513        client: AnyProtoClient,
 514        abs_path: RemotePathBuf,
 515        visible: bool,
 516        cx: &mut Context<Self>,
 517    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
 518        let path_style = abs_path.path_style();
 519        let mut abs_path = abs_path.to_string();
 520        // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
 521        // in which case want to strip the leading the `/`.
 522        // On the host-side, the `~` will get expanded.
 523        // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
 524        if abs_path.starts_with("/~") {
 525            abs_path = abs_path[1..].to_string();
 526        }
 527        if abs_path.is_empty() {
 528            abs_path = "~/".to_string();
 529        }
 530
 531        cx.spawn(async move |this, cx| {
 532            let this = this.upgrade().context("Dropped worktree store")?;
 533
 534            let path = RemotePathBuf::new(abs_path, path_style);
 535            let response = client
 536                .request(proto::AddWorktree {
 537                    project_id: REMOTE_SERVER_PROJECT_ID,
 538                    path: path.to_proto(),
 539                    visible,
 540                })
 541                .await?;
 542
 543            if let Some(existing_worktree) = this.read_with(cx, |this, cx| {
 544                this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
 545            })? {
 546                return Ok(existing_worktree);
 547            }
 548
 549            let root_path_buf = PathBuf::from(response.canonicalized_path.clone());
 550            let root_name = root_path_buf
 551                .file_name()
 552                .map(|n| n.to_string_lossy().into_owned())
 553                .unwrap_or(root_path_buf.to_string_lossy().into_owned());
 554
 555            let worktree = cx.update(|cx| {
 556                Worktree::remote(
 557                    REMOTE_SERVER_PROJECT_ID,
 558                    ReplicaId::REMOTE_SERVER,
 559                    proto::WorktreeMetadata {
 560                        id: response.worktree_id,
 561                        root_name,
 562                        visible,
 563                        abs_path: response.canonicalized_path,
 564                    },
 565                    client,
 566                    path_style,
 567                    cx,
 568                )
 569            })?;
 570
 571            this.update(cx, |this, cx| {
 572                this.add(&worktree, cx);
 573            })?;
 574            Ok(worktree)
 575        })
 576    }
 577
 578    fn create_local_worktree(
 579        &mut self,
 580        fs: Arc<dyn Fs>,
 581        abs_path: Arc<SanitizedPath>,
 582        visible: bool,
 583        cx: &mut Context<Self>,
 584    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
 585        let next_entry_id = self.next_entry_id.clone();
 586        let scanning_enabled = self.scanning_enabled;
 587
 588        cx.spawn(async move |this, cx| {
 589            let worktree = Worktree::local(
 590                SanitizedPath::cast_arc(abs_path.clone()),
 591                visible,
 592                fs,
 593                next_entry_id,
 594                scanning_enabled,
 595                cx,
 596            )
 597            .await;
 598
 599            let worktree = worktree?;
 600
 601            this.update(cx, |this, cx| this.add(&worktree, cx))?;
 602
 603            if visible {
 604                cx.update(|cx| {
 605                    cx.add_recent_document(abs_path.as_path());
 606                })
 607                .log_err();
 608            }
 609
 610            Ok(worktree)
 611        })
 612    }
 613
 614    pub fn add(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
 615        let worktree_id = worktree.read(cx).id();
 616        debug_assert!(self.worktrees().all(|w| w.read(cx).id() != worktree_id));
 617
 618        let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
 619        let handle = if push_strong_handle {
 620            WorktreeHandle::Strong(worktree.clone())
 621        } else {
 622            WorktreeHandle::Weak(worktree.downgrade())
 623        };
 624        if self.worktrees_reordered {
 625            self.worktrees.push(handle);
 626        } else {
 627            let i = match self
 628                .worktrees
 629                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
 630                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
 631                }) {
 632                Ok(i) | Err(i) => i,
 633            };
 634            self.worktrees.insert(i, handle);
 635        }
 636
 637        cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
 638        self.send_project_updates(cx);
 639
 640        let handle_id = worktree.entity_id();
 641        cx.subscribe(worktree, |_, worktree, event, cx| {
 642            let worktree_id = worktree.read(cx).id();
 643            match event {
 644                worktree::Event::UpdatedEntries(changes) => {
 645                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedEntries(
 646                        worktree_id,
 647                        changes.clone(),
 648                    ));
 649                }
 650                worktree::Event::UpdatedGitRepositories(set) => {
 651                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedGitRepositories(
 652                        worktree_id,
 653                        set.clone(),
 654                    ));
 655                }
 656                worktree::Event::DeletedEntry(id) => {
 657                    cx.emit(WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, *id))
 658                }
 659            }
 660        })
 661        .detach();
 662        cx.observe_release(worktree, move |this, worktree, cx| {
 663            cx.emit(WorktreeStoreEvent::WorktreeReleased(
 664                handle_id,
 665                worktree.id(),
 666            ));
 667            cx.emit(WorktreeStoreEvent::WorktreeRemoved(
 668                handle_id,
 669                worktree.id(),
 670            ));
 671            this.send_project_updates(cx);
 672        })
 673        .detach();
 674    }
 675
 676    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
 677        self.worktrees.retain(|worktree| {
 678            if let Some(worktree) = worktree.upgrade() {
 679                if worktree.read(cx).id() == id_to_remove {
 680                    cx.emit(WorktreeStoreEvent::WorktreeRemoved(
 681                        worktree.entity_id(),
 682                        id_to_remove,
 683                    ));
 684                    false
 685                } else {
 686                    true
 687                }
 688            } else {
 689                false
 690            }
 691        });
 692        self.send_project_updates(cx);
 693    }
 694
 695    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
 696        self.worktrees_reordered = worktrees_reordered;
 697    }
 698
 699    fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
 700        match &self.state {
 701            WorktreeStoreState::Remote {
 702                upstream_client,
 703                upstream_project_id,
 704                ..
 705            } => Some((upstream_client.clone(), *upstream_project_id)),
 706            WorktreeStoreState::Local { .. } => None,
 707        }
 708    }
 709
 710    pub fn set_worktrees_from_proto(
 711        &mut self,
 712        worktrees: Vec<proto::WorktreeMetadata>,
 713        replica_id: ReplicaId,
 714        cx: &mut Context<Self>,
 715    ) -> Result<()> {
 716        let mut old_worktrees_by_id = self
 717            .worktrees
 718            .drain(..)
 719            .filter_map(|worktree| {
 720                let worktree = worktree.upgrade()?;
 721                Some((worktree.read(cx).id(), worktree))
 722            })
 723            .collect::<HashMap<_, _>>();
 724
 725        let (client, project_id) = self.upstream_client().context("invalid project")?;
 726
 727        for worktree in worktrees {
 728            if let Some(old_worktree) =
 729                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 730            {
 731                let push_strong_handle =
 732                    self.retain_worktrees || old_worktree.read(cx).is_visible();
 733                let handle = if push_strong_handle {
 734                    WorktreeHandle::Strong(old_worktree.clone())
 735                } else {
 736                    WorktreeHandle::Weak(old_worktree.downgrade())
 737                };
 738                self.worktrees.push(handle);
 739            } else {
 740                self.add(
 741                    &Worktree::remote(
 742                        project_id,
 743                        replica_id,
 744                        worktree,
 745                        client.clone(),
 746                        self.path_style(),
 747                        cx,
 748                    ),
 749                    cx,
 750                );
 751            }
 752        }
 753        self.send_project_updates(cx);
 754
 755        Ok(())
 756    }
 757
 758    pub fn move_worktree(
 759        &mut self,
 760        source: WorktreeId,
 761        destination: WorktreeId,
 762        cx: &mut Context<Self>,
 763    ) -> Result<()> {
 764        if source == destination {
 765            return Ok(());
 766        }
 767
 768        let mut source_index = None;
 769        let mut destination_index = None;
 770        for (i, worktree) in self.worktrees.iter().enumerate() {
 771            if let Some(worktree) = worktree.upgrade() {
 772                let worktree_id = worktree.read(cx).id();
 773                if worktree_id == source {
 774                    source_index = Some(i);
 775                    if destination_index.is_some() {
 776                        break;
 777                    }
 778                } else if worktree_id == destination {
 779                    destination_index = Some(i);
 780                    if source_index.is_some() {
 781                        break;
 782                    }
 783                }
 784            }
 785        }
 786
 787        let source_index =
 788            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
 789        let destination_index =
 790            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
 791
 792        if source_index == destination_index {
 793            return Ok(());
 794        }
 795
 796        let worktree_to_move = self.worktrees.remove(source_index);
 797        self.worktrees.insert(destination_index, worktree_to_move);
 798        self.worktrees_reordered = true;
 799        cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
 800        cx.notify();
 801        Ok(())
 802    }
 803
 804    pub fn disconnected_from_host(&mut self, cx: &mut App) {
 805        for worktree in &self.worktrees {
 806            if let Some(worktree) = worktree.upgrade() {
 807                worktree.update(cx, |worktree, _| {
 808                    if let Some(worktree) = worktree.as_remote_mut() {
 809                        worktree.disconnected_from_host();
 810                    }
 811                });
 812            }
 813        }
 814    }
 815
 816    pub fn send_project_updates(&mut self, cx: &mut Context<Self>) {
 817        let Some((downstream_client, project_id)) = self.downstream_client.clone() else {
 818            return;
 819        };
 820
 821        let update = proto::UpdateProject {
 822            project_id,
 823            worktrees: self.worktree_metadata_protos(cx),
 824        };
 825
 826        // collab has bad concurrency guarantees, so we send requests in serial.
 827        let update_project = if downstream_client.is_via_collab() {
 828            Some(downstream_client.request(update))
 829        } else {
 830            downstream_client.send(update).log_err();
 831            None
 832        };
 833        cx.spawn(async move |this, cx| {
 834            if let Some(update_project) = update_project {
 835                update_project.await?;
 836            }
 837
 838            this.update(cx, |this, cx| {
 839                let worktrees = this.worktrees().collect::<Vec<_>>();
 840
 841                for worktree in worktrees {
 842                    worktree.update(cx, |worktree, cx| {
 843                        let client = downstream_client.clone();
 844                        worktree.observe_updates(project_id, cx, {
 845                            move |update| {
 846                                let client = client.clone();
 847                                async move {
 848                                    if client.is_via_collab() {
 849                                        client
 850                                            .request(update)
 851                                            .map(|result| result.log_err().is_some())
 852                                            .await
 853                                    } else {
 854                                        client.send(update).log_err().is_some()
 855                                    }
 856                                }
 857                            }
 858                        });
 859                    });
 860
 861                    cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
 862                }
 863
 864                anyhow::Ok(())
 865            })
 866        })
 867        .detach_and_log_err(cx);
 868    }
 869
 870    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
 871        self.worktrees()
 872            .map(|worktree| {
 873                let worktree = worktree.read(cx);
 874                proto::WorktreeMetadata {
 875                    id: worktree.id().to_proto(),
 876                    root_name: worktree.root_name_str().to_owned(),
 877                    visible: worktree.is_visible(),
 878                    abs_path: worktree.abs_path().to_string_lossy().into_owned(),
 879                }
 880            })
 881            .collect()
 882    }
 883
 884    pub fn shared(
 885        &mut self,
 886        remote_id: u64,
 887        downstream_client: AnyProtoClient,
 888        cx: &mut Context<Self>,
 889    ) {
 890        self.retain_worktrees = true;
 891        self.downstream_client = Some((downstream_client, remote_id));
 892
 893        // When shared, retain all worktrees
 894        for worktree_handle in self.worktrees.iter_mut() {
 895            match worktree_handle {
 896                WorktreeHandle::Strong(_) => {}
 897                WorktreeHandle::Weak(worktree) => {
 898                    if let Some(worktree) = worktree.upgrade() {
 899                        *worktree_handle = WorktreeHandle::Strong(worktree);
 900                    }
 901                }
 902            }
 903        }
 904        self.send_project_updates(cx);
 905    }
 906
 907    pub fn unshared(&mut self, cx: &mut Context<Self>) {
 908        self.retain_worktrees = false;
 909        self.downstream_client.take();
 910
 911        // When not shared, only retain the visible worktrees
 912        for worktree_handle in self.worktrees.iter_mut() {
 913            if let WorktreeHandle::Strong(worktree) = worktree_handle {
 914                let is_visible = worktree.update(cx, |worktree, _| {
 915                    worktree.stop_observing_updates();
 916                    worktree.is_visible()
 917                });
 918                if !is_visible {
 919                    *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 920                }
 921            }
 922        }
 923    }
 924
 925    /// search over all worktrees and return buffers that *might* match the search.
 926    pub fn find_search_candidates(
 927        &self,
 928        query: SearchQuery,
 929        limit: usize,
 930        open_entries: HashSet<ProjectEntryId>,
 931        fs: Arc<dyn Fs>,
 932        cx: &Context<Self>,
 933    ) -> Receiver<ProjectPath> {
 934        let snapshots = self
 935            .visible_worktrees(cx)
 936            .filter_map(|tree| {
 937                let tree = tree.read(cx);
 938                Some((tree.snapshot(), tree.as_local()?.settings()))
 939            })
 940            .collect::<Vec<_>>();
 941
 942        let executor = cx.background_executor().clone();
 943
 944        // We want to return entries in the order they are in the worktrees, so we have one
 945        // thread that iterates over the worktrees (and ignored directories) as necessary,
 946        // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
 947        // channel.
 948        // We spawn a number of workers that take items from the filter channel and check the query
 949        // against the version of the file on disk.
 950        let (filter_tx, filter_rx) = smol::channel::bounded(64);
 951        let (output_tx, output_rx) = smol::channel::bounded(64);
 952        let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
 953
 954        let input = cx.background_spawn({
 955            let fs = fs.clone();
 956            let query = query.clone();
 957            async move {
 958                Self::find_candidate_paths(
 959                    fs,
 960                    snapshots,
 961                    open_entries,
 962                    query,
 963                    filter_tx,
 964                    output_tx,
 965                )
 966                .await
 967                .log_err();
 968            }
 969        });
 970        const MAX_CONCURRENT_FILE_SCANS: usize = 64;
 971        let filters = cx.background_spawn(async move {
 972            let fs = &fs;
 973            let query = &query;
 974            executor
 975                .scoped(move |scope| {
 976                    for _ in 0..MAX_CONCURRENT_FILE_SCANS {
 977                        let filter_rx = filter_rx.clone();
 978                        scope.spawn(async move {
 979                            Self::filter_paths(fs, filter_rx, query)
 980                                .await
 981                                .log_with_level(log::Level::Debug);
 982                        })
 983                    }
 984                })
 985                .await;
 986        });
 987        cx.background_spawn(async move {
 988            let mut matched = 0;
 989            while let Ok(mut receiver) = output_rx.recv().await {
 990                let Some(path) = receiver.next().await else {
 991                    continue;
 992                };
 993                let Ok(_) = matching_paths_tx.send(path).await else {
 994                    break;
 995                };
 996                matched += 1;
 997                if matched == limit {
 998                    break;
 999                }
1000            }
1001            drop(input);
1002            drop(filters);
1003        })
1004        .detach();
1005        matching_paths_rx
1006    }
1007
1008    async fn find_candidate_paths(
1009        _: Arc<dyn Fs>,
1010        _: Vec<(worktree::Snapshot, WorktreeSettings)>,
1011        _: HashSet<ProjectEntryId>,
1012        _: SearchQuery,
1013        _: Sender<MatchingEntry>,
1014        _: Sender<oneshot::Receiver<ProjectPath>>,
1015    ) -> Result<()> {
1016        Ok(())
1017    }
1018
1019    async fn filter_paths(
1020        fs: &Arc<dyn Fs>,
1021        input: Receiver<MatchingEntry>,
1022        query: &SearchQuery,
1023    ) -> Result<()> {
1024        let mut input = pin!(input);
1025        while let Some(mut entry) = input.next().await {
1026            let abs_path = entry.worktree_root.join(entry.path.path.as_std_path());
1027            let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
1028                continue;
1029            };
1030
1031            let mut file = BufReader::new(file);
1032            let file_start = file.fill_buf()?;
1033
1034            if let Err(Some(starting_position)) =
1035                std::str::from_utf8(file_start).map_err(|e| e.error_len())
1036            {
1037                // Before attempting to match the file content, throw away files that have invalid UTF-8 sequences early on;
1038                // That way we can still match files in a streaming fashion without having look at "obviously binary" files.
1039                log::debug!(
1040                    "Invalid UTF-8 sequence in file {abs_path:?} at byte position {starting_position}"
1041                );
1042                continue;
1043            }
1044
1045            if query.detect(file).unwrap_or(false) {
1046                entry.respond.send(entry.path).await?
1047            }
1048        }
1049
1050        Ok(())
1051    }
1052
1053    pub async fn handle_create_project_entry(
1054        this: Entity<Self>,
1055        envelope: TypedEnvelope<proto::CreateProjectEntry>,
1056        mut cx: AsyncApp,
1057    ) -> Result<proto::ProjectEntryResponse> {
1058        let worktree = this.update(&mut cx, |this, cx| {
1059            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
1060            this.worktree_for_id(worktree_id, cx)
1061                .context("worktree not found")
1062        })??;
1063        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
1064    }
1065
1066    pub async fn handle_copy_project_entry(
1067        this: Entity<Self>,
1068        envelope: TypedEnvelope<proto::CopyProjectEntry>,
1069        mut cx: AsyncApp,
1070    ) -> Result<proto::ProjectEntryResponse> {
1071        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1072        let new_worktree_id = WorktreeId::from_proto(envelope.payload.new_worktree_id);
1073        let new_project_path = (
1074            new_worktree_id,
1075            RelPath::from_proto(&envelope.payload.new_path)?,
1076        );
1077        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
1078            let Some((_, project_id)) = this.downstream_client else {
1079                bail!("no downstream client")
1080            };
1081            let Some(entry) = this.entry_for_id(entry_id, cx) else {
1082                bail!("no such entry");
1083            };
1084            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1085                bail!("entry is private")
1086            }
1087
1088            let new_worktree = this
1089                .worktree_for_id(new_worktree_id, cx)
1090                .context("no such worktree")?;
1091            let scan_id = new_worktree.read(cx).scan_id();
1092            anyhow::Ok((
1093                scan_id,
1094                this.copy_entry(entry_id, new_project_path.into(), cx),
1095            ))
1096        })??;
1097        let entry = entry.await?;
1098        Ok(proto::ProjectEntryResponse {
1099            entry: entry.as_ref().map(|entry| entry.into()),
1100            worktree_scan_id: scan_id as u64,
1101        })
1102    }
1103
1104    pub async fn handle_delete_project_entry(
1105        this: Entity<Self>,
1106        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
1107        mut cx: AsyncApp,
1108    ) -> Result<proto::ProjectEntryResponse> {
1109        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1110        let worktree = this.update(&mut cx, |this, cx| {
1111            let Some((_, project_id)) = this.downstream_client else {
1112                bail!("no downstream client")
1113            };
1114            let Some(entry) = this.entry_for_id(entry_id, cx) else {
1115                bail!("no entry")
1116            };
1117            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1118                bail!("entry is private")
1119            }
1120            this.worktree_for_entry(entry_id, cx)
1121                .context("worktree not found")
1122        })??;
1123        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
1124    }
1125
1126    pub async fn handle_rename_project_entry(
1127        this: Entity<Self>,
1128        request: proto::RenameProjectEntry,
1129        mut cx: AsyncApp,
1130    ) -> Result<proto::ProjectEntryResponse> {
1131        let entry_id = ProjectEntryId::from_proto(request.entry_id);
1132        let new_worktree_id = WorktreeId::from_proto(request.new_worktree_id);
1133        let rel_path = RelPath::from_proto(&request.new_path)
1134            .with_context(|| format!("received invalid relative path {:?}", &request.new_path))?;
1135
1136        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1137            let worktree = this
1138                .worktree_for_entry(entry_id, cx)
1139                .context("no such worktree")?;
1140
1141            let Some((_, project_id)) = this.downstream_client else {
1142                bail!("no downstream client")
1143            };
1144            let entry = worktree
1145                .read(cx)
1146                .entry_for_id(entry_id)
1147                .ok_or_else(|| anyhow!("missing entry"))?;
1148            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1149                bail!("entry is private")
1150            }
1151
1152            let scan_id = worktree.read(cx).scan_id();
1153            anyhow::Ok((
1154                scan_id,
1155                this.rename_entry(entry_id, (new_worktree_id, rel_path).into(), cx),
1156            ))
1157        })??;
1158        Ok(proto::ProjectEntryResponse {
1159            entry: match &task.await? {
1160                CreatedEntry::Included(entry) => Some(entry.into()),
1161                CreatedEntry::Excluded { .. } => None,
1162            },
1163            worktree_scan_id: scan_id as u64,
1164        })
1165    }
1166
1167    pub async fn handle_expand_project_entry(
1168        this: Entity<Self>,
1169        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
1170        mut cx: AsyncApp,
1171    ) -> Result<proto::ExpandProjectEntryResponse> {
1172        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1173        let worktree = this
1174            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1175            .context("invalid request")?;
1176        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
1177    }
1178
1179    pub async fn handle_expand_all_for_project_entry(
1180        this: Entity<Self>,
1181        envelope: TypedEnvelope<proto::ExpandAllForProjectEntry>,
1182        mut cx: AsyncApp,
1183    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1184        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1185        let worktree = this
1186            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1187            .context("invalid request")?;
1188        Worktree::handle_expand_all_for_entry(worktree, envelope.payload, cx).await
1189    }
1190
1191    pub fn fs(&self) -> Option<Arc<dyn Fs>> {
1192        match &self.state {
1193            WorktreeStoreState::Local { fs } => Some(fs.clone()),
1194            WorktreeStoreState::Remote { .. } => None,
1195        }
1196    }
1197}
1198
1199#[derive(Clone, Debug)]
1200enum WorktreeHandle {
1201    Strong(Entity<Worktree>),
1202    Weak(WeakEntity<Worktree>),
1203}
1204
1205impl WorktreeHandle {
1206    fn upgrade(&self) -> Option<Entity<Worktree>> {
1207        match self {
1208            WorktreeHandle::Strong(handle) => Some(handle.clone()),
1209            WorktreeHandle::Weak(handle) => handle.upgrade(),
1210        }
1211    }
1212}