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