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