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