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