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