worktree_store.rs

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