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