1use crate::{
2 pane, persistence::model::ItemId, searchable::SearchableItemHandle, FollowableItemBuilders,
3 ItemNavHistory, Pane, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
4};
5use crate::{AutosaveSetting, DelayedDebouncedEditAction, WorkspaceSettings};
6use anyhow::Result;
7use client::{proto, Client};
8use gpui::geometry::vector::Vector2F;
9use gpui::{
10 fonts::HighlightStyle, AnyElement, AnyViewHandle, AppContext, ModelHandle, Task, View,
11 ViewContext, ViewHandle, WeakViewHandle, WindowContext,
12};
13use project::{Project, ProjectEntryId, ProjectPath};
14use schemars::JsonSchema;
15use serde_derive::{Deserialize, Serialize};
16use settings::Setting;
17use smallvec::SmallVec;
18use std::{
19 any::{Any, TypeId},
20 borrow::Cow,
21 cell::RefCell,
22 fmt,
23 ops::Range,
24 path::PathBuf,
25 rc::Rc,
26 sync::{
27 atomic::{AtomicBool, Ordering},
28 Arc,
29 },
30 time::Duration,
31};
32use theme::Theme;
33
34#[derive(Deserialize)]
35pub struct ItemSettings {
36 pub git_status: bool,
37 pub close_position: ClosePosition,
38}
39
40#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
41#[serde(rename_all = "lowercase")]
42pub enum ClosePosition {
43 Left,
44 #[default]
45 Right,
46}
47
48impl ClosePosition {
49 pub fn right(&self) -> bool {
50 match self {
51 ClosePosition::Left => false,
52 ClosePosition::Right => true,
53 }
54 }
55}
56
57#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
58pub struct ItemSettingsContent {
59 git_status: Option<bool>,
60 close_position: Option<ClosePosition>,
61}
62
63impl Setting for ItemSettings {
64 const KEY: Option<&'static str> = Some("tabs");
65
66 type FileContent = ItemSettingsContent;
67
68 fn load(
69 default_value: &Self::FileContent,
70 user_values: &[&Self::FileContent],
71 _: &gpui::AppContext,
72 ) -> anyhow::Result<Self> {
73 Self::load_via_json_merge(default_value, user_values)
74 }
75}
76
77#[derive(Eq, PartialEq, Hash, Debug)]
78pub enum ItemEvent {
79 CloseItem,
80 UpdateTab,
81 UpdateBreadcrumbs,
82 Edit,
83}
84
85// TODO: Combine this with existing HighlightedText struct?
86pub struct BreadcrumbText {
87 pub text: String,
88 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
89}
90
91pub trait Item: View {
92 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
93 fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
94 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
95 false
96 }
97 fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {
98 None
99 }
100 fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<str>> {
101 None
102 }
103 fn tab_content<V: View>(
104 &self,
105 detail: Option<usize>,
106 style: &theme::Tab,
107 cx: &AppContext,
108 ) -> AnyElement<V>;
109 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project::Item)) {} // (model id, Item)
110 fn is_singleton(&self, _cx: &AppContext) -> bool {
111 false
112 }
113 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
114 fn clone_on_split(&self, _workspace_id: WorkspaceId, _: &mut ViewContext<Self>) -> Option<Self>
115 where
116 Self: Sized,
117 {
118 None
119 }
120 fn is_dirty(&self, _: &AppContext) -> bool {
121 false
122 }
123 fn has_conflict(&self, _: &AppContext) -> bool {
124 false
125 }
126 fn can_save(&self, _cx: &AppContext) -> bool {
127 false
128 }
129 fn save(
130 &mut self,
131 _project: ModelHandle<Project>,
132 _cx: &mut ViewContext<Self>,
133 ) -> Task<Result<()>> {
134 unimplemented!("save() must be implemented if can_save() returns true")
135 }
136 fn save_as(
137 &mut self,
138 _project: ModelHandle<Project>,
139 _abs_path: PathBuf,
140 _cx: &mut ViewContext<Self>,
141 ) -> Task<Result<()>> {
142 unimplemented!("save_as() must be implemented if can_save() returns true")
143 }
144 fn reload(
145 &mut self,
146 _project: ModelHandle<Project>,
147 _cx: &mut ViewContext<Self>,
148 ) -> Task<Result<()>> {
149 unimplemented!("reload() must be implemented if can_save() returns true")
150 }
151 fn to_item_events(_event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
152 SmallVec::new()
153 }
154 fn should_close_item_on_event(_: &Self::Event) -> bool {
155 false
156 }
157 fn should_update_tab_on_event(_: &Self::Event) -> bool {
158 false
159 }
160 fn is_edit_event(_: &Self::Event) -> bool {
161 false
162 }
163 fn act_as_type<'a>(
164 &'a self,
165 type_id: TypeId,
166 self_handle: &'a ViewHandle<Self>,
167 _: &'a AppContext,
168 ) -> Option<&AnyViewHandle> {
169 if TypeId::of::<Self>() == type_id {
170 Some(self_handle)
171 } else {
172 None
173 }
174 }
175 fn as_searchable(&self, _: &ViewHandle<Self>) -> Option<Box<dyn SearchableItemHandle>> {
176 None
177 }
178
179 fn breadcrumb_location(&self) -> ToolbarItemLocation {
180 ToolbarItemLocation::Hidden
181 }
182
183 fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
184 None
185 }
186
187 fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
188
189 fn serialized_item_kind() -> Option<&'static str> {
190 None
191 }
192
193 fn deserialize(
194 _project: ModelHandle<Project>,
195 _workspace: WeakViewHandle<Workspace>,
196 _workspace_id: WorkspaceId,
197 _item_id: ItemId,
198 _cx: &mut ViewContext<Pane>,
199 ) -> Task<Result<ViewHandle<Self>>> {
200 unimplemented!(
201 "deserialize() must be implemented if serialized_item_kind() returns Some(_)"
202 )
203 }
204 fn show_toolbar(&self) -> bool {
205 true
206 }
207 fn pixel_position_of_cursor(&self) -> Option<Vector2F> {
208 None
209 }
210}
211
212pub trait ItemHandle: 'static + fmt::Debug {
213 fn subscribe_to_item_events(
214 &self,
215 cx: &mut WindowContext,
216 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
217 ) -> gpui::Subscription;
218 fn tab_tooltip_text<'a>(&self, cx: &'a AppContext) -> Option<Cow<'a, str>>;
219 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>>;
220 fn tab_content(
221 &self,
222 detail: Option<usize>,
223 style: &theme::Tab,
224 cx: &AppContext,
225 ) -> AnyElement<Pane>;
226 fn dragged_tab_content(
227 &self,
228 detail: Option<usize>,
229 style: &theme::Tab,
230 cx: &AppContext,
231 ) -> AnyElement<Workspace>;
232 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
233 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
234 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]>;
235 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project::Item));
236 fn is_singleton(&self, cx: &AppContext) -> bool;
237 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
238 fn clone_on_split(
239 &self,
240 workspace_id: WorkspaceId,
241 cx: &mut WindowContext,
242 ) -> Option<Box<dyn ItemHandle>>;
243 fn added_to_pane(
244 &self,
245 workspace: &mut Workspace,
246 pane: ViewHandle<Pane>,
247 cx: &mut ViewContext<Workspace>,
248 );
249 fn deactivated(&self, cx: &mut WindowContext);
250 fn workspace_deactivated(&self, cx: &mut WindowContext);
251 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
252 fn id(&self) -> usize;
253 fn window_id(&self) -> usize;
254 fn as_any(&self) -> &AnyViewHandle;
255 fn is_dirty(&self, cx: &AppContext) -> bool;
256 fn has_conflict(&self, cx: &AppContext) -> bool;
257 fn can_save(&self, cx: &AppContext) -> bool;
258 fn save(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
259 fn save_as(
260 &self,
261 project: ModelHandle<Project>,
262 abs_path: PathBuf,
263 cx: &mut WindowContext,
264 ) -> Task<Result<()>>;
265 fn reload(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
266 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<&'a AnyViewHandle>;
267 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
268 fn on_release(
269 &self,
270 cx: &mut AppContext,
271 callback: Box<dyn FnOnce(&mut AppContext)>,
272 ) -> gpui::Subscription;
273 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
274 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
275 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
276 fn serialized_item_kind(&self) -> Option<&'static str>;
277 fn show_toolbar(&self, cx: &AppContext) -> bool;
278 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Vector2F>;
279}
280
281pub trait WeakItemHandle {
282 fn id(&self) -> usize;
283 fn window_id(&self) -> usize;
284 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
285}
286
287impl dyn ItemHandle {
288 pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
289 self.as_any().clone().downcast()
290 }
291
292 pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
293 self.act_as_type(TypeId::of::<T>(), cx)
294 .and_then(|t| t.clone().downcast())
295 }
296}
297
298impl<T: Item> ItemHandle for ViewHandle<T> {
299 fn subscribe_to_item_events(
300 &self,
301 cx: &mut WindowContext,
302 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
303 ) -> gpui::Subscription {
304 cx.subscribe(self, move |_, event, cx| {
305 for item_event in T::to_item_events(event) {
306 handler(item_event, cx)
307 }
308 })
309 }
310
311 fn tab_tooltip_text<'a>(&self, cx: &'a AppContext) -> Option<Cow<'a, str>> {
312 self.read(cx).tab_tooltip_text(cx)
313 }
314
315 fn tab_description<'a>(&'a self, detail: usize, cx: &'a AppContext) -> Option<Cow<'a, str>> {
316 self.read(cx).tab_description(detail, cx)
317 }
318
319 fn tab_content(
320 &self,
321 detail: Option<usize>,
322 style: &theme::Tab,
323 cx: &AppContext,
324 ) -> AnyElement<Pane> {
325 self.read(cx).tab_content(detail, style, cx)
326 }
327
328 fn dragged_tab_content(
329 &self,
330 detail: Option<usize>,
331 style: &theme::Tab,
332 cx: &AppContext,
333 ) -> AnyElement<Workspace> {
334 self.read(cx).tab_content(detail, style, cx)
335 }
336
337 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
338 let this = self.read(cx);
339 let mut result = None;
340 if this.is_singleton(cx) {
341 this.for_each_project_item(cx, &mut |_, item| {
342 result = item.project_path(cx);
343 });
344 }
345 result
346 }
347
348 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
349 let mut result = SmallVec::new();
350 self.read(cx).for_each_project_item(cx, &mut |_, item| {
351 if let Some(id) = item.entry_id(cx) {
352 result.push(id);
353 }
354 });
355 result
356 }
357
358 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]> {
359 let mut result = SmallVec::new();
360 self.read(cx).for_each_project_item(cx, &mut |id, _| {
361 result.push(id);
362 });
363 result
364 }
365
366 fn for_each_project_item(&self, cx: &AppContext, f: &mut dyn FnMut(usize, &dyn project::Item)) {
367 self.read(cx).for_each_project_item(cx, f)
368 }
369
370 fn is_singleton(&self, cx: &AppContext) -> bool {
371 self.read(cx).is_singleton(cx)
372 }
373
374 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
375 Box::new(self.clone())
376 }
377
378 fn clone_on_split(
379 &self,
380 workspace_id: WorkspaceId,
381 cx: &mut WindowContext,
382 ) -> Option<Box<dyn ItemHandle>> {
383 self.update(cx, |item, cx| {
384 cx.add_option_view(|cx| item.clone_on_split(workspace_id, cx))
385 })
386 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
387 }
388
389 fn added_to_pane(
390 &self,
391 workspace: &mut Workspace,
392 pane: ViewHandle<Pane>,
393 cx: &mut ViewContext<Workspace>,
394 ) {
395 let history = pane.read(cx).nav_history_for_item(self);
396 self.update(cx, |this, cx| {
397 this.set_nav_history(history, cx);
398 this.added_to_workspace(workspace, cx);
399 });
400
401 if let Some(followed_item) = self.to_followable_item_handle(cx) {
402 if let Some(message) = followed_item.to_state_proto(cx) {
403 workspace.update_followers(
404 proto::update_followers::Variant::CreateView(proto::View {
405 id: followed_item
406 .remote_id(&workspace.app_state.client, cx)
407 .map(|id| id.to_proto()),
408 variant: Some(message),
409 leader_id: workspace.leader_for_pane(&pane),
410 }),
411 cx,
412 );
413 }
414 }
415
416 if workspace
417 .panes_by_item
418 .insert(self.id(), pane.downgrade())
419 .is_none()
420 {
421 let mut pending_autosave = DelayedDebouncedEditAction::new();
422 let pending_update = Rc::new(RefCell::new(None));
423 let pending_update_scheduled = Rc::new(AtomicBool::new(false));
424
425 let mut event_subscription =
426 Some(cx.subscribe(self, move |workspace, item, event, cx| {
427 let pane = if let Some(pane) = workspace
428 .panes_by_item
429 .get(&item.id())
430 .and_then(|pane| pane.upgrade(cx))
431 {
432 pane
433 } else {
434 log::error!("unexpected item event after pane was dropped");
435 return;
436 };
437
438 if let Some(item) = item.to_followable_item_handle(cx) {
439 let leader_id = workspace.leader_for_pane(&pane);
440
441 if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
442 workspace.unfollow(&pane, cx);
443 }
444
445 if item.add_event_to_update_proto(
446 event,
447 &mut *pending_update.borrow_mut(),
448 cx,
449 ) && !pending_update_scheduled.load(Ordering::SeqCst)
450 {
451 pending_update_scheduled.store(true, Ordering::SeqCst);
452 cx.after_window_update({
453 let pending_update = pending_update.clone();
454 let pending_update_scheduled = pending_update_scheduled.clone();
455 move |this, cx| {
456 pending_update_scheduled.store(false, Ordering::SeqCst);
457 this.update_followers(
458 proto::update_followers::Variant::UpdateView(
459 proto::UpdateView {
460 id: item
461 .remote_id(&this.app_state.client, cx)
462 .map(|id| id.to_proto()),
463 variant: pending_update.borrow_mut().take(),
464 leader_id,
465 },
466 ),
467 cx,
468 );
469 }
470 });
471 }
472 }
473
474 for item_event in T::to_item_events(event).into_iter() {
475 match item_event {
476 ItemEvent::CloseItem => {
477 pane.update(cx, |pane, cx| pane.close_item_by_id(item.id(), cx))
478 .detach_and_log_err(cx);
479 return;
480 }
481
482 ItemEvent::UpdateTab => {
483 pane.update(cx, |_, cx| {
484 cx.emit(pane::Event::ChangeItemTitle);
485 cx.notify();
486 });
487 }
488
489 ItemEvent::Edit => {
490 let autosave = settings::get::<WorkspaceSettings>(cx).autosave;
491 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
492 let delay = Duration::from_millis(milliseconds);
493 let item = item.clone();
494 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
495 Pane::autosave_item(&item, workspace.project().clone(), cx)
496 });
497 }
498 }
499
500 _ => {}
501 }
502 }
503 }));
504
505 cx.observe_focus(self, move |workspace, item, focused, cx| {
506 if !focused
507 && settings::get::<WorkspaceSettings>(cx).autosave
508 == AutosaveSetting::OnFocusChange
509 {
510 Pane::autosave_item(&item, workspace.project.clone(), cx)
511 .detach_and_log_err(cx);
512 }
513 })
514 .detach();
515
516 let item_id = self.id();
517 cx.observe_release(self, move |workspace, _, _| {
518 workspace.panes_by_item.remove(&item_id);
519 event_subscription.take();
520 })
521 .detach();
522 }
523
524 cx.defer(|workspace, cx| {
525 workspace.serialize_workspace(cx);
526 });
527 }
528
529 fn deactivated(&self, cx: &mut WindowContext) {
530 self.update(cx, |this, cx| this.deactivated(cx));
531 }
532
533 fn workspace_deactivated(&self, cx: &mut WindowContext) {
534 self.update(cx, |this, cx| this.workspace_deactivated(cx));
535 }
536
537 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
538 self.update(cx, |this, cx| this.navigate(data, cx))
539 }
540
541 fn id(&self) -> usize {
542 self.id()
543 }
544
545 fn window_id(&self) -> usize {
546 self.window_id()
547 }
548
549 fn as_any(&self) -> &AnyViewHandle {
550 self
551 }
552
553 fn is_dirty(&self, cx: &AppContext) -> bool {
554 self.read(cx).is_dirty(cx)
555 }
556
557 fn has_conflict(&self, cx: &AppContext) -> bool {
558 self.read(cx).has_conflict(cx)
559 }
560
561 fn can_save(&self, cx: &AppContext) -> bool {
562 self.read(cx).can_save(cx)
563 }
564
565 fn save(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
566 self.update(cx, |item, cx| item.save(project, cx))
567 }
568
569 fn save_as(
570 &self,
571 project: ModelHandle<Project>,
572 abs_path: PathBuf,
573 cx: &mut WindowContext,
574 ) -> Task<anyhow::Result<()>> {
575 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
576 }
577
578 fn reload(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
579 self.update(cx, |item, cx| item.reload(project, cx))
580 }
581
582 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<&'a AnyViewHandle> {
583 self.read(cx).act_as_type(type_id, self, cx)
584 }
585
586 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
587 if cx.has_global::<FollowableItemBuilders>() {
588 let builders = cx.global::<FollowableItemBuilders>();
589 let item = self.as_any();
590 Some(builders.get(&item.view_type())?.1(item))
591 } else {
592 None
593 }
594 }
595
596 fn on_release(
597 &self,
598 cx: &mut AppContext,
599 callback: Box<dyn FnOnce(&mut AppContext)>,
600 ) -> gpui::Subscription {
601 cx.observe_release(self, move |_, cx| callback(cx))
602 }
603
604 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
605 self.read(cx).as_searchable(self)
606 }
607
608 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
609 self.read(cx).breadcrumb_location()
610 }
611
612 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
613 self.read(cx).breadcrumbs(theme, cx)
614 }
615
616 fn serialized_item_kind(&self) -> Option<&'static str> {
617 T::serialized_item_kind()
618 }
619
620 fn show_toolbar(&self, cx: &AppContext) -> bool {
621 self.read(cx).show_toolbar()
622 }
623
624 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Vector2F> {
625 self.read(cx).pixel_position_of_cursor()
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(any(test, feature = "test-support"))]
769pub mod test {
770 use super::{Item, ItemEvent};
771 use crate::{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}