worktree_store.rs

  1use std::{
  2    cell::RefCell,
  3    path::{Path, PathBuf},
  4    sync::{atomic::AtomicUsize, Arc},
  5};
  6
  7use anyhow::{anyhow, Context as _, Result};
  8use client::DevServerProjectId;
  9use collections::{HashMap, HashSet};
 10use fs::Fs;
 11use futures::{
 12    future::{BoxFuture, Shared},
 13    FutureExt, SinkExt,
 14};
 15use gpui::{
 16    AppContext, AsyncAppContext, EntityId, EventEmitter, Model, ModelContext, Task, WeakModel,
 17};
 18use postage::oneshot;
 19use rpc::{
 20    proto::{self, SSH_PROJECT_ID},
 21    AnyProtoClient, TypedEnvelope,
 22};
 23use smol::{
 24    channel::{Receiver, Sender},
 25    stream::StreamExt,
 26};
 27use text::ReplicaId;
 28use util::{paths::compare_paths, ResultExt};
 29use worktree::{Entry, ProjectEntryId, Worktree, WorktreeId, WorktreeSettings};
 30
 31use crate::{search::SearchQuery, ProjectPath};
 32
 33struct MatchingEntry {
 34    worktree_path: Arc<Path>,
 35    path: ProjectPath,
 36    respond: oneshot::Sender<ProjectPath>,
 37}
 38
 39pub struct WorktreeStore {
 40    next_entry_id: Arc<AtomicUsize>,
 41    upstream_client: Option<AnyProtoClient>,
 42    downstream_client: Option<AnyProtoClient>,
 43    remote_id: u64,
 44    dev_server_project_id: Option<DevServerProjectId>,
 45    retain_worktrees: bool,
 46    worktrees: Vec<WorktreeHandle>,
 47    worktrees_reordered: bool,
 48    #[allow(clippy::type_complexity)]
 49    loading_worktrees:
 50        HashMap<Arc<Path>, Shared<Task<Result<Model<Worktree>, Arc<anyhow::Error>>>>>,
 51    fs: Arc<dyn Fs>,
 52}
 53
 54pub enum WorktreeStoreEvent {
 55    WorktreeAdded(Model<Worktree>),
 56    WorktreeRemoved(EntityId, WorktreeId),
 57    WorktreeOrderChanged,
 58    WorktreeUpdateSent(Model<Worktree>),
 59}
 60
 61impl EventEmitter<WorktreeStoreEvent> for WorktreeStore {}
 62
 63impl WorktreeStore {
 64    pub fn init(client: &AnyProtoClient) {
 65        client.add_model_request_handler(Self::handle_create_project_entry);
 66        client.add_model_request_handler(Self::handle_rename_project_entry);
 67        client.add_model_request_handler(Self::handle_copy_project_entry);
 68        client.add_model_request_handler(Self::handle_delete_project_entry);
 69        client.add_model_request_handler(Self::handle_expand_project_entry);
 70    }
 71
 72    pub fn new(
 73        upstream_client: Option<AnyProtoClient>,
 74        retain_worktrees: bool,
 75        fs: Arc<dyn Fs>,
 76    ) -> Self {
 77        Self {
 78            next_entry_id: Default::default(),
 79            loading_worktrees: Default::default(),
 80            dev_server_project_id: None,
 81            downstream_client: None,
 82            worktrees: Vec::new(),
 83            worktrees_reordered: false,
 84            retain_worktrees,
 85            remote_id: 0,
 86            upstream_client,
 87            fs,
 88        }
 89    }
 90
 91    pub fn set_dev_server_project_id(&mut self, id: DevServerProjectId) {
 92        self.dev_server_project_id = Some(id);
 93    }
 94
 95    /// Iterates through all worktrees, including ones that don't appear in the project panel
 96    pub fn worktrees(&self) -> impl '_ + DoubleEndedIterator<Item = Model<Worktree>> {
 97        self.worktrees
 98            .iter()
 99            .filter_map(move |worktree| worktree.upgrade())
100    }
101
102    /// Iterates through all user-visible worktrees, the ones that appear in the project panel.
103    pub fn visible_worktrees<'a>(
104        &'a self,
105        cx: &'a AppContext,
106    ) -> impl 'a + DoubleEndedIterator<Item = Model<Worktree>> {
107        self.worktrees()
108            .filter(|worktree| worktree.read(cx).is_visible())
109    }
110
111    pub fn worktree_for_id(&self, id: WorktreeId, cx: &AppContext) -> Option<Model<Worktree>> {
112        self.worktrees()
113            .find(|worktree| worktree.read(cx).id() == id)
114    }
115
116    pub fn worktree_for_entry(
117        &self,
118        entry_id: ProjectEntryId,
119        cx: &AppContext,
120    ) -> Option<Model<Worktree>> {
121        self.worktrees()
122            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
123    }
124
125    pub fn find_worktree(
126        &self,
127        abs_path: &Path,
128        cx: &AppContext,
129    ) -> Option<(Model<Worktree>, PathBuf)> {
130        for tree in self.worktrees() {
131            if let Ok(relative_path) = abs_path.strip_prefix(tree.read(cx).abs_path()) {
132                return Some((tree.clone(), relative_path.into()));
133            }
134        }
135        None
136    }
137
138    pub fn entry_for_id<'a>(
139        &'a self,
140        entry_id: ProjectEntryId,
141        cx: &'a AppContext,
142    ) -> Option<&'a Entry> {
143        self.worktrees()
144            .find_map(|worktree| worktree.read(cx).entry_for_id(entry_id))
145    }
146
147    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
148        self.worktree_for_id(path.worktree_id, cx)?
149            .read(cx)
150            .entry_for_path(&path.path)
151            .cloned()
152    }
153
154    pub fn create_worktree(
155        &mut self,
156        abs_path: impl AsRef<Path>,
157        visible: bool,
158        cx: &mut ModelContext<Self>,
159    ) -> Task<Result<Model<Worktree>>> {
160        let path: Arc<Path> = abs_path.as_ref().into();
161        if !self.loading_worktrees.contains_key(&path) {
162            let task = if let Some(client) = self.upstream_client.clone() {
163                if let Some(dev_server_project_id) = self.dev_server_project_id {
164                    self.create_dev_server_worktree(client, dev_server_project_id, abs_path, cx)
165                } else {
166                    self.create_ssh_worktree(client, abs_path, visible, cx)
167                }
168            } else {
169                self.create_local_worktree(abs_path, visible, cx)
170            };
171
172            self.loading_worktrees.insert(path.clone(), task.shared());
173        }
174        let task = self.loading_worktrees.get(&path).unwrap().clone();
175        cx.background_executor().spawn(async move {
176            match task.await {
177                Ok(worktree) => Ok(worktree),
178                Err(err) => Err(anyhow!("{}", err)),
179            }
180        })
181    }
182
183    fn create_ssh_worktree(
184        &mut self,
185        client: AnyProtoClient,
186        abs_path: impl AsRef<Path>,
187        visible: bool,
188        cx: &mut ModelContext<Self>,
189    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
190        let mut abs_path = abs_path.as_ref().to_string_lossy().to_string();
191        // If we start with `/~` that means the ssh path was something like `ssh://user@host/~/home-dir-folder/`
192        // in which case want to strip the leading the `/` and expand the tilde.
193        // That's what git does too: https://github.com/libgit2/libgit2/issues/3345#issuecomment-127050850
194        if abs_path.starts_with("/~") {
195            abs_path = shellexpand::tilde(&abs_path[1..]).to_string();
196        }
197        let root_name = PathBuf::from(abs_path.clone())
198            .file_name()
199            .unwrap()
200            .to_string_lossy()
201            .to_string();
202        cx.spawn(|this, mut cx| async move {
203            let response = client
204                .request(proto::AddWorktree {
205                    project_id: SSH_PROJECT_ID,
206                    path: abs_path.clone(),
207                })
208                .await?;
209
210            if let Some(existing_worktree) = this.read_with(&cx, |this, cx| {
211                this.worktree_for_id(WorktreeId::from_proto(response.worktree_id), cx)
212            })? {
213                return Ok(existing_worktree);
214            }
215
216            let worktree = cx.update(|cx| {
217                Worktree::remote(
218                    0,
219                    0,
220                    proto::WorktreeMetadata {
221                        id: response.worktree_id,
222                        root_name,
223                        visible,
224                        abs_path,
225                    },
226                    client,
227                    cx,
228                )
229            })?;
230
231            this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
232
233            Ok(worktree)
234        })
235    }
236
237    fn create_local_worktree(
238        &mut self,
239        abs_path: impl AsRef<Path>,
240        visible: bool,
241        cx: &mut ModelContext<Self>,
242    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
243        let fs = self.fs.clone();
244        let next_entry_id = self.next_entry_id.clone();
245        let path: Arc<Path> = abs_path.as_ref().into();
246
247        cx.spawn(move |this, mut cx| async move {
248            let worktree = Worktree::local(path.clone(), visible, fs, next_entry_id, &mut cx).await;
249
250            this.update(&mut cx, |project, _| {
251                project.loading_worktrees.remove(&path);
252            })?;
253
254            let worktree = worktree?;
255            this.update(&mut cx, |this, cx| this.add(&worktree, cx))?;
256
257            if visible {
258                cx.update(|cx| {
259                    cx.add_recent_document(&path);
260                })
261                .log_err();
262            }
263
264            Ok(worktree)
265        })
266    }
267
268    fn create_dev_server_worktree(
269        &mut self,
270        client: AnyProtoClient,
271        dev_server_project_id: DevServerProjectId,
272        abs_path: impl AsRef<Path>,
273        cx: &mut ModelContext<Self>,
274    ) -> Task<Result<Model<Worktree>, Arc<anyhow::Error>>> {
275        let path: Arc<Path> = abs_path.as_ref().into();
276        let mut paths: Vec<String> = self
277            .visible_worktrees(cx)
278            .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().to_string())
279            .collect();
280        paths.push(path.to_string_lossy().to_string());
281        let request = client.request(proto::UpdateDevServerProject {
282            dev_server_project_id: dev_server_project_id.0,
283            paths,
284        });
285
286        let abs_path = abs_path.as_ref().to_path_buf();
287        cx.spawn(move |project, mut cx| async move {
288            let (tx, rx) = futures::channel::oneshot::channel();
289            let tx = RefCell::new(Some(tx));
290            let Some(project) = project.upgrade() else {
291                return Err(anyhow!("project dropped"))?;
292            };
293            let observer = cx.update(|cx| {
294                cx.observe(&project, move |project, cx| {
295                    let abs_path = abs_path.clone();
296                    project.update(cx, |project, cx| {
297                        if let Some((worktree, _)) = project.find_worktree(&abs_path, cx) {
298                            if let Some(tx) = tx.borrow_mut().take() {
299                                tx.send(worktree).ok();
300                            }
301                        }
302                    })
303                })
304            })?;
305
306            request.await?;
307            let worktree = rx.await.map_err(|e| anyhow!(e))?;
308            drop(observer);
309            project.update(&mut cx, |project, _| {
310                project.loading_worktrees.remove(&path);
311            })?;
312            Ok(worktree)
313        })
314    }
315
316    pub fn add(&mut self, worktree: &Model<Worktree>, cx: &mut ModelContext<Self>) {
317        let worktree_id = worktree.read(cx).id();
318        debug_assert!(!self.worktrees().any(|w| w.read(cx).id() == worktree_id));
319
320        let push_strong_handle = self.retain_worktrees || worktree.read(cx).is_visible();
321        let handle = if push_strong_handle {
322            WorktreeHandle::Strong(worktree.clone())
323        } else {
324            WorktreeHandle::Weak(worktree.downgrade())
325        };
326        if self.worktrees_reordered {
327            self.worktrees.push(handle);
328        } else {
329            let i = match self
330                .worktrees
331                .binary_search_by_key(&Some(worktree.read(cx).abs_path()), |other| {
332                    other.upgrade().map(|worktree| worktree.read(cx).abs_path())
333                }) {
334                Ok(i) | Err(i) => i,
335            };
336            self.worktrees.insert(i, handle);
337        }
338
339        cx.emit(WorktreeStoreEvent::WorktreeAdded(worktree.clone()));
340        self.send_project_updates(cx);
341
342        let handle_id = worktree.entity_id();
343        cx.observe_release(worktree, move |this, worktree, cx| {
344            cx.emit(WorktreeStoreEvent::WorktreeRemoved(
345                handle_id,
346                worktree.id(),
347            ));
348            this.send_project_updates(cx);
349        })
350        .detach();
351    }
352
353    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
354        self.worktrees.retain(|worktree| {
355            if let Some(worktree) = worktree.upgrade() {
356                if worktree.read(cx).id() == id_to_remove {
357                    cx.emit(WorktreeStoreEvent::WorktreeRemoved(
358                        worktree.entity_id(),
359                        id_to_remove,
360                    ));
361                    false
362                } else {
363                    true
364                }
365            } else {
366                false
367            }
368        });
369        self.send_project_updates(cx);
370    }
371
372    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool) {
373        self.worktrees_reordered = worktrees_reordered;
374    }
375
376    pub fn set_worktrees_from_proto(
377        &mut self,
378        worktrees: Vec<proto::WorktreeMetadata>,
379        replica_id: ReplicaId,
380        cx: &mut ModelContext<Self>,
381    ) -> Result<()> {
382        let mut old_worktrees_by_id = self
383            .worktrees
384            .drain(..)
385            .filter_map(|worktree| {
386                let worktree = worktree.upgrade()?;
387                Some((worktree.read(cx).id(), worktree))
388            })
389            .collect::<HashMap<_, _>>();
390
391        let client = self
392            .upstream_client
393            .clone()
394            .ok_or_else(|| anyhow!("invalid project"))?;
395
396        for worktree in worktrees {
397            if let Some(old_worktree) =
398                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
399            {
400                let push_strong_handle =
401                    self.retain_worktrees || old_worktree.read(cx).is_visible();
402                let handle = if push_strong_handle {
403                    WorktreeHandle::Strong(old_worktree.clone())
404                } else {
405                    WorktreeHandle::Weak(old_worktree.downgrade())
406                };
407                self.worktrees.push(handle);
408            } else {
409                self.add(
410                    &Worktree::remote(self.remote_id, replica_id, worktree, client.clone(), cx),
411                    cx,
412                );
413            }
414        }
415        self.send_project_updates(cx);
416
417        Ok(())
418    }
419
420    pub fn move_worktree(
421        &mut self,
422        source: WorktreeId,
423        destination: WorktreeId,
424        cx: &mut ModelContext<Self>,
425    ) -> Result<()> {
426        if source == destination {
427            return Ok(());
428        }
429
430        let mut source_index = None;
431        let mut destination_index = None;
432        for (i, worktree) in self.worktrees.iter().enumerate() {
433            if let Some(worktree) = worktree.upgrade() {
434                let worktree_id = worktree.read(cx).id();
435                if worktree_id == source {
436                    source_index = Some(i);
437                    if destination_index.is_some() {
438                        break;
439                    }
440                } else if worktree_id == destination {
441                    destination_index = Some(i);
442                    if source_index.is_some() {
443                        break;
444                    }
445                }
446            }
447        }
448
449        let source_index =
450            source_index.with_context(|| format!("Missing worktree for id {source}"))?;
451        let destination_index =
452            destination_index.with_context(|| format!("Missing worktree for id {destination}"))?;
453
454        if source_index == destination_index {
455            return Ok(());
456        }
457
458        let worktree_to_move = self.worktrees.remove(source_index);
459        self.worktrees.insert(destination_index, worktree_to_move);
460        self.worktrees_reordered = true;
461        cx.emit(WorktreeStoreEvent::WorktreeOrderChanged);
462        cx.notify();
463        Ok(())
464    }
465
466    pub fn disconnected_from_host(&mut self, cx: &mut AppContext) {
467        for worktree in &self.worktrees {
468            if let Some(worktree) = worktree.upgrade() {
469                worktree.update(cx, |worktree, _| {
470                    if let Some(worktree) = worktree.as_remote_mut() {
471                        worktree.disconnected_from_host();
472                    }
473                });
474            }
475        }
476    }
477
478    pub fn send_project_updates(&mut self, cx: &mut ModelContext<Self>) {
479        let Some(downstream_client) = self.downstream_client.clone() else {
480            return;
481        };
482        let project_id = self.remote_id;
483
484        let update = proto::UpdateProject {
485            project_id,
486            worktrees: self.worktree_metadata_protos(cx),
487        };
488
489        // collab has bad concurrency guarantees, so we send requests in serial.
490        let update_project = if downstream_client.goes_via_collab() {
491            Some(downstream_client.request(update))
492        } else {
493            downstream_client.send(update).log_err();
494            None
495        };
496        cx.spawn(|this, mut cx| async move {
497            if let Some(update_project) = update_project {
498                update_project.await?;
499            }
500
501            this.update(&mut cx, |this, cx| {
502                let worktrees = this.worktrees().collect::<Vec<_>>();
503
504                for worktree in worktrees {
505                    worktree.update(cx, |worktree, cx| {
506                        let client = downstream_client.clone();
507                        worktree.observe_updates(project_id, cx, {
508                            move |update| {
509                                let client = client.clone();
510                                async move {
511                                    if client.goes_via_collab() {
512                                        client.request(update).map(|result| result.is_ok()).await
513                                    } else {
514                                        client.send(update).is_ok()
515                                    }
516                                }
517                            }
518                        });
519                    });
520
521                    cx.emit(WorktreeStoreEvent::WorktreeUpdateSent(worktree.clone()))
522                }
523
524                anyhow::Ok(())
525            })
526        })
527        .detach_and_log_err(cx);
528    }
529
530    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
531        self.worktrees()
532            .map(|worktree| {
533                let worktree = worktree.read(cx);
534                proto::WorktreeMetadata {
535                    id: worktree.id().to_proto(),
536                    root_name: worktree.root_name().into(),
537                    visible: worktree.is_visible(),
538                    abs_path: worktree.abs_path().to_string_lossy().into(),
539                }
540            })
541            .collect()
542    }
543
544    pub fn shared(
545        &mut self,
546        remote_id: u64,
547        downsteam_client: AnyProtoClient,
548        cx: &mut ModelContext<Self>,
549    ) {
550        self.retain_worktrees = true;
551        self.remote_id = remote_id;
552        self.downstream_client = Some(downsteam_client);
553
554        // When shared, retain all worktrees
555        for worktree_handle in self.worktrees.iter_mut() {
556            match worktree_handle {
557                WorktreeHandle::Strong(_) => {}
558                WorktreeHandle::Weak(worktree) => {
559                    if let Some(worktree) = worktree.upgrade() {
560                        *worktree_handle = WorktreeHandle::Strong(worktree);
561                    }
562                }
563            }
564        }
565        self.send_project_updates(cx);
566    }
567
568    pub fn unshared(&mut self, cx: &mut ModelContext<Self>) {
569        self.retain_worktrees = false;
570        self.downstream_client.take();
571
572        // When not shared, only retain the visible worktrees
573        for worktree_handle in self.worktrees.iter_mut() {
574            if let WorktreeHandle::Strong(worktree) = worktree_handle {
575                let is_visible = worktree.update(cx, |worktree, _| {
576                    worktree.stop_observing_updates();
577                    worktree.is_visible()
578                });
579                if !is_visible {
580                    *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
581                }
582            }
583        }
584    }
585
586    /// search over all worktrees and return buffers that *might* match the search.
587    pub fn find_search_candidates(
588        &self,
589        query: SearchQuery,
590        limit: usize,
591        open_entries: HashSet<ProjectEntryId>,
592        fs: Arc<dyn Fs>,
593        cx: &ModelContext<Self>,
594    ) -> Receiver<ProjectPath> {
595        let snapshots = self
596            .visible_worktrees(cx)
597            .filter_map(|tree| {
598                let tree = tree.read(cx);
599                Some((tree.snapshot(), tree.as_local()?.settings()))
600            })
601            .collect::<Vec<_>>();
602
603        let executor = cx.background_executor().clone();
604
605        // We want to return entries in the order they are in the worktrees, so we have one
606        // thread that iterates over the worktrees (and ignored directories) as necessary,
607        // and pushes a oneshot::Receiver to the output channel and a oneshot::Sender to the filter
608        // channel.
609        // We spawn a number of workers that take items from the filter channel and check the query
610        // against the version of the file on disk.
611        let (filter_tx, filter_rx) = smol::channel::bounded(64);
612        let (output_tx, mut output_rx) = smol::channel::bounded(64);
613        let (matching_paths_tx, matching_paths_rx) = smol::channel::unbounded();
614
615        let input = cx.background_executor().spawn({
616            let fs = fs.clone();
617            let query = query.clone();
618            async move {
619                Self::find_candidate_paths(
620                    fs,
621                    snapshots,
622                    open_entries,
623                    query,
624                    filter_tx,
625                    output_tx,
626                )
627                .await
628                .log_err();
629            }
630        });
631        const MAX_CONCURRENT_FILE_SCANS: usize = 64;
632        let filters = cx.background_executor().spawn(async move {
633            let fs = &fs;
634            let query = &query;
635            executor
636                .scoped(move |scope| {
637                    for _ in 0..MAX_CONCURRENT_FILE_SCANS {
638                        let filter_rx = filter_rx.clone();
639                        scope.spawn(async move {
640                            Self::filter_paths(fs, filter_rx, query).await.log_err();
641                        })
642                    }
643                })
644                .await;
645        });
646        cx.background_executor()
647            .spawn(async move {
648                let mut matched = 0;
649                while let Some(mut receiver) = output_rx.next().await {
650                    let Some(path) = receiver.next().await else {
651                        continue;
652                    };
653                    let Ok(_) = matching_paths_tx.send(path).await else {
654                        break;
655                    };
656                    matched += 1;
657                    if matched == limit {
658                        break;
659                    }
660                }
661                drop(input);
662                drop(filters);
663            })
664            .detach();
665        matching_paths_rx
666    }
667
668    fn scan_ignored_dir<'a>(
669        fs: &'a Arc<dyn Fs>,
670        snapshot: &'a worktree::Snapshot,
671        path: &'a Path,
672        query: &'a SearchQuery,
673        include_root: bool,
674        filter_tx: &'a Sender<MatchingEntry>,
675        output_tx: &'a Sender<oneshot::Receiver<ProjectPath>>,
676    ) -> BoxFuture<'a, Result<()>> {
677        async move {
678            let abs_path = snapshot.abs_path().join(path);
679            let Some(mut files) = fs
680                .read_dir(&abs_path)
681                .await
682                .with_context(|| format!("listing ignored path {abs_path:?}"))
683                .log_err()
684            else {
685                return Ok(());
686            };
687
688            let mut results = Vec::new();
689
690            while let Some(Ok(file)) = files.next().await {
691                let Some(metadata) = fs
692                    .metadata(&file)
693                    .await
694                    .with_context(|| format!("fetching fs metadata for {abs_path:?}"))
695                    .log_err()
696                    .flatten()
697                else {
698                    continue;
699                };
700                if metadata.is_symlink || metadata.is_fifo {
701                    continue;
702                }
703                results.push((
704                    file.strip_prefix(snapshot.abs_path())?.to_path_buf(),
705                    !metadata.is_dir,
706                ))
707            }
708            results.sort_by(|(a_path, a_is_file), (b_path, b_is_file)| {
709                compare_paths((a_path, *a_is_file), (b_path, *b_is_file))
710            });
711            for (path, is_file) in results {
712                if is_file {
713                    if query.filters_path() {
714                        let matched_path = if include_root {
715                            let mut full_path = PathBuf::from(snapshot.root_name());
716                            full_path.push(&path);
717                            query.file_matches(&full_path)
718                        } else {
719                            query.file_matches(&path)
720                        };
721                        if !matched_path {
722                            continue;
723                        }
724                    }
725                    let (tx, rx) = oneshot::channel();
726                    output_tx.send(rx).await?;
727                    filter_tx
728                        .send(MatchingEntry {
729                            respond: tx,
730                            worktree_path: snapshot.abs_path().clone(),
731                            path: ProjectPath {
732                                worktree_id: snapshot.id(),
733                                path: Arc::from(path),
734                            },
735                        })
736                        .await?;
737                } else {
738                    Self::scan_ignored_dir(
739                        fs,
740                        snapshot,
741                        &path,
742                        query,
743                        include_root,
744                        filter_tx,
745                        output_tx,
746                    )
747                    .await?;
748                }
749            }
750            Ok(())
751        }
752        .boxed()
753    }
754
755    async fn find_candidate_paths(
756        fs: Arc<dyn Fs>,
757        snapshots: Vec<(worktree::Snapshot, WorktreeSettings)>,
758        open_entries: HashSet<ProjectEntryId>,
759        query: SearchQuery,
760        filter_tx: Sender<MatchingEntry>,
761        output_tx: Sender<oneshot::Receiver<ProjectPath>>,
762    ) -> Result<()> {
763        let include_root = snapshots.len() > 1;
764        for (snapshot, settings) in snapshots {
765            let mut entries: Vec<_> = snapshot.entries(query.include_ignored(), 0).collect();
766            entries.sort_by(|a, b| compare_paths((&a.path, a.is_file()), (&b.path, b.is_file())));
767            for entry in entries {
768                if entry.is_dir() && entry.is_ignored {
769                    if !settings.is_path_excluded(&entry.path) {
770                        Self::scan_ignored_dir(
771                            &fs,
772                            &snapshot,
773                            &entry.path,
774                            &query,
775                            include_root,
776                            &filter_tx,
777                            &output_tx,
778                        )
779                        .await?;
780                    }
781                    continue;
782                }
783
784                if entry.is_fifo || !entry.is_file() {
785                    continue;
786                }
787
788                if query.filters_path() {
789                    let matched_path = if include_root {
790                        let mut full_path = PathBuf::from(snapshot.root_name());
791                        full_path.push(&entry.path);
792                        query.file_matches(&full_path)
793                    } else {
794                        query.file_matches(&entry.path)
795                    };
796                    if !matched_path {
797                        continue;
798                    }
799                }
800
801                let (mut tx, rx) = oneshot::channel();
802
803                if open_entries.contains(&entry.id) {
804                    tx.send(ProjectPath {
805                        worktree_id: snapshot.id(),
806                        path: entry.path.clone(),
807                    })
808                    .await?;
809                } else {
810                    filter_tx
811                        .send(MatchingEntry {
812                            respond: tx,
813                            worktree_path: snapshot.abs_path().clone(),
814                            path: ProjectPath {
815                                worktree_id: snapshot.id(),
816                                path: entry.path.clone(),
817                            },
818                        })
819                        .await?;
820                }
821
822                output_tx.send(rx).await?;
823            }
824        }
825        Ok(())
826    }
827
828    async fn filter_paths(
829        fs: &Arc<dyn Fs>,
830        mut input: Receiver<MatchingEntry>,
831        query: &SearchQuery,
832    ) -> Result<()> {
833        while let Some(mut entry) = input.next().await {
834            let abs_path = entry.worktree_path.join(&entry.path.path);
835            let Some(file) = fs.open_sync(&abs_path).await.log_err() else {
836                continue;
837            };
838            if query.detect(file).unwrap_or(false) {
839                entry.respond.send(entry.path).await?
840            }
841        }
842
843        Ok(())
844    }
845
846    pub async fn handle_create_project_entry(
847        this: Model<Self>,
848        envelope: TypedEnvelope<proto::CreateProjectEntry>,
849        mut cx: AsyncAppContext,
850    ) -> Result<proto::ProjectEntryResponse> {
851        let worktree = this.update(&mut cx, |this, cx| {
852            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
853            this.worktree_for_id(worktree_id, cx)
854                .ok_or_else(|| anyhow!("worktree not found"))
855        })??;
856        Worktree::handle_create_entry(worktree, envelope.payload, cx).await
857    }
858
859    pub async fn handle_rename_project_entry(
860        this: Model<Self>,
861        envelope: TypedEnvelope<proto::RenameProjectEntry>,
862        mut cx: AsyncAppContext,
863    ) -> Result<proto::ProjectEntryResponse> {
864        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
865        let worktree = this.update(&mut cx, |this, cx| {
866            this.worktree_for_entry(entry_id, cx)
867                .ok_or_else(|| anyhow!("worktree not found"))
868        })??;
869        Worktree::handle_rename_entry(worktree, envelope.payload, cx).await
870    }
871
872    pub async fn handle_copy_project_entry(
873        this: Model<Self>,
874        envelope: TypedEnvelope<proto::CopyProjectEntry>,
875        mut cx: AsyncAppContext,
876    ) -> Result<proto::ProjectEntryResponse> {
877        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
878        let worktree = this.update(&mut cx, |this, cx| {
879            this.worktree_for_entry(entry_id, cx)
880                .ok_or_else(|| anyhow!("worktree not found"))
881        })??;
882        Worktree::handle_copy_entry(worktree, envelope.payload, cx).await
883    }
884
885    pub async fn handle_delete_project_entry(
886        this: Model<Self>,
887        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
888        mut cx: AsyncAppContext,
889    ) -> Result<proto::ProjectEntryResponse> {
890        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
891        let worktree = this.update(&mut cx, |this, cx| {
892            this.worktree_for_entry(entry_id, cx)
893                .ok_or_else(|| anyhow!("worktree not found"))
894        })??;
895        Worktree::handle_delete_entry(worktree, envelope.payload, cx).await
896    }
897
898    pub async fn handle_expand_project_entry(
899        this: Model<Self>,
900        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
901        mut cx: AsyncAppContext,
902    ) -> Result<proto::ExpandProjectEntryResponse> {
903        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
904        let worktree = this
905            .update(&mut cx, |this, cx| this.worktree_for_entry(entry_id, cx))?
906            .ok_or_else(|| anyhow!("invalid request"))?;
907        Worktree::handle_expand_entry(worktree, envelope.payload, cx).await
908    }
909}
910
911#[derive(Clone)]
912enum WorktreeHandle {
913    Strong(Model<Worktree>),
914    Weak(WeakModel<Worktree>),
915}
916
917impl WorktreeHandle {
918    fn upgrade(&self) -> Option<Model<Worktree>> {
919        match self {
920            WorktreeHandle::Strong(handle) => Some(handle.clone()),
921            WorktreeHandle::Weak(handle) => handle.upgrade(),
922        }
923    }
924}