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, 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(|_, mut 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 todo!()
521 }
522 })
523 }
524 }
525 })
526 .detach();
527 }
528 }
529 }
530 }
531 }
532
533 pub fn diagnostic_summaries<'a>(
534 &'a self,
535 cx: &'a AppContext,
536 ) -> impl Iterator<Item = (ProjectPath, DiagnosticSummary)> + 'a {
537 self.worktrees.iter().flat_map(move |worktree| {
538 let worktree_id = worktree.id();
539 worktree
540 .read(cx)
541 .diagnostic_summaries()
542 .map(move |(path, summary)| (ProjectPath { worktree_id, path }, summary))
543 })
544 }
545
546 pub fn active_entry(&self) -> Option<ProjectEntry> {
547 self.active_entry
548 }
549
550 // RPC message handlers
551
552 fn handle_unshare_project(
553 &mut self,
554 _: TypedEnvelope<proto::UnshareProject>,
555 _: Arc<Client>,
556 cx: &mut ModelContext<Self>,
557 ) -> Result<()> {
558 if let ProjectClientState::Remote {
559 sharing_has_stopped,
560 ..
561 } = &mut self.client_state
562 {
563 *sharing_has_stopped = true;
564 self.collaborators.clear();
565 cx.notify();
566 Ok(())
567 } else {
568 unreachable!()
569 }
570 }
571
572 fn handle_add_collaborator(
573 &mut self,
574 mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
575 _: Arc<Client>,
576 cx: &mut ModelContext<Self>,
577 ) -> Result<()> {
578 let user_store = self.user_store.clone();
579 let collaborator = envelope
580 .payload
581 .collaborator
582 .take()
583 .ok_or_else(|| anyhow!("empty collaborator"))?;
584
585 cx.spawn(|this, mut cx| {
586 async move {
587 let collaborator =
588 Collaborator::from_proto(collaborator, &user_store, &mut cx).await?;
589 this.update(&mut cx, |this, cx| {
590 this.collaborators
591 .insert(collaborator.peer_id, collaborator);
592 cx.notify();
593 });
594 Ok(())
595 }
596 .log_err()
597 })
598 .detach();
599
600 Ok(())
601 }
602
603 fn handle_remove_collaborator(
604 &mut self,
605 envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
606 _: Arc<Client>,
607 cx: &mut ModelContext<Self>,
608 ) -> Result<()> {
609 let peer_id = PeerId(envelope.payload.peer_id);
610 let replica_id = self
611 .collaborators
612 .remove(&peer_id)
613 .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
614 .replica_id;
615 for worktree in &self.worktrees {
616 worktree.update(cx, |worktree, cx| {
617 worktree.remove_collaborator(peer_id, replica_id, cx);
618 })
619 }
620 Ok(())
621 }
622
623 fn handle_share_worktree(
624 &mut self,
625 envelope: TypedEnvelope<proto::ShareWorktree>,
626 client: Arc<Client>,
627 cx: &mut ModelContext<Self>,
628 ) -> Result<()> {
629 let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
630 let replica_id = self.replica_id();
631 let worktree = envelope
632 .payload
633 .worktree
634 .ok_or_else(|| anyhow!("invalid worktree"))?;
635 let user_store = self.user_store.clone();
636 let languages = self.languages.clone();
637 cx.spawn(|this, mut cx| {
638 async move {
639 let worktree = Worktree::remote(
640 remote_id, replica_id, worktree, client, user_store, languages, &mut cx,
641 )
642 .await?;
643 this.update(&mut cx, |this, cx| this.add_worktree(worktree, cx));
644 Ok(())
645 }
646 .log_err()
647 })
648 .detach();
649 Ok(())
650 }
651
652 fn handle_unregister_worktree(
653 &mut self,
654 envelope: TypedEnvelope<proto::UnregisterWorktree>,
655 _: Arc<Client>,
656 cx: &mut ModelContext<Self>,
657 ) -> Result<()> {
658 self.worktrees.retain(|worktree| {
659 worktree.read(cx).as_remote().unwrap().remote_id() != envelope.payload.worktree_id
660 });
661 cx.notify();
662 Ok(())
663 }
664
665 fn handle_update_worktree(
666 &mut self,
667 envelope: TypedEnvelope<proto::UpdateWorktree>,
668 _: Arc<Client>,
669 cx: &mut ModelContext<Self>,
670 ) -> Result<()> {
671 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
672 worktree.update(cx, |worktree, cx| {
673 let worktree = worktree.as_remote_mut().unwrap();
674 worktree.update_from_remote(envelope, cx)
675 })?;
676 }
677 Ok(())
678 }
679
680 pub fn handle_update_buffer(
681 &mut self,
682 envelope: TypedEnvelope<proto::UpdateBuffer>,
683 _: Arc<Client>,
684 cx: &mut ModelContext<Self>,
685 ) -> Result<()> {
686 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
687 worktree.update(cx, |worktree, cx| {
688 worktree.handle_update_buffer(envelope, cx)
689 })?;
690 }
691 Ok(())
692 }
693
694 pub fn handle_save_buffer(
695 &mut self,
696 envelope: TypedEnvelope<proto::SaveBuffer>,
697 rpc: Arc<Client>,
698 cx: &mut ModelContext<Self>,
699 ) -> Result<()> {
700 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
701 worktree.update(cx, |worktree, cx| {
702 worktree.handle_save_buffer(envelope, rpc, cx)
703 })?;
704 }
705 Ok(())
706 }
707
708 pub fn handle_open_buffer(
709 &mut self,
710 envelope: TypedEnvelope<proto::OpenBuffer>,
711 rpc: Arc<Client>,
712 cx: &mut ModelContext<Self>,
713 ) -> anyhow::Result<()> {
714 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
715 return worktree.update(cx, |worktree, cx| {
716 worktree.handle_open_buffer(envelope, rpc, cx)
717 });
718 } else {
719 Err(anyhow!("no such worktree"))
720 }
721 }
722
723 pub fn handle_close_buffer(
724 &mut self,
725 envelope: TypedEnvelope<proto::CloseBuffer>,
726 rpc: Arc<Client>,
727 cx: &mut ModelContext<Self>,
728 ) -> anyhow::Result<()> {
729 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
730 worktree.update(cx, |worktree, cx| {
731 worktree.handle_close_buffer(envelope, rpc, cx)
732 })?;
733 }
734 Ok(())
735 }
736
737 pub fn handle_buffer_saved(
738 &mut self,
739 envelope: TypedEnvelope<proto::BufferSaved>,
740 _: Arc<Client>,
741 cx: &mut ModelContext<Self>,
742 ) -> Result<()> {
743 if let Some(worktree) = self.worktree_for_id(envelope.payload.worktree_id as usize, cx) {
744 worktree.update(cx, |worktree, cx| {
745 worktree.handle_buffer_saved(envelope, cx)
746 })?;
747 }
748 Ok(())
749 }
750
751 pub fn match_paths<'a>(
752 &self,
753 query: &'a str,
754 include_ignored: bool,
755 smart_case: bool,
756 max_results: usize,
757 cancel_flag: &'a AtomicBool,
758 cx: &AppContext,
759 ) -> impl 'a + Future<Output = Vec<PathMatch>> {
760 let include_root_name = self.worktrees.len() > 1;
761 let candidate_sets = self
762 .worktrees
763 .iter()
764 .map(|worktree| CandidateSet {
765 snapshot: worktree.read(cx).snapshot(),
766 include_ignored,
767 include_root_name,
768 })
769 .collect::<Vec<_>>();
770
771 let background = cx.background().clone();
772 async move {
773 fuzzy::match_paths(
774 candidate_sets.as_slice(),
775 query,
776 smart_case,
777 max_results,
778 cancel_flag,
779 background,
780 )
781 .await
782 }
783 }
784}
785
786struct CandidateSet {
787 snapshot: Snapshot,
788 include_ignored: bool,
789 include_root_name: bool,
790}
791
792impl<'a> PathMatchCandidateSet<'a> for CandidateSet {
793 type Candidates = CandidateSetIter<'a>;
794
795 fn id(&self) -> usize {
796 self.snapshot.id()
797 }
798
799 fn len(&self) -> usize {
800 if self.include_ignored {
801 self.snapshot.file_count()
802 } else {
803 self.snapshot.visible_file_count()
804 }
805 }
806
807 fn prefix(&self) -> Arc<str> {
808 if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
809 self.snapshot.root_name().into()
810 } else if self.include_root_name {
811 format!("{}/", self.snapshot.root_name()).into()
812 } else {
813 "".into()
814 }
815 }
816
817 fn candidates(&'a self, start: usize) -> Self::Candidates {
818 CandidateSetIter {
819 traversal: self.snapshot.files(self.include_ignored, start),
820 }
821 }
822}
823
824struct CandidateSetIter<'a> {
825 traversal: Traversal<'a>,
826}
827
828impl<'a> Iterator for CandidateSetIter<'a> {
829 type Item = PathMatchCandidate<'a>;
830
831 fn next(&mut self) -> Option<Self::Item> {
832 self.traversal.next().map(|entry| {
833 if let EntryKind::File(char_bag) = entry.kind {
834 PathMatchCandidate {
835 path: &entry.path,
836 char_bag,
837 }
838 } else {
839 unreachable!()
840 }
841 })
842 }
843}
844
845impl Entity for Project {
846 type Event = Event;
847
848 fn release(&mut self, cx: &mut gpui::MutableAppContext) {
849 match &self.client_state {
850 ProjectClientState::Local { remote_id_rx, .. } => {
851 if let Some(project_id) = *remote_id_rx.borrow() {
852 let rpc = self.client.clone();
853 cx.spawn(|_| async move {
854 if let Err(err) = rpc.send(proto::UnregisterProject { project_id }).await {
855 log::error!("error unregistering project: {}", err);
856 }
857 })
858 .detach();
859 }
860 }
861 ProjectClientState::Remote { remote_id, .. } => {
862 let rpc = self.client.clone();
863 let project_id = *remote_id;
864 cx.spawn(|_| async move {
865 if let Err(err) = rpc.send(proto::LeaveProject { project_id }).await {
866 log::error!("error leaving project: {}", err);
867 }
868 })
869 .detach();
870 }
871 }
872 }
873}
874
875impl Collaborator {
876 fn from_proto(
877 message: proto::Collaborator,
878 user_store: &ModelHandle<UserStore>,
879 cx: &mut AsyncAppContext,
880 ) -> impl Future<Output = Result<Self>> {
881 let user = user_store.update(cx, |user_store, cx| {
882 user_store.fetch_user(message.user_id, cx)
883 });
884
885 async move {
886 Ok(Self {
887 peer_id: PeerId(message.peer_id),
888 user: user.await?,
889 replica_id: message.replica_id as ReplicaId,
890 })
891 }
892 }
893}
894
895#[cfg(test)]
896mod tests {
897 use super::*;
898 use client::{http::ServerResponse, test::FakeHttpClient};
899 use fs::RealFs;
900 use gpui::TestAppContext;
901 use language::LanguageRegistry;
902 use serde_json::json;
903 use std::{os::unix, path::PathBuf};
904 use util::test::temp_tree;
905
906 #[gpui::test]
907 async fn test_populate_and_search(mut cx: gpui::TestAppContext) {
908 let dir = temp_tree(json!({
909 "root": {
910 "apple": "",
911 "banana": {
912 "carrot": {
913 "date": "",
914 "endive": "",
915 }
916 },
917 "fennel": {
918 "grape": "",
919 }
920 }
921 }));
922
923 let root_link_path = dir.path().join("root_link");
924 unix::fs::symlink(&dir.path().join("root"), &root_link_path).unwrap();
925 unix::fs::symlink(
926 &dir.path().join("root/fennel"),
927 &dir.path().join("root/finnochio"),
928 )
929 .unwrap();
930
931 let project = build_project(&mut cx);
932
933 let tree = project
934 .update(&mut cx, |project, cx| {
935 project.add_local_worktree(&root_link_path, cx)
936 })
937 .await
938 .unwrap();
939
940 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
941 .await;
942 cx.read(|cx| {
943 let tree = tree.read(cx);
944 assert_eq!(tree.file_count(), 5);
945 assert_eq!(
946 tree.inode_for_path("fennel/grape"),
947 tree.inode_for_path("finnochio/grape")
948 );
949 });
950
951 let cancel_flag = Default::default();
952 let results = project
953 .read_with(&cx, |project, cx| {
954 project.match_paths("bna", false, false, 10, &cancel_flag, cx)
955 })
956 .await;
957 assert_eq!(
958 results
959 .into_iter()
960 .map(|result| result.path)
961 .collect::<Vec<Arc<Path>>>(),
962 vec![
963 PathBuf::from("banana/carrot/date").into(),
964 PathBuf::from("banana/carrot/endive").into(),
965 ]
966 );
967 }
968
969 #[gpui::test]
970 async fn test_search_worktree_without_files(mut cx: gpui::TestAppContext) {
971 let dir = temp_tree(json!({
972 "root": {
973 "dir1": {},
974 "dir2": {
975 "dir3": {}
976 }
977 }
978 }));
979
980 let project = build_project(&mut cx);
981 let tree = project
982 .update(&mut cx, |project, cx| {
983 project.add_local_worktree(&dir.path(), cx)
984 })
985 .await
986 .unwrap();
987
988 cx.read(|cx| tree.read(cx).as_local().unwrap().scan_complete())
989 .await;
990
991 let cancel_flag = Default::default();
992 let results = project
993 .read_with(&cx, |project, cx| {
994 project.match_paths("dir", false, false, 10, &cancel_flag, cx)
995 })
996 .await;
997
998 assert!(results.is_empty());
999 }
1000
1001 fn build_project(cx: &mut TestAppContext) -> ModelHandle<Project> {
1002 let languages = Arc::new(LanguageRegistry::new());
1003 let fs = Arc::new(RealFs);
1004 let client = client::Client::new();
1005 let http_client = FakeHttpClient::new(|_| async move { Ok(ServerResponse::new(404)) });
1006 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
1007 cx.update(|cx| Project::local(client, user_store, languages, fs, cx))
1008 }
1009}