1use crate::{
2 pane, persistence::model::ItemId, searchable::SearchableItemHandle, DelayedDebouncedEditAction,
3 FollowableItemBuilders, ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace,
4 WorkspaceId,
5};
6use crate::{AutosaveSetting, WorkspaceSettings};
7use anyhow::Result;
8use client::{proto, Client};
9use gpui::{
10 fonts::HighlightStyle, AnyElement, AnyViewHandle, AppContext, ModelHandle, Task, View,
11 ViewContext, ViewHandle, WeakViewHandle, WindowContext,
12};
13use project::{Project, ProjectEntryId, ProjectPath};
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)) {} // (model id, 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.app_state.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.app_state.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 let settings = settings::get::<WorkspaceSettings>(cx);
454 let debounce_delay = settings.git.gutter_debounce;
455
456 if let AutosaveSetting::AfterDelay { milliseconds } =
457 settings.autosave
458 {
459 let delay = Duration::from_millis(milliseconds);
460 let item = item.clone();
461 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
462 Pane::autosave_item(&item, workspace.project().clone(), cx)
463 });
464 }
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(|workspace, mut cx| async move {
483 workspace
484 .update(&mut cx, |workspace, cx| {
485 item.git_diff_recalc(
486 workspace.project().clone(),
487 cx,
488 )
489 })?
490 .await?;
491 anyhow::Ok(())
492 })
493 .detach_and_log_err(cx);
494 }
495 }
496
497 _ => {}
498 }
499 }
500 }));
501
502 cx.observe_focus(self, move |workspace, item, focused, cx| {
503 if !focused
504 && settings::get::<WorkspaceSettings>(cx).autosave
505 == AutosaveSetting::OnFocusChange
506 {
507 Pane::autosave_item(&item, workspace.project.clone(), cx)
508 .detach_and_log_err(cx);
509 }
510 })
511 .detach();
512
513 let item_id = self.id();
514 cx.observe_release(self, move |workspace, _, _| {
515 workspace.panes_by_item.remove(&item_id);
516 event_subscription.take();
517 })
518 .detach();
519 }
520
521 cx.defer(|workspace, cx| {
522 workspace.serialize_workspace(cx);
523 });
524 }
525
526 fn deactivated(&self, cx: &mut WindowContext) {
527 self.update(cx, |this, cx| this.deactivated(cx));
528 }
529
530 fn workspace_deactivated(&self, cx: &mut WindowContext) {
531 self.update(cx, |this, cx| this.workspace_deactivated(cx));
532 }
533
534 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
535 self.update(cx, |this, cx| this.navigate(data, cx))
536 }
537
538 fn id(&self) -> usize {
539 self.id()
540 }
541
542 fn window_id(&self) -> usize {
543 self.window_id()
544 }
545
546 fn as_any(&self) -> &AnyViewHandle {
547 self
548 }
549
550 fn is_dirty(&self, cx: &AppContext) -> bool {
551 self.read(cx).is_dirty(cx)
552 }
553
554 fn has_conflict(&self, cx: &AppContext) -> bool {
555 self.read(cx).has_conflict(cx)
556 }
557
558 fn can_save(&self, cx: &AppContext) -> bool {
559 self.read(cx).can_save(cx)
560 }
561
562 fn save(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
563 self.update(cx, |item, cx| item.save(project, cx))
564 }
565
566 fn save_as(
567 &self,
568 project: ModelHandle<Project>,
569 abs_path: PathBuf,
570 cx: &mut WindowContext,
571 ) -> Task<anyhow::Result<()>> {
572 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
573 }
574
575 fn reload(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
576 self.update(cx, |item, cx| item.reload(project, cx))
577 }
578
579 fn git_diff_recalc(
580 &self,
581 project: ModelHandle<Project>,
582 cx: &mut WindowContext,
583 ) -> Task<Result<()>> {
584 self.update(cx, |item, cx| item.git_diff_recalc(project, cx))
585 }
586
587 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<&'a AnyViewHandle> {
588 self.read(cx).act_as_type(type_id, self, cx)
589 }
590
591 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
592 if cx.has_global::<FollowableItemBuilders>() {
593 let builders = cx.global::<FollowableItemBuilders>();
594 let item = self.as_any();
595 Some(builders.get(&item.view_type())?.1(item))
596 } else {
597 None
598 }
599 }
600
601 fn on_release(
602 &self,
603 cx: &mut AppContext,
604 callback: Box<dyn FnOnce(&mut AppContext)>,
605 ) -> gpui::Subscription {
606 cx.observe_release(self, move |_, cx| callback(cx))
607 }
608
609 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
610 self.read(cx).as_searchable(self)
611 }
612
613 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
614 self.read(cx).breadcrumb_location()
615 }
616
617 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
618 self.read(cx).breadcrumbs(theme, cx)
619 }
620
621 fn serialized_item_kind(&self) -> Option<&'static str> {
622 T::serialized_item_kind()
623 }
624
625 fn show_toolbar(&self, cx: &AppContext) -> bool {
626 self.read(cx).show_toolbar()
627 }
628}
629
630impl From<Box<dyn ItemHandle>> for AnyViewHandle {
631 fn from(val: Box<dyn ItemHandle>) -> Self {
632 val.as_any().clone()
633 }
634}
635
636impl From<&Box<dyn ItemHandle>> for AnyViewHandle {
637 fn from(val: &Box<dyn ItemHandle>) -> Self {
638 val.as_any().clone()
639 }
640}
641
642impl Clone for Box<dyn ItemHandle> {
643 fn clone(&self) -> Box<dyn ItemHandle> {
644 self.boxed_clone()
645 }
646}
647
648impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
649 fn id(&self) -> usize {
650 self.id()
651 }
652
653 fn window_id(&self) -> usize {
654 self.window_id()
655 }
656
657 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
658 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
659 }
660}
661
662pub trait ProjectItem: Item {
663 type Item: project::Item + gpui::Entity;
664
665 fn for_project_item(
666 project: ModelHandle<Project>,
667 item: ModelHandle<Self::Item>,
668 cx: &mut ViewContext<Self>,
669 ) -> Self;
670}
671
672pub trait FollowableItem: Item {
673 fn remote_id(&self) -> Option<ViewId>;
674 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
675 fn from_state_proto(
676 pane: ViewHandle<Pane>,
677 project: ModelHandle<Project>,
678 id: ViewId,
679 state: &mut Option<proto::view::Variant>,
680 cx: &mut AppContext,
681 ) -> Option<Task<Result<ViewHandle<Self>>>>;
682 fn add_event_to_update_proto(
683 &self,
684 event: &Self::Event,
685 update: &mut Option<proto::update_view::Variant>,
686 cx: &AppContext,
687 ) -> bool;
688 fn apply_update_proto(
689 &mut self,
690 project: &ModelHandle<Project>,
691 message: proto::update_view::Variant,
692 cx: &mut ViewContext<Self>,
693 ) -> Task<Result<()>>;
694
695 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
696 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
697}
698
699pub trait FollowableItemHandle: ItemHandle {
700 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId>;
701 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut WindowContext);
702 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
703 fn add_event_to_update_proto(
704 &self,
705 event: &dyn Any,
706 update: &mut Option<proto::update_view::Variant>,
707 cx: &AppContext,
708 ) -> bool;
709 fn apply_update_proto(
710 &self,
711 project: &ModelHandle<Project>,
712 message: proto::update_view::Variant,
713 cx: &mut WindowContext,
714 ) -> Task<Result<()>>;
715 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
716}
717
718impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
719 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId> {
720 self.read(cx).remote_id().or_else(|| {
721 client.peer_id().map(|creator| ViewId {
722 creator,
723 id: self.id() as u64,
724 })
725 })
726 }
727
728 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut WindowContext) {
729 self.update(cx, |this, cx| {
730 this.set_leader_replica_id(leader_replica_id, cx)
731 })
732 }
733
734 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
735 self.read(cx).to_state_proto(cx)
736 }
737
738 fn add_event_to_update_proto(
739 &self,
740 event: &dyn Any,
741 update: &mut Option<proto::update_view::Variant>,
742 cx: &AppContext,
743 ) -> bool {
744 if let Some(event) = event.downcast_ref() {
745 self.read(cx).add_event_to_update_proto(event, update, cx)
746 } else {
747 false
748 }
749 }
750
751 fn apply_update_proto(
752 &self,
753 project: &ModelHandle<Project>,
754 message: proto::update_view::Variant,
755 cx: &mut WindowContext,
756 ) -> Task<Result<()>> {
757 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
758 }
759
760 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
761 if let Some(event) = event.downcast_ref() {
762 T::should_unfollow_on_event(event, cx)
763 } else {
764 false
765 }
766 }
767}
768
769#[cfg(test)]
770pub(crate) mod test {
771 use super::{Item, ItemEvent};
772 use crate::{sidebar::SidebarItem, ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
773 use gpui::{
774 elements::Empty, AnyElement, AppContext, Element, Entity, ModelHandle, Task, View,
775 ViewContext, ViewHandle, WeakViewHandle,
776 };
777 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
778 use smallvec::SmallVec;
779 use std::{any::Any, borrow::Cow, cell::Cell, path::Path};
780
781 pub struct TestProjectItem {
782 pub entry_id: Option<ProjectEntryId>,
783 pub project_path: Option<ProjectPath>,
784 }
785
786 pub struct TestItem {
787 pub workspace_id: WorkspaceId,
788 pub state: String,
789 pub label: String,
790 pub save_count: usize,
791 pub save_as_count: usize,
792 pub reload_count: usize,
793 pub is_dirty: bool,
794 pub is_singleton: bool,
795 pub has_conflict: bool,
796 pub project_items: Vec<ModelHandle<TestProjectItem>>,
797 pub nav_history: Option<ItemNavHistory>,
798 pub tab_descriptions: Option<Vec<&'static str>>,
799 pub tab_detail: Cell<Option<usize>>,
800 }
801
802 impl Entity for TestProjectItem {
803 type Event = ();
804 }
805
806 impl project::Item for TestProjectItem {
807 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
808 self.entry_id
809 }
810
811 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
812 self.project_path.clone()
813 }
814 }
815
816 pub enum TestItemEvent {
817 Edit,
818 }
819
820 impl Clone for TestItem {
821 fn clone(&self) -> Self {
822 Self {
823 state: self.state.clone(),
824 label: self.label.clone(),
825 save_count: self.save_count,
826 save_as_count: self.save_as_count,
827 reload_count: self.reload_count,
828 is_dirty: self.is_dirty,
829 is_singleton: self.is_singleton,
830 has_conflict: self.has_conflict,
831 project_items: self.project_items.clone(),
832 nav_history: None,
833 tab_descriptions: None,
834 tab_detail: Default::default(),
835 workspace_id: self.workspace_id,
836 }
837 }
838 }
839
840 impl TestProjectItem {
841 pub fn new(id: u64, path: &str, cx: &mut AppContext) -> ModelHandle<Self> {
842 let entry_id = Some(ProjectEntryId::from_proto(id));
843 let project_path = Some(ProjectPath {
844 worktree_id: WorktreeId::from_usize(0),
845 path: Path::new(path).into(),
846 });
847 cx.add_model(|_| Self {
848 entry_id,
849 project_path,
850 })
851 }
852
853 pub fn new_untitled(cx: &mut AppContext) -> ModelHandle<Self> {
854 cx.add_model(|_| Self {
855 project_path: None,
856 entry_id: None,
857 })
858 }
859 }
860
861 impl TestItem {
862 pub fn new() -> Self {
863 Self {
864 state: String::new(),
865 label: String::new(),
866 save_count: 0,
867 save_as_count: 0,
868 reload_count: 0,
869 is_dirty: false,
870 has_conflict: false,
871 project_items: Vec::new(),
872 is_singleton: true,
873 nav_history: None,
874 tab_descriptions: None,
875 tab_detail: Default::default(),
876 workspace_id: 0,
877 }
878 }
879
880 pub fn new_deserialized(id: WorkspaceId) -> Self {
881 let mut this = Self::new();
882 this.workspace_id = id;
883 this
884 }
885
886 pub fn with_label(mut self, state: &str) -> Self {
887 self.label = state.to_string();
888 self
889 }
890
891 pub fn with_singleton(mut self, singleton: bool) -> Self {
892 self.is_singleton = singleton;
893 self
894 }
895
896 pub fn with_dirty(mut self, dirty: bool) -> Self {
897 self.is_dirty = dirty;
898 self
899 }
900
901 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
902 self.has_conflict = has_conflict;
903 self
904 }
905
906 pub fn with_project_items(mut self, items: &[ModelHandle<TestProjectItem>]) -> Self {
907 self.project_items.clear();
908 self.project_items.extend(items.iter().cloned());
909 self
910 }
911
912 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
913 self.push_to_nav_history(cx);
914 self.state = state;
915 }
916
917 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
918 if let Some(history) = &mut self.nav_history {
919 history.push(Some(Box::new(self.state.clone())), cx);
920 }
921 }
922 }
923
924 impl Entity for TestItem {
925 type Event = TestItemEvent;
926 }
927
928 impl View for TestItem {
929 fn ui_name() -> &'static str {
930 "TestItem"
931 }
932
933 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
934 Empty::new().into_any()
935 }
936 }
937
938 impl Item for TestItem {
939 fn tab_description(&self, detail: usize, _: &AppContext) -> Option<Cow<str>> {
940 self.tab_descriptions.as_ref().and_then(|descriptions| {
941 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
942 Some(description.into())
943 })
944 }
945
946 fn tab_content<V: View>(
947 &self,
948 detail: Option<usize>,
949 _: &theme::Tab,
950 _: &AppContext,
951 ) -> AnyElement<V> {
952 self.tab_detail.set(detail);
953 Empty::new().into_any()
954 }
955
956 fn for_each_project_item(
957 &self,
958 cx: &AppContext,
959 f: &mut dyn FnMut(usize, &dyn project::Item),
960 ) {
961 self.project_items
962 .iter()
963 .for_each(|item| f(item.id(), item.read(cx)))
964 }
965
966 fn is_singleton(&self, _: &AppContext) -> bool {
967 self.is_singleton
968 }
969
970 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
971 self.nav_history = Some(history);
972 }
973
974 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
975 let state = *state.downcast::<String>().unwrap_or_default();
976 if state != self.state {
977 self.state = state;
978 true
979 } else {
980 false
981 }
982 }
983
984 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
985 self.push_to_nav_history(cx);
986 }
987
988 fn clone_on_split(
989 &self,
990 _workspace_id: WorkspaceId,
991 _: &mut ViewContext<Self>,
992 ) -> Option<Self>
993 where
994 Self: Sized,
995 {
996 Some(self.clone())
997 }
998
999 fn is_dirty(&self, _: &AppContext) -> bool {
1000 self.is_dirty
1001 }
1002
1003 fn has_conflict(&self, _: &AppContext) -> bool {
1004 self.has_conflict
1005 }
1006
1007 fn can_save(&self, cx: &AppContext) -> bool {
1008 !self.project_items.is_empty()
1009 && self
1010 .project_items
1011 .iter()
1012 .all(|item| item.read(cx).entry_id.is_some())
1013 }
1014
1015 fn save(
1016 &mut self,
1017 _: ModelHandle<Project>,
1018 _: &mut ViewContext<Self>,
1019 ) -> Task<anyhow::Result<()>> {
1020 self.save_count += 1;
1021 self.is_dirty = false;
1022 Task::ready(Ok(()))
1023 }
1024
1025 fn save_as(
1026 &mut self,
1027 _: ModelHandle<Project>,
1028 _: std::path::PathBuf,
1029 _: &mut ViewContext<Self>,
1030 ) -> Task<anyhow::Result<()>> {
1031 self.save_as_count += 1;
1032 self.is_dirty = false;
1033 Task::ready(Ok(()))
1034 }
1035
1036 fn reload(
1037 &mut self,
1038 _: ModelHandle<Project>,
1039 _: &mut ViewContext<Self>,
1040 ) -> Task<anyhow::Result<()>> {
1041 self.reload_count += 1;
1042 self.is_dirty = false;
1043 Task::ready(Ok(()))
1044 }
1045
1046 fn to_item_events(_: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
1047 [ItemEvent::UpdateTab, ItemEvent::Edit].into()
1048 }
1049
1050 fn serialized_item_kind() -> Option<&'static str> {
1051 Some("TestItem")
1052 }
1053
1054 fn deserialize(
1055 _project: ModelHandle<Project>,
1056 _workspace: WeakViewHandle<Workspace>,
1057 workspace_id: WorkspaceId,
1058 _item_id: ItemId,
1059 cx: &mut ViewContext<Pane>,
1060 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
1061 let view = cx.add_view(|_cx| Self::new_deserialized(workspace_id));
1062 Task::Ready(Some(anyhow::Ok(view)))
1063 }
1064 }
1065
1066 impl SidebarItem for TestItem {}
1067}