1pub mod fs;
2mod ignore;
3mod worktree;
4
5use anyhow::{anyhow, Result};
6use client::{proto, Client, PeerId, TypedEnvelope, User, UserStore};
7use clock::ReplicaId;
8use collections::HashMap;
9use futures::Future;
10use fuzzy::{PathMatch, PathMatchCandidate, PathMatchCandidateSet};
11use gpui::{
12 AppContext, AsyncAppContext, Entity, ModelContext, ModelHandle, MutableAppContext, Task,
13};
14use language::{Buffer, DiagnosticEntry, Language, LanguageRegistry};
15use lsp::DiagnosticSeverity;
16use postage::{prelude::Stream, watch};
17use std::{
18 path::Path,
19 sync::{atomic::AtomicBool, Arc},
20};
21use util::{ResultExt, TryFutureExt as _};
22
23pub use fs::*;
24pub use worktree::*;
25
26pub struct Project {
27 worktrees: Vec<ModelHandle<Worktree>>,
28 active_entry: Option<ProjectEntry>,
29 languages: Arc<LanguageRegistry>,
30 client: Arc<client::Client>,
31 user_store: ModelHandle<UserStore>,
32 fs: Arc<dyn Fs>,
33 client_state: ProjectClientState,
34 collaborators: HashMap<PeerId, Collaborator>,
35 subscriptions: Vec<client::Subscription>,
36}
37
38enum ProjectClientState {
39 Local {
40 is_shared: bool,
41 remote_id_tx: watch::Sender<Option<u64>>,
42 remote_id_rx: watch::Receiver<Option<u64>>,
43 _maintain_remote_id_task: Task<Option<()>>,
44 },
45 Remote {
46 sharing_has_stopped: bool,
47 remote_id: u64,
48 replica_id: ReplicaId,
49 },
50}
51
52#[derive(Clone, Debug)]
53pub struct Collaborator {
54 pub user: Arc<User>,
55 pub peer_id: PeerId,
56 pub replica_id: ReplicaId,
57}
58
59#[derive(Debug)]
60pub enum Event {
61 ActiveEntryChanged(Option<ProjectEntry>),
62 WorktreeRemoved(usize),
63 DiagnosticsUpdated(ProjectPath),
64}
65
66#[derive(Clone, Debug, Eq, PartialEq, Hash)]
67pub struct ProjectPath {
68 pub worktree_id: usize,
69 pub path: Arc<Path>,
70}
71
72#[derive(Clone)]
73pub struct DiagnosticSummary {
74 pub error_count: usize,
75 pub warning_count: usize,
76 pub info_count: usize,
77 pub hint_count: usize,
78}
79
80impl DiagnosticSummary {
81 fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
82 let mut this = Self {
83 error_count: 0,
84 warning_count: 0,
85 info_count: 0,
86 hint_count: 0,
87 };
88
89 for entry in diagnostics {
90 if entry.diagnostic.is_primary {
91 match entry.diagnostic.severity {
92 DiagnosticSeverity::ERROR => this.error_count += 1,
93 DiagnosticSeverity::WARNING => this.warning_count += 1,
94 DiagnosticSeverity::INFORMATION => this.info_count += 1,
95 DiagnosticSeverity::HINT => this.hint_count += 1,
96 _ => {}
97 }
98 }
99 }
100
101 this
102 }
103}
104
105#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
106pub struct ProjectEntry {
107 pub worktree_id: usize,
108 pub entry_id: usize,
109}
110
111impl Project {
112 pub fn local(
113 client: Arc<Client>,
114 user_store: ModelHandle<UserStore>,
115 languages: Arc<LanguageRegistry>,
116 fs: Arc<dyn Fs>,
117 cx: &mut MutableAppContext,
118 ) -> ModelHandle<Self> {
119 cx.add_model(|cx: &mut ModelContext<Self>| {
120 let (remote_id_tx, remote_id_rx) = watch::channel();
121 let _maintain_remote_id_task = cx.spawn_weak({
122 let rpc = client.clone();
123 move |this, mut cx| {
124 async move {
125 let mut status = rpc.status();
126 while let Some(status) = status.recv().await {
127 if let Some(this) = this.upgrade(&cx) {
128 let remote_id = if let client::Status::Connected { .. } = status {
129 let response = rpc.request(proto::RegisterProject {}).await?;
130 Some(response.project_id)
131 } else {
132 None
133 };
134
135 if let Some(project_id) = remote_id {
136 let mut registrations = Vec::new();
137 this.read_with(&cx, |this, cx| {
138 for worktree in &this.worktrees {
139 let worktree_id = worktree.id() as u64;
140 let worktree = worktree.read(cx).as_local().unwrap();
141 registrations.push(rpc.request(
142 proto::RegisterWorktree {
143 project_id,
144 worktree_id,
145 root_name: worktree.root_name().to_string(),
146 authorized_logins: worktree.authorized_logins(),
147 },
148 ));
149 }
150 });
151 for registration in registrations {
152 registration.await?;
153 }
154 }
155 this.update(&mut cx, |this, cx| this.set_remote_id(remote_id, cx));
156 }
157 }
158 Ok(())
159 }
160 .log_err()
161 }
162 });
163
164 Self {
165 worktrees: Default::default(),
166 collaborators: Default::default(),
167 client_state: ProjectClientState::Local {
168 is_shared: false,
169 remote_id_tx,
170 remote_id_rx,
171 _maintain_remote_id_task,
172 },
173 subscriptions: Vec::new(),
174 active_entry: None,
175 languages,
176 client,
177 user_store,
178 fs,
179 }
180 })
181 }
182
183 pub async fn remote(
184 remote_id: u64,
185 client: Arc<Client>,
186 user_store: ModelHandle<UserStore>,
187 languages: Arc<LanguageRegistry>,
188 fs: Arc<dyn Fs>,
189 cx: &mut AsyncAppContext,
190 ) -> Result<ModelHandle<Self>> {
191 client.authenticate_and_connect(&cx).await?;
192
193 let response = client
194 .request(proto::JoinProject {
195 project_id: remote_id,
196 })
197 .await?;
198
199 let replica_id = response.replica_id as ReplicaId;
200
201 let mut worktrees = Vec::new();
202 for worktree in response.worktrees {
203 worktrees.push(
204 Worktree::remote(
205 remote_id,
206 replica_id,
207 worktree,
208 client.clone(),
209 user_store.clone(),
210 languages.clone(),
211 cx,
212 )
213 .await?,
214 );
215 }
216
217 let user_ids = response
218 .collaborators
219 .iter()
220 .map(|peer| peer.user_id)
221 .collect();
222 user_store
223 .update(cx, |user_store, cx| user_store.load_users(user_ids, cx))
224 .await?;
225 let mut collaborators = HashMap::default();
226 for message in response.collaborators {
227 let collaborator = Collaborator::from_proto(message, &user_store, cx).await?;
228 collaborators.insert(collaborator.peer_id, collaborator);
229 }
230
231 Ok(cx.add_model(|cx| Self {
232 worktrees,
233 active_entry: None,
234 collaborators,
235 languages,
236 user_store,
237 fs,
238 subscriptions: vec![
239 client.subscribe_to_entity(remote_id, cx, Self::handle_unshare_project),
240 client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
241 client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
242 client.subscribe_to_entity(remote_id, cx, Self::handle_share_worktree),
243 client.subscribe_to_entity(remote_id, cx, Self::handle_unregister_worktree),
244 client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
245 client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
246 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
247 ],
248 client,
249 client_state: ProjectClientState::Remote {
250 sharing_has_stopped: false,
251 remote_id,
252 replica_id,
253 },
254 }))
255 }
256
257 fn set_remote_id(&mut self, remote_id: Option<u64>, cx: &mut ModelContext<Self>) {
258 if let ProjectClientState::Local { remote_id_tx, .. } = &mut self.client_state {
259 *remote_id_tx.borrow_mut() = remote_id;
260 }
261
262 self.subscriptions.clear();
263 if let Some(remote_id) = remote_id {
264 let client = &self.client;
265 self.subscriptions.extend([
266 client.subscribe_to_entity(remote_id, cx, Self::handle_open_buffer),
267 client.subscribe_to_entity(remote_id, cx, Self::handle_close_buffer),
268 client.subscribe_to_entity(remote_id, cx, Self::handle_add_collaborator),
269 client.subscribe_to_entity(remote_id, cx, Self::handle_remove_collaborator),
270 client.subscribe_to_entity(remote_id, cx, Self::handle_update_worktree),
271 client.subscribe_to_entity(remote_id, cx, Self::handle_update_buffer),
272 client.subscribe_to_entity(remote_id, cx, Self::handle_save_buffer),
273 client.subscribe_to_entity(remote_id, cx, Self::handle_buffer_saved),
274 ]);
275 }
276 }
277
278 pub fn remote_id(&self) -> Option<u64> {
279 match &self.client_state {
280 ProjectClientState::Local { remote_id_rx, .. } => *remote_id_rx.borrow(),
281 ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
282 }
283 }
284
285 pub fn next_remote_id(&self) -> impl Future<Output = u64> {
286 let mut id = None;
287 let mut watch = None;
288 match &self.client_state {
289 ProjectClientState::Local { remote_id_rx, .. } => watch = Some(remote_id_rx.clone()),
290 ProjectClientState::Remote { remote_id, .. } => id = Some(*remote_id),
291 }
292
293 async move {
294 if let Some(id) = id {
295 return id;
296 }
297 let mut watch = watch.unwrap();
298 loop {
299 let id = *watch.borrow();
300 if let Some(id) = id {
301 return id;
302 }
303 watch.recv().await;
304 }
305 }
306 }
307
308 pub fn replica_id(&self) -> ReplicaId {
309 match &self.client_state {
310 ProjectClientState::Local { .. } => 0,
311 ProjectClientState::Remote { replica_id, .. } => *replica_id,
312 }
313 }
314
315 pub fn collaborators(&self) -> &HashMap<PeerId, Collaborator> {
316 &self.collaborators
317 }
318
319 pub fn worktrees(&self) -> &[ModelHandle<Worktree>] {
320 &self.worktrees
321 }
322
323 pub fn worktree_for_id(&self, id: usize, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
324 self.worktrees
325 .iter()
326 .find(|worktree| worktree.read(cx).id() == id)
327 .cloned()
328 }
329
330 pub fn share(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
331 let rpc = self.client.clone();
332 cx.spawn(|this, mut cx| async move {
333 let project_id = this.update(&mut cx, |this, _| {
334 if let ProjectClientState::Local {
335 is_shared,
336 remote_id_rx,
337 ..
338 } = &mut this.client_state
339 {
340 *is_shared = true;
341 remote_id_rx
342 .borrow()
343 .ok_or_else(|| anyhow!("no project id"))
344 } else {
345 Err(anyhow!("can't share a remote project"))
346 }
347 })?;
348
349 rpc.request(proto::ShareProject { project_id }).await?;
350 let mut tasks = Vec::new();
351 this.update(&mut cx, |this, cx| {
352 for worktree in &this.worktrees {
353 worktree.update(cx, |worktree, cx| {
354 let worktree = worktree.as_local_mut().unwrap();
355 tasks.push(worktree.share(project_id, cx));
356 });
357 }
358 });
359 for task in tasks {
360 task.await?;
361 }
362 this.update(&mut cx, |_, cx| cx.notify());
363 Ok(())
364 })
365 }
366
367 pub fn unshare(&self, cx: &mut ModelContext<Self>) -> Task<anyhow::Result<()>> {
368 let rpc = self.client.clone();
369 cx.spawn(|this, mut cx| async move {
370 let project_id = this.update(&mut cx, |this, _| {
371 if let ProjectClientState::Local {
372 is_shared,
373 remote_id_rx,
374 ..
375 } = &mut this.client_state
376 {
377 *is_shared = false;
378 remote_id_rx
379 .borrow()
380 .ok_or_else(|| anyhow!("no project id"))
381 } else {
382 Err(anyhow!("can't share a remote project"))
383 }
384 })?;
385
386 rpc.send(proto::UnshareProject { project_id }).await?;
387 this.update(&mut cx, |this, cx| {
388 this.collaborators.clear();
389 cx.notify()
390 });
391 Ok(())
392 })
393 }
394
395 pub fn is_read_only(&self) -> bool {
396 match &self.client_state {
397 ProjectClientState::Local { .. } => false,
398 ProjectClientState::Remote {
399 sharing_has_stopped,
400 ..
401 } => *sharing_has_stopped,
402 }
403 }
404
405 pub fn is_local(&self) -> bool {
406 match &self.client_state {
407 ProjectClientState::Local { .. } => true,
408 ProjectClientState::Remote { .. } => false,
409 }
410 }
411
412 pub fn open_buffer(
413 &self,
414 path: ProjectPath,
415 cx: &mut ModelContext<Self>,
416 ) -> Task<Result<ModelHandle<Buffer>>> {
417 if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
418 worktree.update(cx, |worktree, cx| worktree.open_buffer(path.path, cx))
419 } else {
420 cx.spawn(|_, _| async move { Err(anyhow!("no such worktree")) })
421 }
422 }
423
424 pub fn is_shared(&self) -> bool {
425 match &self.client_state {
426 ProjectClientState::Local { is_shared, .. } => *is_shared,
427 ProjectClientState::Remote { .. } => false,
428 }
429 }
430
431 pub fn add_local_worktree(
432 &mut self,
433 abs_path: impl AsRef<Path>,
434 cx: &mut ModelContext<Self>,
435 ) -> Task<Result<ModelHandle<Worktree>>> {
436 let fs = self.fs.clone();
437 let client = self.client.clone();
438 let user_store = self.user_store.clone();
439 let languages = self.languages.clone();
440 let path = Arc::from(abs_path.as_ref());
441 cx.spawn(|project, mut cx| async move {
442 let worktree =
443 Worktree::open_local(client.clone(), user_store, path, fs, languages, &mut cx)
444 .await?;
445
446 let (remote_project_id, is_shared) = project.update(&mut cx, |project, cx| {
447 project.add_worktree(worktree.clone(), cx);
448 (project.remote_id(), project.is_shared())
449 });
450
451 if let Some(project_id) = remote_project_id {
452 let worktree_id = worktree.id() as u64;
453 let register_message = worktree.update(&mut cx, |worktree, _| {
454 let worktree = worktree.as_local_mut().unwrap();
455 proto::RegisterWorktree {
456 project_id,
457 worktree_id,
458 root_name: worktree.root_name().to_string(),
459 authorized_logins: worktree.authorized_logins(),
460 }
461 });
462 client.request(register_message).await?;
463 if is_shared {
464 worktree
465 .update(&mut cx, |worktree, cx| {
466 worktree.as_local_mut().unwrap().share(project_id, cx)
467 })
468 .await?;
469 }
470 }
471
472 Ok(worktree)
473 })
474 }
475
476 fn add_worktree(&mut self, worktree: ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
477 cx.observe(&worktree, |_, _, cx| cx.notify()).detach();
478 cx.subscribe(&worktree, |_, worktree, event, cx| match event {
479 worktree::Event::DiagnosticsUpdated(path) => {
480 cx.emit(Event::DiagnosticsUpdated(ProjectPath {
481 worktree_id: worktree.id(),
482 path: path.clone(),
483 }));
484 }
485 })
486 .detach();
487 self.worktrees.push(worktree);
488 cx.notify();
489 }
490
491 pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
492 let new_active_entry = entry.and_then(|project_path| {
493 let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
494 let entry = worktree.read(cx).entry_for_path(project_path.path)?;
495 Some(ProjectEntry {
496 worktree_id: project_path.worktree_id,
497 entry_id: entry.id,
498 })
499 });
500 if new_active_entry != self.active_entry {
501 self.active_entry = new_active_entry;
502 cx.emit(Event::ActiveEntryChanged(new_active_entry));
503 }
504 }
505
506 pub fn diagnose(&self, cx: &mut ModelContext<Self>) {
507 for worktree_handle in &self.worktrees {
508 if let Some(worktree) = worktree_handle.read(cx).as_local() {
509 for language in worktree.languages() {
510 if let Some(diagnostic_source) = language.diagnostic_source().cloned() {
511 let worktree_path = worktree.abs_path().clone();
512 let worktree_handle = worktree_handle.downgrade();
513 cx.spawn_weak(|_, cx| async move {
514 if let Some(diagnostics) =
515 diagnostic_source.diagnose(worktree_path).await.log_err()
516 {
517 if let Some(worktree_handle) = worktree_handle.upgrade(&cx) {
518 worktree_handle.update(&mut cx, |worktree, cx| {
519 for (path, diagnostics) in diagnostics {}
520 })
521 }
522 }
523 })
524 .detach();
525 }
526 }
527 }
528 }
529 }
530
531 pub fn diagnostic_summaries<'a>(
532 &'a self,
533 cx: &'a AppContext,
534 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
535 self.worktrees.iter().flat_map(move |worktree| {
536 let worktree_id = worktree.id();
537 worktree
538 .read(cx)
539 .diagnostic_summaries()
540 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
541 })
542 }
543
544 pub fn active_entry(&self) -> Option<ProjectEntry> {
545 self.active_entry
546 }
547
548 // RPC message handlers
549
550 fn handle_unshare_project(
551 &mut self,
552 _: TypedEnvelope<proto::UnshareProject>,
553 _: Arc<Client>,
554 cx: &mut ModelContext<Self>,
555 ) -> Result<()> {
556 if let ProjectClientState::Remote {
557 sharing_has_stopped,
558 ..
559 } = &mut self.client_state
560 {
561 *sharing_has_stopped = true;
562 self.collaborators.clear();
563 cx.notify();
564 Ok(())
565 } else {
566 unreachable!()
567 }
568 }
569
570 fn handle_add_collaborator(
571 &mut self,
572 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
573 _: Arc<Client>,
574 cx: &mut ModelContext<Self>,
575 ) -> Result<()> {
576 let user_store = self.user_store.clone();
577 let collaborator = envelope
578 .payload
579 .collaborator
580 .take()
581 .ok_or_else(|| anyhow!("empty collaborator"))?;
582
583 cx.spawn(|this, mut cx| {
584 async move {
585 let collaborator =
586 Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
587 this.update(&mut cx, |this, cx| {
588 this.collaborators
589 .insert(collaborator.peer_id, collaborator);
590 cx.notify();
591 });
592 Ok(())
593 }
594 .log_err()
595 })
596 .detach();
597
598 Ok(())
599 }
600
601 fn handle_remove_collaborator(
602 &mut self,
603 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
604 _: Arc<Client>,
605 cx: &mut ModelContext<Self>,
606 ) -> Result<()> {
607 let peer_id = PeerId(envelope.payload.peer_id);
608 let replica_id = self
609 .collaborators
610 .remove(&peer_id)
611 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
612 .replica_id;
613 for worktree in &self.worktrees {
614 worktree.update(cx, |worktree, cx| {
615 worktree.remove_collaborator(peer_id, replica_id, cx);
616 })
617 }
618 Ok(())
619 }
620
621 fn handle_share_worktree(
622 &mut self,
623 envelope: TypedEnvelope<proto::ShareWorktree>,
624 client: Arc<Client>,
625 cx: &mut ModelContext<Self>,
626 ) -> Result<()> {
627 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
628 let replica_id = self.replica_id();
629 let worktree = envelope
630 .payload
631 .worktree
632 .ok_or_else(|| anyhow!("invalid worktree"))?;
633 let user_store = self.user_store.clone();
634 let languages = self.languages.clone();
635 cx.spawn(|this, mut cx| {
636 async move {
637 let worktree = Worktree::remote(
638 remote_id, replica_id, worktree, client, user_store, languages, &mut cx,
639 )
640 .await?;
641 this.update(&mut cx, |this, cx| this.add_worktree(worktree, cx));
642 Ok(())
643 }
644 .log_err()
645 })
646 .detach();
647 Ok(())
648 }
649
650 fn handle_unregister_worktree(
651 &mut self,
652 envelope: TypedEnvelope<proto::UnregisterWorktree>,
653 _: Arc<Client>,
654 cx: &mut ModelContext<Self>,
655 ) -> Result<()> {
656 self.worktrees.retain(|worktree| {
657 worktree.read(cx).as_remote().unwrap().remote_id() != envelope.payload.worktree_id
658 });
659 cx.notify();
660 Ok(())
661 }
662
663 fn handle_update_worktree(
664 &mut self,
665 envelope: TypedEnvelope<proto::UpdateWorktree>,
666 _: Arc<Client>,
667 cx: &mut ModelContext<Self>,
668 ) -> Result<()> {
669 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
670 worktree.update(cx, |worktree, cx| {
671 let worktree = worktree.as_remote_mut().unwrap();
672 worktree.update_from_remote(envelope, cx)
673 })?;
674 }
675 Ok(())
676 }
677
678 pub fn handle_update_buffer(
679 &mut self,
680 envelope: TypedEnvelope<proto::UpdateBuffer>,
681 _: Arc<Client>,
682 cx: &mut ModelContext<Self>,
683 ) -> Result<()> {
684 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
685 worktree.update(cx, |worktree, cx| {
686 worktree.handle_update_buffer(envelope, cx)
687 })?;
688 }
689 Ok(())
690 }
691
692 pub fn handle_save_buffer(
693 &mut self,
694 envelope: TypedEnvelope<proto::SaveBuffer>,
695 rpc: Arc<Client>,
696 cx: &mut ModelContext<Self>,
697 ) -> Result<()> {
698 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
699 worktree.update(cx, |worktree, cx| {
700 worktree.handle_save_buffer(envelope, rpc, cx)
701 })?;
702 }
703 Ok(())
704 }
705
706 pub fn handle_open_buffer(
707 &mut self,
708 envelope: TypedEnvelope<proto::OpenBuffer>,
709 rpc: Arc<Client>,
710 cx: &mut ModelContext<Self>,
711 ) -> anyhow::Result<()> {
712 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
713 return worktree.update(cx, |worktree, cx| {
714 worktree.handle_open_buffer(envelope, rpc, cx)
715 });
716 } else {
717 Err(anyhow!("no such worktree"))
718 }
719 }
720
721 pub fn handle_close_buffer(
722 &mut self,
723 envelope: TypedEnvelope<proto::CloseBuffer>,
724 rpc: Arc<Client>,
725 cx: &mut ModelContext<Self>,
726 ) -> anyhow::Result<()> {
727 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
728 worktree.update(cx, |worktree, cx| {
729 worktree.handle_close_buffer(envelope, rpc, cx)
730 })?;
731 }
732 Ok(())
733 }
734
735 pub fn handle_buffer_saved(
736 &mut self,
737 envelope: TypedEnvelope<proto::BufferSaved>,
738 _: Arc<Client>,
739 cx: &mut ModelContext<Self>,
740 ) -> Result<()> {
741 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
742 worktree.update(cx, |worktree, cx| {
743 worktree.handle_buffer_saved(envelope, cx)
744 })?;
745 }
746 Ok(())
747 }
748
749 pub fn match_paths<'a>(
750 &self,
751 query: &'a str,
752 include_ignored: bool,
753 smart_case: bool,
754 max_results: usize,
755 cancel_flag: &'a AtomicBool,
756 cx: &AppContext,
757 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
758 let include_root_name = self.worktrees.len() > 1;
759 let candidate_sets = self
760 .worktrees
761 .iter()
762 .map(|worktree| CandidateSet {
763 snapshot: worktree.read(cx).snapshot(),
764 include_ignored,
765 include_root_name,
766 })
767 .collect::<Vec<_>>();
768
769 let background = cx.background().clone();
770 async move {
771 fuzzy::match_paths(
772 candidate_sets.as_slice(),
773 query,
774 smart_case,
775 max_results,
776 cancel_flag,
777 background,
778 )
779 .await
780 }
781 }
782}
783
784struct CandidateSet {
785 snapshot: Snapshot,
786 include_ignored: bool,
787 include_root_name: bool,
788}
789
790impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
791 type Candidates = CandidateSetIter<'a>;
792
793 fn id(&self) -> usize {
794 self.snapshot.id()
795 }
796
797 fn len(&self) -> usize {
798 if self.include_ignored {
799 self.snapshot.file_count()
800 } else {
801 self.snapshot.visible_file_count()
802 }
803 }
804
805 fn prefix(&self) -> Arc<str> {
806 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
807 self.snapshot.root_name().into()
808 } else if self.include_root_name {
809 format!("{}/", self.snapshot.root_name()).into()
810 } else {
811 "".into()
812 }
813 }
814
815 fn candidates(&'a self, start: usize) -> Self::Candidates {
816 CandidateSetIter {
817 traversal: self.snapshot.files(self.include_ignored, start),
818 }
819 }
820}
821
822struct CandidateSetIter<'a> {
823 traversal: Traversal<'a>,
824}
825
826impl<'a> Iterator for CandidateSetIter<'a> {
827 type Item = PathMatchCandidate<'a>;
828
829 fn next(&mut self) -> Option<Self::Item> {
830 self.traversal.next().map(|entry| {
831 if let EntryKind::File(char_bag) = entry.kind {
832 PathMatchCandidate {
833 path: &entry.path,
834 char_bag,
835 }
836 } else {
837 unreachable!()
838 }
839 })
840 }
841}
842
843impl Entity for Project {
844 type Event = Event;
845
846 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
847 match &self.client_state {
848 ProjectClientState::Local { remote_id_rx, .. } => {
849 if let Some(project_id) = *remote_id_rx.borrow() {
850 let rpc = self.client.clone();
851 cx.spawn(|_| async move {
852 if let Err(err) = rpc.send(proto::UnregisterProject { project_id }).await {
853 log::error!("error unregistering project: {}", err);
854 }
855 })
856 .detach();
857 }
858 }
859 ProjectClientState::Remote { remote_id, .. } => {
860 let rpc = self.client.clone();
861 let project_id = *remote_id;
862 cx.spawn(|_| async move {
863 if let Err(err) = rpc.send(proto::LeaveProject { project_id }).await {
864 log::error!("error leaving project: {}", err);
865 }
866 })
867 .detach();
868 }
869 }
870 }
871}
872
873impl Collaborator {
874 fn from_proto(
875 message: proto::Collaborator,
876 user_store: &ModelHandle<UserStore>,
877 cx: &mut AsyncAppContext,
878 ) -> impl Future<Output = Result<Self>> {
879 let user = user_store.update(cx, |user_store, cx| {
880 user_store.fetch_user(message.user_id, cx)
881 });
882
883 async move {
884 Ok(Self {
885 peer_id: PeerId(message.peer_id),
886 user: user.await?,
887 replica_id: message.replica_id as ReplicaId,
888 })
889 }
890 }
891}
892
893#[cfg(test)]
894mod tests {
895 use super::*;
896 use client::{http::ServerResponse, test::FakeHttpClient};
897 use fs::RealFs;
898 use gpui::TestAppContext;
899 use language::LanguageRegistry;
900 use serde_json::json;
901 use std::{os::unix, path::PathBuf};
902 use util::test::temp_tree;
903
904 #[gpui::test]
905 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
906 let dir = temp_tree(json!({
907 "root": {
908 "apple": "",
909 "banana": {
910 "carrot": {
911 "date": "",
912 "endive": "",
913 }
914 },
915 "fennel": {
916 "grape": "",
917 }
918 }
919 }));
920
921 let root_link_path = dir.path().join("root_link");
922 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
923 unix::fs::symlink(
924 &dir.path().join("root/fennel"),
925 &dir.path().join("root/finnochio"),
926 )
927 .unwrap();
928
929 let project = build_project(&mut cx);
930
931 let tree = project
932 .update(&mut cx, |project, cx| {
933 project.add_local_worktree(&root_link_path, cx)
934 })
935 .await
936 .unwrap();
937
938 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
939 .await;
940 cx.read(|cx| {
941 let tree = tree.read(cx);
942 assert_eq!(tree.file_count(), 5);
943 assert_eq!(
944 tree.inode_for_path("fennel/grape"),
945 tree.inode_for_path("finnochio/grape")
946 );
947 });
948
949 let cancel_flag = Default::default();
950 let results = project
951 .read_with(&cx, |project, cx| {
952 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
953 })
954 .await;
955 assert_eq!(
956 results
957 .into_iter()
958 .map(|result| result.path)
959 .collect::<Vec<Arc<Path>>>(),
960 vec![
961 PathBuf::from("banana/carrot/date").into(),
962 PathBuf::from("banana/carrot/endive").into(),
963 ]
964 );
965 }
966
967 #[gpui::test]
968 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
969 let dir = temp_tree(json!({
970 "root": {
971 "dir1": {},
972 "dir2": {
973 "dir3": {}
974 }
975 }
976 }));
977
978 let project = build_project(&mut cx);
979 let tree = project
980 .update(&mut cx, |project, cx| {
981 project.add_local_worktree(&dir.path(), cx)
982 })
983 .await
984 .unwrap();
985
986 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
987 .await;
988
989 let cancel_flag = Default::default();
990 let results = project
991 .read_with(&cx, |project, cx| {
992 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
993 })
994 .await;
995
996 assert!(results.is_empty());
997 }
998
999 fn build_project(cx: &mut TestAppContext) -> ModelHandle<Project> {
1000 let languages = Arc::new(LanguageRegistry::new());
1001 let fs = Arc::new(RealFs);
1002 let client = client::Client::new();
1003 let http_client = FakeHttpClient::new(|_| async move { Ok(ServerResponse::new(404)) });
1004 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
1005 cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
1006 }
1007}