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
 511                                .update(cx, |trusted_worktrees, cx| {
 512                                    trusted_worktrees.can_trust(
 513                                        &worktree_store,
 514                                        worktree.read(cx).id(),
 515                                        cx,
 516                                    );
 517                                })
 518                                .ok();
 519                        }
 520                    }
 521                    Ok(worktree)
 522                }
 523                Err(err) => Err((*err).cloned()),
 524            }
 525        })
 526    }
 527
 528    fn create_remote_worktree(
 529        &mut self,
 530        client: AnyProtoClient,
 531        abs_path: RemotePathBuf,
 532        visible: bool,
 533        cx: &mut Context<Self>,
 534    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
 535        let path_style = abs_path.path_style();
 536        let mut abs_path = abs_path.to_string();
 537        // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
 538        // in which case want to strip the leading the `/`.
 539        // On the host-side, the `~` will get expanded.
 540        // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
 541        if abs_path.starts_with("/~") {
 542            abs_path = abs_path[1..].to_string();
 543        }
 544        if abs_path.is_empty() {
 545            abs_path = "~/".to_string();
 546        }
 547
 548        cx.spawn(async move |this, cx| {
 549            let this = this.upgrade().context("Dropped worktree store")?;
 550
 551            let path = RemotePathBuf::new(abs_path, path_style);
 552            let response = client
 553                .request(proto::AddWorktree {
 554                    project_id: REMOTE_SERVER_PROJECT_ID,
 555                    path: path.to_proto(),
 556                    visible,
 557                })
 558                .await?;
 559
 560            if let Some(existing_worktree) = this.read_with(cx, |this, cx| {
 561                this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
 562            })? {
 563                return Ok(existing_worktree);
 564            }
 565
 566            let root_path_buf = PathBuf::from(response.canonicalized_path.clone());
 567            let root_name = root_path_buf
 568                .file_name()
 569                .map(|n| n.to_string_lossy().into_owned())
 570                .unwrap_or(root_path_buf.to_string_lossy().into_owned());
 571
 572            let worktree = cx.update(|cx| {
 573                Worktree::remote(
 574                    REMOTE_SERVER_PROJECT_ID,
 575                    ReplicaId::REMOTE_SERVER,
 576                    proto::WorktreeMetadata {
 577                        id: response.worktree_id,
 578                        root_name,
 579                        visible,
 580                        abs_path: response.canonicalized_path,
 581                    },
 582                    client,
 583                    path_style,
 584                    cx,
 585                )
 586            })?;
 587
 588            this.update(cx, |this, cx| {
 589                this.add(&worktree, cx);
 590            })?;
 591            Ok(worktree)
 592        })
 593    }
 594
 595    fn create_local_worktree(
 596        &mut self,
 597        fs: Arc<dyn Fs>,
 598        abs_path: Arc<SanitizedPath>,
 599        visible: bool,
 600        cx: &mut Context<Self>,
 601    ) -> Task<Result<Entity<Worktree>, Arc<anyhow::Error>>> {
 602        let next_entry_id = self.next_entry_id.clone();
 603        let scanning_enabled = self.scanning_enabled;
 604
 605        cx.spawn(async move |this, cx| {
 606            let worktree = Worktree::local(
 607                SanitizedPath::cast_arc(abs_path.clone()),
 608                visible,
 609                fs,
 610                next_entry_id,
 611                scanning_enabled,
 612                cx,
 613            )
 614            .await;
 615
 616            let worktree = worktree?;
 617
 618            this.update(cx, |this, cx| this.add(&worktree, cx))?;
 619
 620            if visible {
 621                cx.update(|cx| {
 622                    cx.add_recent_document(abs_path.as_path());
 623                })
 624                .log_err();
 625            }
 626
 627            Ok(worktree)
 628        })
 629    }
 630
 631    pub fn add(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
 632        let worktree_id = worktree.read(cx).id();
 633        debug_assert!(self.worktrees().all(|w| w.read(cx).id() != worktree_id));
 634
 635        let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
 636        let handle = if push_strong_handle {
 637            WorktreeHandle::Strong(worktree.clone())
 638        } else {
 639            WorktreeHandle::Weak(worktree.downgrade())
 640        };
 641        if self.worktrees_reordered {
 642            self.worktrees.push(handle);
 643        } else {
 644            let i = match self
 645                .worktrees
 646                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
 647                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
 648                }) {
 649                Ok(i) | Err(i) => i,
 650            };
 651            self.worktrees.insert(i, handle);
 652        }
 653
 654        cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
 655        self.send_project_updates(cx);
 656
 657        let handle_id = worktree.entity_id();
 658        cx.subscribe(worktree, |_, worktree, event, cx| {
 659            let worktree_id = worktree.read(cx).id();
 660            match event {
 661                worktree::Event::UpdatedEntries(changes) => {
 662                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedEntries(
 663                        worktree_id,
 664                        changes.clone(),
 665                    ));
 666                }
 667                worktree::Event::UpdatedGitRepositories(set) => {
 668                    cx.emit(WorktreeStoreEvent::WorktreeUpdatedGitRepositories(
 669                        worktree_id,
 670                        set.clone(),
 671                    ));
 672                }
 673                worktree::Event::DeletedEntry(id) => {
 674                    cx.emit(WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, *id))
 675                }
 676            }
 677        })
 678        .detach();
 679        cx.observe_release(worktree, move |this, worktree, cx| {
 680            cx.emit(WorktreeStoreEvent::WorktreeReleased(
 681                handle_id,
 682                worktree.id(),
 683            ));
 684            cx.emit(WorktreeStoreEvent::WorktreeRemoved(
 685                handle_id,
 686                worktree.id(),
 687            ));
 688            this.send_project_updates(cx);
 689        })
 690        .detach();
 691    }
 692
 693    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
 694        self.worktrees.retain(|worktree| {
 695            if let Some(worktree) = worktree.upgrade() {
 696                if worktree.read(cx).id() == id_to_remove {
 697                    cx.emit(WorktreeStoreEvent::WorktreeRemoved(
 698                        worktree.entity_id(),
 699                        id_to_remove,
 700                    ));
 701                    false
 702                } else {
 703                    true
 704                }
 705            } else {
 706                false
 707            }
 708        });
 709        self.send_project_updates(cx);
 710    }
 711
 712    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
 713        self.worktrees_reordered = worktrees_reordered;
 714    }
 715
 716    fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
 717        match &self.state {
 718            WorktreeStoreState::Remote {
 719                upstream_client,
 720                upstream_project_id,
 721                ..
 722            } => Some((upstream_client.clone(), *upstream_project_id)),
 723            WorktreeStoreState::Local { .. } => None,
 724        }
 725    }
 726
 727    pub fn set_worktrees_from_proto(
 728        &mut self,
 729        worktrees: Vec<proto::WorktreeMetadata>,
 730        replica_id: ReplicaId,
 731        cx: &mut Context<Self>,
 732    ) -> Result<()> {
 733        let mut old_worktrees_by_id = self
 734            .worktrees
 735            .drain(..)
 736            .filter_map(|worktree| {
 737                let worktree = worktree.upgrade()?;
 738                Some((worktree.read(cx).id(), worktree))
 739            })
 740            .collect::<HashMap<_, _>>();
 741
 742        let (client, project_id) = self.upstream_client().context("invalid project")?;
 743
 744        for worktree in worktrees {
 745            if let Some(old_worktree) =
 746                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
 747            {
 748                let push_strong_handle =
 749                    self.retain_worktrees || old_worktree.read(cx).is_visible();
 750                let handle = if push_strong_handle {
 751                    WorktreeHandle::Strong(old_worktree.clone())
 752                } else {
 753                    WorktreeHandle::Weak(old_worktree.downgrade())
 754                };
 755                self.worktrees.push(handle);
 756            } else {
 757                self.add(
 758                    &Worktree::remote(
 759                        project_id,
 760                        replica_id,
 761                        worktree,
 762                        client.clone(),
 763                        self.path_style(),
 764                        cx,
 765                    ),
 766                    cx,
 767                );
 768            }
 769        }
 770        self.send_project_updates(cx);
 771
 772        Ok(())
 773    }
 774
 775    pub fn move_worktree(
 776        &mut self,
 777        source: WorktreeId,
 778        destination: WorktreeId,
 779        cx: &mut Context<Self>,
 780    ) -> Result<()> {
 781        if source == destination {
 782            return Ok(());
 783        }
 784
 785        let mut source_index = None;
 786        let mut destination_index = None;
 787        for (i, worktree) in self.worktrees.iter().enumerate() {
 788            if let Some(worktree) = worktree.upgrade() {
 789                let worktree_id = worktree.read(cx).id();
 790                if worktree_id == source {
 791                    source_index = Some(i);
 792                    if destination_index.is_some() {
 793                        break;
 794                    }
 795                } else if worktree_id == destination {
 796                    destination_index = Some(i);
 797                    if source_index.is_some() {
 798                        break;
 799                    }
 800                }
 801            }
 802        }
 803
 804        let source_index =
 805            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
 806        let destination_index =
 807            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
 808
 809        if source_index == destination_index {
 810            return Ok(());
 811        }
 812
 813        let worktree_to_move = self.worktrees.remove(source_index);
 814        self.worktrees.insert(destination_index, worktree_to_move);
 815        self.worktrees_reordered = true;
 816        cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
 817        cx.notify();
 818        Ok(())
 819    }
 820
 821    pub fn disconnected_from_host(&mut self, cx: &mut App) {
 822        for worktree in &self.worktrees {
 823            if let Some(worktree) = worktree.upgrade() {
 824                worktree.update(cx, |worktree, _| {
 825                    if let Some(worktree) = worktree.as_remote_mut() {
 826                        worktree.disconnected_from_host();
 827                    }
 828                });
 829            }
 830        }
 831    }
 832
 833    pub fn send_project_updates(&mut self, cx: &mut Context<Self>) {
 834        let Some((downstream_client, project_id)) = self.downstream_client.clone() else {
 835            return;
 836        };
 837
 838        let update = proto::UpdateProject {
 839            project_id,
 840            worktrees: self.worktree_metadata_protos(cx),
 841        };
 842
 843        // collab has bad concurrency guarantees, so we send requests in serial.
 844        let update_project = if downstream_client.is_via_collab() {
 845            Some(downstream_client.request(update))
 846        } else {
 847            downstream_client.send(update).log_err();
 848            None
 849        };
 850        cx.spawn(async move |this, cx| {
 851            if let Some(update_project) = update_project {
 852                update_project.await?;
 853            }
 854
 855            this.update(cx, |this, cx| {
 856                let worktrees = this.worktrees().collect::<Vec<_>>();
 857
 858                for worktree in worktrees {
 859                    worktree.update(cx, |worktree, cx| {
 860                        let client = downstream_client.clone();
 861                        worktree.observe_updates(project_id, cx, {
 862                            move |update| {
 863                                let client = client.clone();
 864                                async move {
 865                                    if client.is_via_collab() {
 866                                        client
 867                                            .request(update)
 868                                            .map(|result| result.log_err().is_some())
 869                                            .await
 870                                    } else {
 871                                        client.send(update).log_err().is_some()
 872                                    }
 873                                }
 874                            }
 875                        });
 876                    });
 877
 878                    cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
 879                }
 880
 881                anyhow::Ok(())
 882            })
 883        })
 884        .detach_and_log_err(cx);
 885    }
 886
 887    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
 888        self.worktrees()
 889            .map(|worktree| {
 890                let worktree = worktree.read(cx);
 891                proto::WorktreeMetadata {
 892                    id: worktree.id().to_proto(),
 893                    root_name: worktree.root_name_str().to_owned(),
 894                    visible: worktree.is_visible(),
 895                    abs_path: worktree.abs_path().to_string_lossy().into_owned(),
 896                }
 897            })
 898            .collect()
 899    }
 900
 901    pub fn shared(
 902        &mut self,
 903        remote_id: u64,
 904        downstream_client: AnyProtoClient,
 905        cx: &mut Context<Self>,
 906    ) {
 907        self.retain_worktrees = true;
 908        self.downstream_client = Some((downstream_client, remote_id));
 909
 910        // When shared, retain all worktrees
 911        for worktree_handle in self.worktrees.iter_mut() {
 912            match worktree_handle {
 913                WorktreeHandle::Strong(_) => {}
 914                WorktreeHandle::Weak(worktree) => {
 915                    if let Some(worktree) = worktree.upgrade() {
 916                        *worktree_handle = WorktreeHandle::Strong(worktree);
 917                    }
 918                }
 919            }
 920        }
 921        self.send_project_updates(cx);
 922    }
 923
 924    pub fn unshared(&mut self, cx: &mut Context<Self>) {
 925        self.retain_worktrees = false;
 926        self.downstream_client.take();
 927
 928        // When not shared, only retain the visible worktrees
 929        for worktree_handle in self.worktrees.iter_mut() {
 930            if let WorktreeHandle::Strong(worktree) = worktree_handle {
 931                let is_visible = worktree.update(cx, |worktree, _| {
 932                    worktree.stop_observing_updates();
 933                    worktree.is_visible()
 934                });
 935                if !is_visible {
 936                    *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
 937                }
 938            }
 939        }
 940    }
 941
 942    pub async fn handle_create_project_entry(
 943        this: Entity<Self>,
 944        envelope: TypedEnvelope<proto::CreateProjectEntry>,
 945        mut cx: AsyncApp,
 946    ) -> Result<proto::ProjectEntryResponse> {
 947        let worktree = this.update(&mut cx, |this, cx| {
 948            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
 949            this.worktree_for_id(worktree_id, cx)
 950                .context("worktree not found")
 951        })??;
 952        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
 953    }
 954
 955    pub async fn handle_copy_project_entry(
 956        this: Entity<Self>,
 957        envelope: TypedEnvelope<proto::CopyProjectEntry>,
 958        mut cx: AsyncApp,
 959    ) -> Result<proto::ProjectEntryResponse> {
 960        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 961        let new_worktree_id = WorktreeId::from_proto(envelope.payload.new_worktree_id);
 962        let new_project_path = (
 963            new_worktree_id,
 964            RelPath::from_proto(&envelope.payload.new_path)?,
 965        );
 966        let (scan_id, entry) = this.update(&mut cx, |this, cx| {
 967            let Some((_, project_id)) = this.downstream_client else {
 968                bail!("no downstream client")
 969            };
 970            let Some(entry) = this.entry_for_id(entry_id, cx) else {
 971                bail!("no such entry");
 972            };
 973            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
 974                bail!("entry is private")
 975            }
 976
 977            let new_worktree = this
 978                .worktree_for_id(new_worktree_id, cx)
 979                .context("no such worktree")?;
 980            let scan_id = new_worktree.read(cx).scan_id();
 981            anyhow::Ok((
 982                scan_id,
 983                this.copy_entry(entry_id, new_project_path.into(), cx),
 984            ))
 985        })??;
 986        let entry = entry.await?;
 987        Ok(proto::ProjectEntryResponse {
 988            entry: entry.as_ref().map(|entry| entry.into()),
 989            worktree_scan_id: scan_id as u64,
 990        })
 991    }
 992
 993    pub async fn handle_delete_project_entry(
 994        this: Entity<Self>,
 995        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
 996        mut cx: AsyncApp,
 997    ) -> Result<proto::ProjectEntryResponse> {
 998        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
 999        let worktree = this.update(&mut cx, |this, cx| {
1000            let Some((_, project_id)) = this.downstream_client else {
1001                bail!("no downstream client")
1002            };
1003            let Some(entry) = this.entry_for_id(entry_id, cx) else {
1004                bail!("no entry")
1005            };
1006            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1007                bail!("entry is private")
1008            }
1009            this.worktree_for_entry(entry_id, cx)
1010                .context("worktree not found")
1011        })??;
1012        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
1013    }
1014
1015    pub async fn handle_rename_project_entry(
1016        this: Entity<Self>,
1017        request: proto::RenameProjectEntry,
1018        mut cx: AsyncApp,
1019    ) -> Result<proto::ProjectEntryResponse> {
1020        let entry_id = ProjectEntryId::from_proto(request.entry_id);
1021        let new_worktree_id = WorktreeId::from_proto(request.new_worktree_id);
1022        let rel_path = RelPath::from_proto(&request.new_path)
1023            .with_context(|| format!("received invalid relative path {:?}", &request.new_path))?;
1024
1025        let (scan_id, task) = this.update(&mut cx, |this, cx| {
1026            let worktree = this
1027                .worktree_for_entry(entry_id, cx)
1028                .context("no such worktree")?;
1029
1030            let Some((_, project_id)) = this.downstream_client else {
1031                bail!("no downstream client")
1032            };
1033            let entry = worktree
1034                .read(cx)
1035                .entry_for_id(entry_id)
1036                .ok_or_else(|| anyhow!("missing entry"))?;
1037            if entry.is_private && project_id != REMOTE_SERVER_PROJECT_ID {
1038                bail!("entry is private")
1039            }
1040
1041            let scan_id = worktree.read(cx).scan_id();
1042            anyhow::Ok((
1043                scan_id,
1044                this.rename_entry(entry_id, (new_worktree_id, rel_path).into(), cx),
1045            ))
1046        })??;
1047        Ok(proto::ProjectEntryResponse {
1048            entry: match &task.await? {
1049                CreatedEntry::Included(entry) => Some(entry.into()),
1050                CreatedEntry::Excluded { .. } => None,
1051            },
1052            worktree_scan_id: scan_id as u64,
1053        })
1054    }
1055
1056    pub async fn handle_expand_project_entry(
1057        this: Entity<Self>,
1058        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
1059        mut cx: AsyncApp,
1060    ) -> Result<proto::ExpandProjectEntryResponse> {
1061        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1062        let worktree = this
1063            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1064            .context("invalid request")?;
1065        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
1066    }
1067
1068    pub async fn handle_expand_all_for_project_entry(
1069        this: Entity<Self>,
1070        envelope: TypedEnvelope<proto::ExpandAllForProjectEntry>,
1071        mut cx: AsyncApp,
1072    ) -> Result<proto::ExpandAllForProjectEntryResponse> {
1073        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
1074        let worktree = this
1075            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
1076            .context("invalid request")?;
1077        Worktree::handle_expand_all_for_entry(worktree, envelope.payload, cx).await
1078    }
1079
1080    pub fn fs(&self) -> Option<Arc<dyn Fs>> {
1081        match &self.state {
1082            WorktreeStoreState::Local { fs } => Some(fs.clone()),
1083            WorktreeStoreState::Remote { .. } => None,
1084        }
1085    }
1086}
1087
1088#[derive(Clone, Debug)]
1089enum WorktreeHandle {
1090    Strong(Entity<Worktree>),
1091    Weak(WeakEntity<Worktree>),
1092}
1093
1094impl WorktreeHandle {
1095    fn upgrade(&self) -> Option<Entity<Worktree>> {
1096        match self {
1097            WorktreeHandle::Strong(handle) => Some(handle.clone()),
1098            WorktreeHandle::Weak(handle) => handle.upgrade(),
1099        }
1100    }
1101}