1use std::{
2 any::{Any, TypeId},
3 borrow::Cow,
4 cell::RefCell,
5 fmt,
6 path::PathBuf,
7 rc::Rc,
8 sync::{
9 atomic::{AtomicBool, Ordering},
10 Arc,
11 },
12 time::Duration,
13};
14
15use anyhow::Result;
16use client::{proto, Client};
17use gpui::{
18 AnyViewHandle, AppContext, ElementBox, ModelHandle, MutableAppContext, Task, View, ViewContext,
19 ViewHandle, WeakViewHandle,
20};
21use project::{Project, ProjectEntryId, ProjectPath};
22use settings::{Autosave, Settings};
23use smallvec::SmallVec;
24use theme::Theme;
25use util::ResultExt;
26
27use crate::{
28 pane, persistence::model::ItemId, searchable::SearchableItemHandle, DelayedDebouncedEditAction,
29 FollowableItemBuilders, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace,
30 WorkspaceId,
31};
32
33#[derive(Eq, PartialEq, Hash)]
34pub enum ItemEvent {
35 CloseItem,
36 UpdateTab,
37 UpdateBreadcrumbs,
38 Edit,
39}
40
41pub trait Item: View {
42 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
43 fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
44 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
45 false
46 }
47 fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
48 None
49 }
50 fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
51 -> ElementBox;
52 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project::Item)) {}
53 fn is_singleton(&self, _cx: &AppContext) -> bool {
54 false
55 }
56 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
57 fn clone_on_split(&self, _workspace_id: WorkspaceId, _: &mut ViewContext<Self>) -> Option<Self>
58 where
59 Self: Sized,
60 {
61 None
62 }
63 fn is_dirty(&self, _: &AppContext) -> bool {
64 false
65 }
66 fn has_conflict(&self, _: &AppContext) -> bool {
67 false
68 }
69 fn can_save(&self, _cx: &AppContext) -> bool {
70 false
71 }
72 fn save(
73 &mut self,
74 _project: ModelHandle<Project>,
75 _cx: &mut ViewContext<Self>,
76 ) -> Task<Result<()>> {
77 unimplemented!("save() must be implemented if can_save() returns true")
78 }
79 fn save_as(
80 &mut self,
81 _project: ModelHandle<Project>,
82 _abs_path: PathBuf,
83 _cx: &mut ViewContext<Self>,
84 ) -> Task<Result<()>> {
85 unimplemented!("save_as() must be implemented if can_save() returns true")
86 }
87 fn reload(
88 &mut self,
89 _project: ModelHandle<Project>,
90 _cx: &mut ViewContext<Self>,
91 ) -> Task<Result<()>> {
92 unimplemented!("reload() must be implemented if can_save() returns true")
93 }
94 fn git_diff_recalc(
95 &mut self,
96 _project: ModelHandle<Project>,
97 _cx: &mut ViewContext<Self>,
98 ) -> Task<Result<()>> {
99 Task::ready(Ok(()))
100 }
101 fn to_item_events(_event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
102 SmallVec::new()
103 }
104 fn should_close_item_on_event(_: &Self::Event) -> bool {
105 false
106 }
107 fn should_update_tab_on_event(_: &Self::Event) -> bool {
108 false
109 }
110 fn is_edit_event(_: &Self::Event) -> bool {
111 false
112 }
113 fn act_as_type(
114 &self,
115 type_id: TypeId,
116 self_handle: &ViewHandle<Self>,
117 _: &AppContext,
118 ) -> Option<AnyViewHandle> {
119 if TypeId::of::<Self>() == type_id {
120 Some(self_handle.into())
121 } else {
122 None
123 }
124 }
125 fn as_searchable(&self, _: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
126 None
127 }
128
129 fn breadcrumb_location(&self) -> ToolbarItemLocation {
130 ToolbarItemLocation::Hidden
131 }
132
133 fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<ElementBox>> {
134 None
135 }
136
137 fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
138
139 fn serialized_item_kind() -> Option<&'static str> {
140 None
141 }
142
143 fn deserialize(
144 _project: ModelHandle<Project>,
145 _workspace: WeakViewHandle<Workspace>,
146 _workspace_id: WorkspaceId,
147 _item_id: ItemId,
148 _cx: &mut ViewContext<Pane>,
149 ) -> Task<Result<ViewHandle<Self>>> {
150 unimplemented!(
151 "deserialize() must be implemented if serialized_item_kind() returns Some(_)"
152 )
153 }
154}
155
156pub trait ItemHandle: 'static + fmt::Debug {
157 fn subscribe_to_item_events(
158 &self,
159 cx: &mut MutableAppContext,
160 handler: Box<dyn Fn(ItemEvent, &mut MutableAppContext)>,
161 ) -> gpui::Subscription;
162 fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;
163 fn tab_content(&self, detail: Option<usize>, style: &theme::Tab, cx: &AppContext)
164 -> ElementBox;
165 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
166 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
167 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]>;
168 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project::Item));
169 fn is_singleton(&self, cx: &AppContext) -> bool;
170 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
171 fn clone_on_split(
172 &self,
173 workspace_id: WorkspaceId,
174 cx: &mut MutableAppContext,
175 ) -> Option<Box<dyn ItemHandle>>;
176 fn added_to_pane(
177 &self,
178 workspace: &mut Workspace,
179 pane: ViewHandle<Pane>,
180 cx: &mut ViewContext<Workspace>,
181 );
182 fn deactivated(&self, cx: &mut MutableAppContext);
183 fn workspace_deactivated(&self, cx: &mut MutableAppContext);
184 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool;
185 fn id(&self) -> usize;
186 fn window_id(&self) -> usize;
187 fn to_any(&self) -> AnyViewHandle;
188 fn is_dirty(&self, cx: &AppContext) -> bool;
189 fn has_conflict(&self, cx: &AppContext) -> bool;
190 fn can_save(&self, cx: &AppContext) -> bool;
191 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
192 fn save_as(
193 &self,
194 project: ModelHandle<Project>,
195 abs_path: PathBuf,
196 cx: &mut MutableAppContext,
197 ) -> Task<Result<()>>;
198 fn reload(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext)
199 -> Task<Result<()>>;
200 fn git_diff_recalc(
201 &self,
202 project: ModelHandle<Project>,
203 cx: &mut MutableAppContext,
204 ) -> Task<Result<()>>;
205 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
206 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
207 fn on_release(
208 &self,
209 cx: &mut MutableAppContext,
210 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
211 ) -> gpui::Subscription;
212 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
213 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
214 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<ElementBox>>;
215 fn serialized_item_kind(&self) -> Option<&'static str>;
216}
217
218pub trait WeakItemHandle {
219 fn id(&self) -> usize;
220 fn window_id(&self) -> usize;
221 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
222}
223
224impl dyn ItemHandle {
225 pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
226 self.to_any().downcast()
227 }
228
229 pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
230 self.act_as_type(TypeId::of::<T>(), cx)
231 .and_then(|t| t.downcast())
232 }
233}
234
235impl<T: Item> ItemHandle for ViewHandle<T> {
236 fn subscribe_to_item_events(
237 &self,
238 cx: &mut MutableAppContext,
239 handler: Box<dyn Fn(ItemEvent, &mut MutableAppContext)>,
240 ) -> gpui::Subscription {
241 cx.subscribe(self, move |_, event, cx| {
242 for item_event in T::to_item_events(event) {
243 handler(item_event, cx)
244 }
245 })
246 }
247
248 fn tab_description<'a>(&self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
249 self.read(cx).tab_description(detail, cx)
250 }
251
252 fn tab_content(
253 &self,
254 detail: Option<usize>,
255 style: &theme::Tab,
256 cx: &AppContext,
257 ) -> ElementBox {
258 self.read(cx).tab_content(detail, style, cx)
259 }
260
261 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
262 let this = self.read(cx);
263 let mut result = None;
264 if this.is_singleton(cx) {
265 this.for_each_project_item(cx, &mut |_, item| {
266 result = item.project_path(cx);
267 });
268 }
269 result
270 }
271
272 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
273 let mut result = SmallVec::new();
274 self.read(cx).for_each_project_item(cx, &mut |_, item| {
275 if let Some(id) = item.entry_id(cx) {
276 result.push(id);
277 }
278 });
279 result
280 }
281
282 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]> {
283 let mut result = SmallVec::new();
284 self.read(cx).for_each_project_item(cx, &mut |id, _| {
285 result.push(id);
286 });
287 result
288 }
289
290 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
291 self.read(cx).for_each_project_item(cx, f)
292 }
293
294 fn is_singleton(&self, cx: &AppContext) -> bool {
295 self.read(cx).is_singleton(cx)
296 }
297
298 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
299 Box::new(self.clone())
300 }
301
302 fn clone_on_split(
303 &self,
304 workspace_id: WorkspaceId,
305 cx: &mut MutableAppContext,
306 ) -> Option<Box<dyn ItemHandle>> {
307 self.update(cx, |item, cx| {
308 cx.add_option_view(|cx| item.clone_on_split(workspace_id, cx))
309 })
310 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
311 }
312
313 fn added_to_pane(
314 &self,
315 workspace: &mut Workspace,
316 pane: ViewHandle<Pane>,
317 cx: &mut ViewContext<Workspace>,
318 ) {
319 let history = pane.read(cx).nav_history_for_item(self);
320 self.update(cx, |this, cx| {
321 this.set_nav_history(history, cx);
322 this.added_to_workspace(workspace, cx);
323 });
324
325 if let Some(followed_item) = self.to_followable_item_handle(cx) {
326 if let Some(message) = followed_item.to_state_proto(cx) {
327 workspace.update_followers(
328 proto::update_followers::Variant::CreateView(proto::View {
329 id: followed_item
330 .remote_id(&workspace.client, cx)
331 .map(|id| id.to_proto()),
332 variant: Some(message),
333 leader_id: workspace.leader_for_pane(&pane),
334 }),
335 cx,
336 );
337 }
338 }
339
340 if workspace
341 .panes_by_item
342 .insert(self.id(), pane.downgrade())
343 .is_none()
344 {
345 let mut pending_autosave = DelayedDebouncedEditAction::new();
346 let mut pending_git_update = DelayedDebouncedEditAction::new();
347 let pending_update = Rc::new(RefCell::new(None));
348 let pending_update_scheduled = Rc::new(AtomicBool::new(false));
349
350 let mut event_subscription =
351 Some(cx.subscribe(self, move |workspace, item, event, cx| {
352 let pane = if let Some(pane) = workspace
353 .panes_by_item
354 .get(&item.id())
355 .and_then(|pane| pane.upgrade(cx))
356 {
357 pane
358 } else {
359 log::error!("unexpected item event after pane was dropped");
360 return;
361 };
362
363 if let Some(item) = item.to_followable_item_handle(cx) {
364 let leader_id = workspace.leader_for_pane(&pane);
365
366 if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
367 workspace.unfollow(&pane, cx);
368 }
369
370 if item.add_event_to_update_proto(
371 event,
372 &mut *pending_update.borrow_mut(),
373 cx,
374 ) && !pending_update_scheduled.load(Ordering::SeqCst)
375 {
376 pending_update_scheduled.store(true, Ordering::SeqCst);
377 cx.after_window_update({
378 let pending_update = pending_update.clone();
379 let pending_update_scheduled = pending_update_scheduled.clone();
380 move |this, cx| {
381 pending_update_scheduled.store(false, Ordering::SeqCst);
382 this.update_followers(
383 proto::update_followers::Variant::UpdateView(
384 proto::UpdateView {
385 id: item
386 .remote_id(&this.client, cx)
387 .map(|id| id.to_proto()),
388 variant: pending_update.borrow_mut().take(),
389 leader_id,
390 },
391 ),
392 cx,
393 );
394 }
395 });
396 }
397 }
398
399 for item_event in T::to_item_events(event).into_iter() {
400 match item_event {
401 ItemEvent::CloseItem => {
402 Pane::close_item(workspace, pane, item.id(), cx)
403 .detach_and_log_err(cx);
404 return;
405 }
406
407 ItemEvent::UpdateTab => {
408 pane.update(cx, |_, cx| {
409 cx.emit(pane::Event::ChangeItemTitle);
410 cx.notify();
411 });
412 }
413
414 ItemEvent::Edit => {
415 if let Autosave::AfterDelay { milliseconds } =
416 cx.global::<Settings>().autosave
417 {
418 let delay = Duration::from_millis(milliseconds);
419 let item = item.clone();
420 pending_autosave.fire_new(
421 delay,
422 workspace,
423 cx,
424 |project, mut cx| async move {
425 cx.update(|cx| Pane::autosave_item(&item, project, cx))
426 .await
427 .log_err();
428 },
429 );
430 }
431
432 let settings = cx.global::<Settings>();
433 let debounce_delay = settings.git_overrides.gutter_debounce;
434
435 let item = item.clone();
436
437 if let Some(delay) = debounce_delay {
438 const MIN_GIT_DELAY: u64 = 50;
439
440 let delay = delay.max(MIN_GIT_DELAY);
441 let duration = Duration::from_millis(delay);
442
443 pending_git_update.fire_new(
444 duration,
445 workspace,
446 cx,
447 |project, mut cx| async move {
448 cx.update(|cx| item.git_diff_recalc(project, cx))
449 .await
450 .log_err();
451 },
452 );
453 } else {
454 let project = workspace.project().downgrade();
455 cx.spawn_weak(|_, mut cx| async move {
456 if let Some(project) = project.upgrade(&cx) {
457 cx.update(|cx| item.git_diff_recalc(project, cx))
458 .await
459 .log_err();
460 }
461 })
462 .detach();
463 }
464 }
465
466 _ => {}
467 }
468 }
469 }));
470
471 cx.observe_focus(self, move |workspace, item, focused, cx| {
472 if !focused && cx.global::<Settings>().autosave == Autosave::OnFocusChange {
473 Pane::autosave_item(&item, workspace.project.clone(), cx)
474 .detach_and_log_err(cx);
475 }
476 })
477 .detach();
478
479 let item_id = self.id();
480 cx.observe_release(self, move |workspace, _, _| {
481 workspace.panes_by_item.remove(&item_id);
482 event_subscription.take();
483 })
484 .detach();
485 }
486
487 cx.defer(|workspace, cx| {
488 workspace.serialize_workspace(cx);
489 });
490 }
491
492 fn deactivated(&self, cx: &mut MutableAppContext) {
493 self.update(cx, |this, cx| this.deactivated(cx));
494 }
495
496 fn workspace_deactivated(&self, cx: &mut MutableAppContext) {
497 self.update(cx, |this, cx| this.workspace_deactivated(cx));
498 }
499
500 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) -> bool {
501 self.update(cx, |this, cx| this.navigate(data, cx))
502 }
503
504 fn id(&self) -> usize {
505 self.id()
506 }
507
508 fn window_id(&self) -> usize {
509 self.window_id()
510 }
511
512 fn to_any(&self) -> AnyViewHandle {
513 self.into()
514 }
515
516 fn is_dirty(&self, cx: &AppContext) -> bool {
517 self.read(cx).is_dirty(cx)
518 }
519
520 fn has_conflict(&self, cx: &AppContext) -> bool {
521 self.read(cx).has_conflict(cx)
522 }
523
524 fn can_save(&self, cx: &AppContext) -> bool {
525 self.read(cx).can_save(cx)
526 }
527
528 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
529 self.update(cx, |item, cx| item.save(project, cx))
530 }
531
532 fn save_as(
533 &self,
534 project: ModelHandle<Project>,
535 abs_path: PathBuf,
536 cx: &mut MutableAppContext,
537 ) -> Task<anyhow::Result<()>> {
538 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
539 }
540
541 fn reload(
542 &self,
543 project: ModelHandle<Project>,
544 cx: &mut MutableAppContext,
545 ) -> Task<Result<()>> {
546 self.update(cx, |item, cx| item.reload(project, cx))
547 }
548
549 fn git_diff_recalc(
550 &self,
551 project: ModelHandle<Project>,
552 cx: &mut MutableAppContext,
553 ) -> Task<Result<()>> {
554 self.update(cx, |item, cx| item.git_diff_recalc(project, cx))
555 }
556
557 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
558 self.read(cx).act_as_type(type_id, self, cx)
559 }
560
561 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
562 if cx.has_global::<FollowableItemBuilders>() {
563 let builders = cx.global::<FollowableItemBuilders>();
564 let item = self.to_any();
565 Some(builders.get(&item.view_type())?.1(item))
566 } else {
567 None
568 }
569 }
570
571 fn on_release(
572 &self,
573 cx: &mut MutableAppContext,
574 callback: Box<dyn FnOnce(&mut MutableAppContext)>,
575 ) -> gpui::Subscription {
576 cx.observe_release(self, move |_, cx| callback(cx))
577 }
578
579 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
580 self.read(cx).as_searchable(self)
581 }
582
583 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
584 self.read(cx).breadcrumb_location()
585 }
586
587 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<ElementBox>> {
588 self.read(cx).breadcrumbs(theme, cx)
589 }
590
591 fn serialized_item_kind(&self) -> Option<&'static str> {
592 T::serialized_item_kind()
593 }
594}
595
596impl From<Box<dyn ItemHandle>> for AnyViewHandle {
597 fn from(val: Box<dyn ItemHandle>) -> Self {
598 val.to_any()
599 }
600}
601
602impl From<&Box<dyn ItemHandle>> for AnyViewHandle {
603 fn from(val: &Box<dyn ItemHandle>) -> Self {
604 val.to_any()
605 }
606}
607
608impl Clone for Box<dyn ItemHandle> {
609 fn clone(&self) -> Box<dyn ItemHandle> {
610 self.boxed_clone()
611 }
612}
613
614impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
615 fn id(&self) -> usize {
616 self.id()
617 }
618
619 fn window_id(&self) -> usize {
620 self.window_id()
621 }
622
623 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
624 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
625 }
626}
627
628pub trait ProjectItem: Item {
629 type Item: project::Item + gpui::Entity;
630
631 fn for_project_item(
632 project: ModelHandle<Project>,
633 item: ModelHandle<Self::Item>,
634 cx: &mut ViewContext<Self>,
635 ) -> Self;
636}
637
638pub trait FollowableItem: Item {
639 fn remote_id(&self) -> Option<ViewId>;
640 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
641 fn from_state_proto(
642 pane: ViewHandle<Pane>,
643 project: ModelHandle<Project>,
644 id: ViewId,
645 state: &mut Option<proto::view::Variant>,
646 cx: &mut MutableAppContext,
647 ) -> Option<Task<Result<ViewHandle<Self>>>>;
648 fn add_event_to_update_proto(
649 &self,
650 event: &Self::Event,
651 update: &mut Option<proto::update_view::Variant>,
652 cx: &AppContext,
653 ) -> bool;
654 fn apply_update_proto(
655 &mut self,
656 project: &ModelHandle<Project>,
657 message: proto::update_view::Variant,
658 cx: &mut ViewContext<Self>,
659 ) -> Task<Result<()>>;
660
661 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
662 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
663}
664
665pub trait FollowableItemHandle: ItemHandle {
666 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId>;
667 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
668 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
669 fn add_event_to_update_proto(
670 &self,
671 event: &dyn Any,
672 update: &mut Option<proto::update_view::Variant>,
673 cx: &AppContext,
674 ) -> bool;
675 fn apply_update_proto(
676 &self,
677 project: &ModelHandle<Project>,
678 message: proto::update_view::Variant,
679 cx: &mut MutableAppContext,
680 ) -> Task<Result<()>>;
681 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
682}
683
684impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
685 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId> {
686 self.read(cx).remote_id().or_else(|| {
687 client.peer_id().map(|creator| ViewId {
688 creator,
689 id: self.id() as u64,
690 })
691 })
692 }
693
694 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
695 self.update(cx, |this, cx| {
696 this.set_leader_replica_id(leader_replica_id, cx)
697 })
698 }
699
700 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
701 self.read(cx).to_state_proto(cx)
702 }
703
704 fn add_event_to_update_proto(
705 &self,
706 event: &dyn Any,
707 update: &mut Option<proto::update_view::Variant>,
708 cx: &AppContext,
709 ) -> bool {
710 if let Some(event) = event.downcast_ref() {
711 self.read(cx).add_event_to_update_proto(event, update, cx)
712 } else {
713 false
714 }
715 }
716
717 fn apply_update_proto(
718 &self,
719 project: &ModelHandle<Project>,
720 message: proto::update_view::Variant,
721 cx: &mut MutableAppContext,
722 ) -> Task<Result<()>> {
723 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
724 }
725
726 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
727 if let Some(event) = event.downcast_ref() {
728 T::should_unfollow_on_event(event, cx)
729 } else {
730 false
731 }
732 }
733}
734
735#[cfg(test)]
736pub(crate) mod test {
737 use super::{Item, ItemEvent};
738 use crate::{sidebar::SidebarItem, ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
739 use gpui::{
740 elements::Empty, AppContext, Element, ElementBox, Entity, ModelHandle, MutableAppContext,
741 RenderContext, Task, View, ViewContext, ViewHandle, WeakViewHandle,
742 };
743 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
744 use smallvec::SmallVec;
745 use std::{any::Any, borrow::Cow, cell::Cell, path::Path};
746
747 pub struct TestProjectItem {
748 pub entry_id: Option<ProjectEntryId>,
749 pub project_path: Option<ProjectPath>,
750 }
751
752 pub struct TestItem {
753 pub workspace_id: WorkspaceId,
754 pub state: String,
755 pub label: String,
756 pub save_count: usize,
757 pub save_as_count: usize,
758 pub reload_count: usize,
759 pub is_dirty: bool,
760 pub is_singleton: bool,
761 pub has_conflict: bool,
762 pub project_items: Vec<ModelHandle<TestProjectItem>>,
763 pub nav_history: Option<ItemNavHistory>,
764 pub tab_descriptions: Option<Vec<&'static str>>,
765 pub tab_detail: Cell<Option<usize>>,
766 }
767
768 impl Entity for TestProjectItem {
769 type Event = ();
770 }
771
772 impl project::Item for TestProjectItem {
773 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
774 self.entry_id
775 }
776
777 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
778 self.project_path.clone()
779 }
780 }
781
782 pub enum TestItemEvent {
783 Edit,
784 }
785
786 impl Clone for TestItem {
787 fn clone(&self) -> Self {
788 Self {
789 state: self.state.clone(),
790 label: self.label.clone(),
791 save_count: self.save_count,
792 save_as_count: self.save_as_count,
793 reload_count: self.reload_count,
794 is_dirty: self.is_dirty,
795 is_singleton: self.is_singleton,
796 has_conflict: self.has_conflict,
797 project_items: self.project_items.clone(),
798 nav_history: None,
799 tab_descriptions: None,
800 tab_detail: Default::default(),
801 workspace_id: self.workspace_id,
802 }
803 }
804 }
805
806 impl TestProjectItem {
807 pub fn new(id: u64, path: &str, cx: &mut MutableAppContext) -> ModelHandle<Self> {
808 let entry_id = Some(ProjectEntryId::from_proto(id));
809 let project_path = Some(ProjectPath {
810 worktree_id: WorktreeId::from_usize(0),
811 path: Path::new(path).into(),
812 });
813 cx.add_model(|_| Self {
814 entry_id,
815 project_path,
816 })
817 }
818
819 pub fn new_untitled(cx: &mut MutableAppContext) -> ModelHandle<Self> {
820 cx.add_model(|_| Self {
821 project_path: None,
822 entry_id: None,
823 })
824 }
825 }
826
827 impl TestItem {
828 pub fn new() -> Self {
829 Self {
830 state: String::new(),
831 label: String::new(),
832 save_count: 0,
833 save_as_count: 0,
834 reload_count: 0,
835 is_dirty: false,
836 has_conflict: false,
837 project_items: Vec::new(),
838 is_singleton: true,
839 nav_history: None,
840 tab_descriptions: None,
841 tab_detail: Default::default(),
842 workspace_id: 0,
843 }
844 }
845
846 pub fn new_deserialized(id: WorkspaceId) -> Self {
847 let mut this = Self::new();
848 this.workspace_id = id;
849 this
850 }
851
852 pub fn with_label(mut self, state: &str) -> Self {
853 self.label = state.to_string();
854 self
855 }
856
857 pub fn with_singleton(mut self, singleton: bool) -> Self {
858 self.is_singleton = singleton;
859 self
860 }
861
862 pub fn with_dirty(mut self, dirty: bool) -> Self {
863 self.is_dirty = dirty;
864 self
865 }
866
867 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
868 self.has_conflict = has_conflict;
869 self
870 }
871
872 pub fn with_project_items(mut self, items: &[ModelHandle<TestProjectItem>]) -> Self {
873 self.project_items.clear();
874 self.project_items.extend(items.iter().cloned());
875 self
876 }
877
878 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
879 self.push_to_nav_history(cx);
880 self.state = state;
881 }
882
883 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
884 if let Some(history) = &mut self.nav_history {
885 history.push(Some(Box::new(self.state.clone())), cx);
886 }
887 }
888 }
889
890 impl Entity for TestItem {
891 type Event = TestItemEvent;
892 }
893
894 impl View for TestItem {
895 fn ui_name() -> &'static str {
896 "TestItem"
897 }
898
899 fn render(&mut self, _: &mut RenderContext<Self>) -> ElementBox {
900 Empty::new().boxed()
901 }
902 }
903
904 impl Item for TestItem {
905 fn tab_description<'a>(&'a self, detail: usize, _: &'a AppContext) -> Option<Cow<'a, str>> {
906 self.tab_descriptions.as_ref().and_then(|descriptions| {
907 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
908 Some(description.into())
909 })
910 }
911
912 fn tab_content(&self, detail: Option<usize>, _: &theme::Tab, _: &AppContext) -> ElementBox {
913 self.tab_detail.set(detail);
914 Empty::new().boxed()
915 }
916
917 fn for_each_project_item(
918 &self,
919 cx: &AppContext,
920 f: &mut dyn FnMut(usize, &dyn project::Item),
921 ) {
922 self.project_items
923 .iter()
924 .for_each(|item| f(item.id(), item.read(cx)))
925 }
926
927 fn is_singleton(&self, _: &AppContext) -> bool {
928 self.is_singleton
929 }
930
931 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
932 self.nav_history = Some(history);
933 }
934
935 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
936 let state = *state.downcast::<String>().unwrap_or_default();
937 if state != self.state {
938 self.state = state;
939 true
940 } else {
941 false
942 }
943 }
944
945 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
946 self.push_to_nav_history(cx);
947 }
948
949 fn clone_on_split(
950 &self,
951 _workspace_id: WorkspaceId,
952 _: &mut ViewContext<Self>,
953 ) -> Option<Self>
954 where
955 Self: Sized,
956 {
957 Some(self.clone())
958 }
959
960 fn is_dirty(&self, _: &AppContext) -> bool {
961 self.is_dirty
962 }
963
964 fn has_conflict(&self, _: &AppContext) -> bool {
965 self.has_conflict
966 }
967
968 fn can_save(&self, cx: &AppContext) -> bool {
969 !self.project_items.is_empty()
970 && self
971 .project_items
972 .iter()
973 .all(|item| item.read(cx).entry_id.is_some())
974 }
975
976 fn save(
977 &mut self,
978 _: ModelHandle<Project>,
979 _: &mut ViewContext<Self>,
980 ) -> Task<anyhow::Result<()>> {
981 self.save_count += 1;
982 self.is_dirty = false;
983 Task::ready(Ok(()))
984 }
985
986 fn save_as(
987 &mut self,
988 _: ModelHandle<Project>,
989 _: std::path::PathBuf,
990 _: &mut ViewContext<Self>,
991 ) -> Task<anyhow::Result<()>> {
992 self.save_as_count += 1;
993 self.is_dirty = false;
994 Task::ready(Ok(()))
995 }
996
997 fn reload(
998 &mut self,
999 _: ModelHandle<Project>,
1000 _: &mut ViewContext<Self>,
1001 ) -> Task<anyhow::Result<()>> {
1002 self.reload_count += 1;
1003 self.is_dirty = false;
1004 Task::ready(Ok(()))
1005 }
1006
1007 fn to_item_events(_: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
1008 [ItemEvent::UpdateTab, ItemEvent::Edit].into()
1009 }
1010
1011 fn serialized_item_kind() -> Option<&'static str> {
1012 Some("TestItem")
1013 }
1014
1015 fn deserialize(
1016 _project: ModelHandle<Project>,
1017 _workspace: WeakViewHandle<Workspace>,
1018 workspace_id: WorkspaceId,
1019 _item_id: ItemId,
1020 cx: &mut ViewContext<Pane>,
1021 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
1022 let view = cx.add_view(|_cx| Self::new_deserialized(workspace_id));
1023 Task::Ready(Some(anyhow::Ok(view)))
1024 }
1025 }
1026
1027 impl SidebarItem for TestItem {}
1028}