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::AnyWindowHandle;
10use gpui::{
11 fonts::HighlightStyle, AnyElement, AnyViewHandle, AppContext, ModelHandle, Task, View,
12 ViewContext, ViewHandle, WeakViewHandle, WindowContext,
13};
14use project::{Project, ProjectEntryId, ProjectPath};
15use schemars::JsonSchema;
16use serde_derive::{Deserialize, Serialize};
17use settings::Setting;
18use smallvec::SmallVec;
19use std::{
20 any::{Any, TypeId},
21 borrow::Cow,
22 cell::RefCell,
23 fmt,
24 ops::Range,
25 path::PathBuf,
26 rc::Rc,
27 sync::{
28 atomic::{AtomicBool, Ordering},
29 Arc,
30 },
31 time::Duration,
32};
33use theme::Theme;
34
35#[derive(Deserialize)]
36pub struct ItemSettings {
37 pub git_status: bool,
38 pub close_position: ClosePosition,
39}
40
41#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
42#[serde(rename_all = "lowercase")]
43pub enum ClosePosition {
44 Left,
45 #[default]
46 Right,
47}
48
49impl ClosePosition {
50 pub fn right(&self) -> bool {
51 match self {
52 ClosePosition::Left => false,
53 ClosePosition::Right => true,
54 }
55 }
56}
57
58#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
59pub struct ItemSettingsContent {
60 git_status: Option<bool>,
61 close_position: Option<ClosePosition>,
62}
63
64impl Setting for ItemSettings {
65 const KEY: Option<&'static str> = Some("tabs");
66
67 type FileContent = ItemSettingsContent;
68
69 fn load(
70 default_value: &Self::FileContent,
71 user_values: &[&Self::FileContent],
72 _: &gpui::AppContext,
73 ) -> anyhow::Result<Self> {
74 Self::load_via_json_merge(default_value, user_values)
75 }
76}
77
78#[derive(Eq, PartialEq, Hash, Debug)]
79pub enum ItemEvent {
80 CloseItem,
81 UpdateTab,
82 UpdateBreadcrumbs,
83 Edit,
84}
85
86// TODO: Combine this with existing HighlightedText struct?
87pub struct BreadcrumbText {
88 pub text: String,
89 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
90}
91
92pub trait Item: View {
93 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
94 fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
95 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
96 false
97 }
98 fn tab_tooltip_text(&self, _: &AppContext) -> Option<Cow<str>> {
99 None
100 }
101 fn tab_description<'a>(&'a self, _: usize, _: &'a AppContext) -> Option<Cow<str>> {
102 None
103 }
104 fn tab_content<V: 'static>(
105 &self,
106 detail: Option<usize>,
107 style: &theme::Tab,
108 cx: &AppContext,
109 ) -> AnyElement<V>;
110 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project::Item)) {} // (model id, Item)
111 fn is_singleton(&self, _cx: &AppContext) -> bool {
112 false
113 }
114 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
115 fn clone_on_split(&self, _workspace_id: WorkspaceId, _: &mut ViewContext<Self>) -> Option<Self>
116 where
117 Self: Sized,
118 {
119 None
120 }
121 fn is_dirty(&self, _: &AppContext) -> bool {
122 false
123 }
124 fn has_conflict(&self, _: &AppContext) -> bool {
125 false
126 }
127 fn can_save(&self, _cx: &AppContext) -> bool {
128 false
129 }
130 fn save(
131 &mut self,
132 _project: ModelHandle<Project>,
133 _cx: &mut ViewContext<Self>,
134 ) -> Task<Result<()>> {
135 unimplemented!("save() must be implemented if can_save() returns true")
136 }
137 fn save_as(
138 &mut self,
139 _project: ModelHandle<Project>,
140 _abs_path: PathBuf,
141 _cx: &mut ViewContext<Self>,
142 ) -> Task<Result<()>> {
143 unimplemented!("save_as() must be implemented if can_save() returns true")
144 }
145 fn reload(
146 &mut self,
147 _project: ModelHandle<Project>,
148 _cx: &mut ViewContext<Self>,
149 ) -> Task<Result<()>> {
150 unimplemented!("reload() must be implemented if can_save() returns true")
151 }
152 fn to_item_events(_event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
153 SmallVec::new()
154 }
155 fn should_close_item_on_event(_: &Self::Event) -> bool {
156 false
157 }
158 fn should_update_tab_on_event(_: &Self::Event) -> bool {
159 false
160 }
161
162 fn act_as_type<'a>(
163 &'a self,
164 type_id: TypeId,
165 self_handle: &'a ViewHandle<Self>,
166 _: &'a AppContext,
167 ) -> Option<&AnyViewHandle> {
168 if TypeId::of::<Self>() == type_id {
169 Some(self_handle)
170 } else {
171 None
172 }
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, _: &AppContext) -> 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(&self) -> AnyWindowHandle;
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(&self) -> AnyWindowHandle;
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| {
478 pane.close_item_by_id(
479 item.id(),
480 crate::SaveBehavior::PromptOnWrite,
481 cx,
482 )
483 })
484 .detach_and_log_err(cx);
485 return;
486 }
487
488 ItemEvent::UpdateTab => {
489 pane.update(cx, |_, cx| {
490 cx.emit(pane::Event::ChangeItemTitle);
491 cx.notify();
492 });
493 }
494
495 ItemEvent::Edit => {
496 let autosave = settings::get::<WorkspaceSettings>(cx).autosave;
497 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
498 let delay = Duration::from_millis(milliseconds);
499 let item = item.clone();
500 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
501 Pane::autosave_item(&item, workspace.project().clone(), cx)
502 });
503 }
504 }
505
506 _ => {}
507 }
508 }
509 }));
510
511 cx.observe_focus(self, move |workspace, item, focused, cx| {
512 if !focused
513 && settings::get::<WorkspaceSettings>(cx).autosave
514 == AutosaveSetting::OnFocusChange
515 {
516 Pane::autosave_item(&item, workspace.project.clone(), cx)
517 .detach_and_log_err(cx);
518 }
519 })
520 .detach();
521
522 let item_id = self.id();
523 cx.observe_release(self, move |workspace, _, _| {
524 workspace.panes_by_item.remove(&item_id);
525 event_subscription.take();
526 })
527 .detach();
528 }
529
530 cx.defer(|workspace, cx| {
531 workspace.serialize_workspace(cx);
532 });
533 }
534
535 fn deactivated(&self, cx: &mut WindowContext) {
536 self.update(cx, |this, cx| this.deactivated(cx));
537 }
538
539 fn workspace_deactivated(&self, cx: &mut WindowContext) {
540 self.update(cx, |this, cx| this.workspace_deactivated(cx));
541 }
542
543 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
544 self.update(cx, |this, cx| this.navigate(data, cx))
545 }
546
547 fn id(&self) -> usize {
548 self.id()
549 }
550
551 fn window(&self) -> AnyWindowHandle {
552 AnyViewHandle::window(self)
553 }
554
555 fn as_any(&self) -> &AnyViewHandle {
556 self
557 }
558
559 fn is_dirty(&self, cx: &AppContext) -> bool {
560 self.read(cx).is_dirty(cx)
561 }
562
563 fn has_conflict(&self, cx: &AppContext) -> bool {
564 self.read(cx).has_conflict(cx)
565 }
566
567 fn can_save(&self, cx: &AppContext) -> bool {
568 self.read(cx).can_save(cx)
569 }
570
571 fn save(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
572 self.update(cx, |item, cx| item.save(project, cx))
573 }
574
575 fn save_as(
576 &self,
577 project: ModelHandle<Project>,
578 abs_path: PathBuf,
579 cx: &mut WindowContext,
580 ) -> Task<anyhow::Result<()>> {
581 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
582 }
583
584 fn reload(&self, project: ModelHandle<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
585 self.update(cx, |item, cx| item.reload(project, cx))
586 }
587
588 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<&'a AnyViewHandle> {
589 self.read(cx).act_as_type(type_id, self, cx)
590 }
591
592 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
593 if cx.has_global::<FollowableItemBuilders>() {
594 let builders = cx.global::<FollowableItemBuilders>();
595 let item = self.as_any();
596 Some(builders.get(&item.view_type())?.1(item))
597 } else {
598 None
599 }
600 }
601
602 fn on_release(
603 &self,
604 cx: &mut AppContext,
605 callback: Box<dyn FnOnce(&mut AppContext)>,
606 ) -> gpui::Subscription {
607 cx.observe_release(self, move |_, cx| callback(cx))
608 }
609
610 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
611 self.read(cx).as_searchable(self)
612 }
613
614 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
615 self.read(cx).breadcrumb_location()
616 }
617
618 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
619 self.read(cx).breadcrumbs(theme, cx)
620 }
621
622 fn serialized_item_kind(&self) -> Option<&'static str> {
623 T::serialized_item_kind()
624 }
625
626 fn show_toolbar(&self, cx: &AppContext) -> bool {
627 self.read(cx).show_toolbar()
628 }
629
630 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Vector2F> {
631 self.read(cx).pixel_position_of_cursor(cx)
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 From<&Box<dyn ItemHandle>> for AnyViewHandle {
642 fn from(val: &Box<dyn ItemHandle>) -> Self {
643 val.as_any().clone()
644 }
645}
646
647impl Clone for Box<dyn ItemHandle> {
648 fn clone(&self) -> Box<dyn ItemHandle> {
649 self.boxed_clone()
650 }
651}
652
653impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
654 fn id(&self) -> usize {
655 self.id()
656 }
657
658 fn window(&self) -> AnyWindowHandle {
659 self.window()
660 }
661
662 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
663 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
664 }
665}
666
667pub trait ProjectItem: Item {
668 type Item: project::Item + gpui::Entity;
669
670 fn for_project_item(
671 project: ModelHandle<Project>,
672 item: ModelHandle<Self::Item>,
673 cx: &mut ViewContext<Self>,
674 ) -> Self;
675}
676
677pub trait FollowableItem: Item {
678 fn remote_id(&self) -> Option<ViewId>;
679 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
680 fn from_state_proto(
681 pane: ViewHandle<Pane>,
682 project: ViewHandle<Workspace>,
683 id: ViewId,
684 state: &mut Option<proto::view::Variant>,
685 cx: &mut AppContext,
686 ) -> Option<Task<Result<ViewHandle<Self>>>>;
687 fn add_event_to_update_proto(
688 &self,
689 event: &Self::Event,
690 update: &mut Option<proto::update_view::Variant>,
691 cx: &AppContext,
692 ) -> bool;
693 fn apply_update_proto(
694 &mut self,
695 project: &ModelHandle<Project>,
696 message: proto::update_view::Variant,
697 cx: &mut ViewContext<Self>,
698 ) -> Task<Result<()>>;
699
700 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
701 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
702}
703
704pub trait FollowableItemHandle: ItemHandle {
705 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId>;
706 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut WindowContext);
707 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
708 fn add_event_to_update_proto(
709 &self,
710 event: &dyn Any,
711 update: &mut Option<proto::update_view::Variant>,
712 cx: &AppContext,
713 ) -> bool;
714 fn apply_update_proto(
715 &self,
716 project: &ModelHandle<Project>,
717 message: proto::update_view::Variant,
718 cx: &mut WindowContext,
719 ) -> Task<Result<()>>;
720 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
721}
722
723impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
724 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId> {
725 self.read(cx).remote_id().or_else(|| {
726 client.peer_id().map(|creator| ViewId {
727 creator,
728 id: self.id() as u64,
729 })
730 })
731 }
732
733 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut WindowContext) {
734 self.update(cx, |this, cx| {
735 this.set_leader_replica_id(leader_replica_id, cx)
736 })
737 }
738
739 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
740 self.read(cx).to_state_proto(cx)
741 }
742
743 fn add_event_to_update_proto(
744 &self,
745 event: &dyn Any,
746 update: &mut Option<proto::update_view::Variant>,
747 cx: &AppContext,
748 ) -> bool {
749 if let Some(event) = event.downcast_ref() {
750 self.read(cx).add_event_to_update_proto(event, update, cx)
751 } else {
752 false
753 }
754 }
755
756 fn apply_update_proto(
757 &self,
758 project: &ModelHandle<Project>,
759 message: proto::update_view::Variant,
760 cx: &mut WindowContext,
761 ) -> Task<Result<()>> {
762 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
763 }
764
765 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
766 if let Some(event) = event.downcast_ref() {
767 T::should_unfollow_on_event(event, cx)
768 } else {
769 false
770 }
771 }
772}
773
774#[cfg(any(test, feature = "test-support"))]
775pub mod test {
776 use super::{Item, ItemEvent};
777 use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
778 use gpui::{
779 elements::Empty, AnyElement, AppContext, Element, Entity, ModelHandle, Task, View,
780 ViewContext, ViewHandle, WeakViewHandle,
781 };
782 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
783 use smallvec::SmallVec;
784 use std::{any::Any, borrow::Cow, cell::Cell, path::Path};
785
786 pub struct TestProjectItem {
787 pub entry_id: Option<ProjectEntryId>,
788 pub project_path: Option<ProjectPath>,
789 }
790
791 pub struct TestItem {
792 pub workspace_id: WorkspaceId,
793 pub state: String,
794 pub label: String,
795 pub save_count: usize,
796 pub save_as_count: usize,
797 pub reload_count: usize,
798 pub is_dirty: bool,
799 pub is_singleton: bool,
800 pub has_conflict: bool,
801 pub project_items: Vec<ModelHandle<TestProjectItem>>,
802 pub nav_history: Option<ItemNavHistory>,
803 pub tab_descriptions: Option<Vec<&'static str>>,
804 pub tab_detail: Cell<Option<usize>>,
805 }
806
807 impl Entity for TestProjectItem {
808 type Event = ();
809 }
810
811 impl project::Item for TestProjectItem {
812 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
813 self.entry_id
814 }
815
816 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
817 self.project_path.clone()
818 }
819 }
820
821 pub enum TestItemEvent {
822 Edit,
823 }
824
825 impl Clone for TestItem {
826 fn clone(&self) -> Self {
827 Self {
828 state: self.state.clone(),
829 label: self.label.clone(),
830 save_count: self.save_count,
831 save_as_count: self.save_as_count,
832 reload_count: self.reload_count,
833 is_dirty: self.is_dirty,
834 is_singleton: self.is_singleton,
835 has_conflict: self.has_conflict,
836 project_items: self.project_items.clone(),
837 nav_history: None,
838 tab_descriptions: None,
839 tab_detail: Default::default(),
840 workspace_id: self.workspace_id,
841 }
842 }
843 }
844
845 impl TestProjectItem {
846 pub fn new(id: u64, path: &str, cx: &mut AppContext) -> ModelHandle<Self> {
847 let entry_id = Some(ProjectEntryId::from_proto(id));
848 let project_path = Some(ProjectPath {
849 worktree_id: WorktreeId::from_usize(0),
850 path: Path::new(path).into(),
851 });
852 cx.add_model(|_| Self {
853 entry_id,
854 project_path,
855 })
856 }
857
858 pub fn new_untitled(cx: &mut AppContext) -> ModelHandle<Self> {
859 cx.add_model(|_| Self {
860 project_path: None,
861 entry_id: None,
862 })
863 }
864 }
865
866 impl TestItem {
867 pub fn new() -> Self {
868 Self {
869 state: String::new(),
870 label: String::new(),
871 save_count: 0,
872 save_as_count: 0,
873 reload_count: 0,
874 is_dirty: false,
875 has_conflict: false,
876 project_items: Vec::new(),
877 is_singleton: true,
878 nav_history: None,
879 tab_descriptions: None,
880 tab_detail: Default::default(),
881 workspace_id: 0,
882 }
883 }
884
885 pub fn new_deserialized(id: WorkspaceId) -> Self {
886 let mut this = Self::new();
887 this.workspace_id = id;
888 this
889 }
890
891 pub fn with_label(mut self, state: &str) -> Self {
892 self.label = state.to_string();
893 self
894 }
895
896 pub fn with_singleton(mut self, singleton: bool) -> Self {
897 self.is_singleton = singleton;
898 self
899 }
900
901 pub fn with_dirty(mut self, dirty: bool) -> Self {
902 self.is_dirty = dirty;
903 self
904 }
905
906 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
907 self.has_conflict = has_conflict;
908 self
909 }
910
911 pub fn with_project_items(mut self, items: &[ModelHandle<TestProjectItem>]) -> Self {
912 self.project_items.clear();
913 self.project_items.extend(items.iter().cloned());
914 self
915 }
916
917 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
918 self.push_to_nav_history(cx);
919 self.state = state;
920 }
921
922 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
923 if let Some(history) = &mut self.nav_history {
924 history.push(Some(Box::new(self.state.clone())), cx);
925 }
926 }
927 }
928
929 impl Entity for TestItem {
930 type Event = TestItemEvent;
931 }
932
933 impl View for TestItem {
934 fn ui_name() -> &'static str {
935 "TestItem"
936 }
937
938 fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
939 Empty::new().into_any()
940 }
941 }
942
943 impl Item for TestItem {
944 fn tab_description(&self, detail: usize, _: &AppContext) -> Option<Cow<str>> {
945 self.tab_descriptions.as_ref().and_then(|descriptions| {
946 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
947 Some(description.into())
948 })
949 }
950
951 fn tab_content<V: 'static>(
952 &self,
953 detail: Option<usize>,
954 _: &theme::Tab,
955 _: &AppContext,
956 ) -> AnyElement<V> {
957 self.tab_detail.set(detail);
958 Empty::new().into_any()
959 }
960
961 fn for_each_project_item(
962 &self,
963 cx: &AppContext,
964 f: &mut dyn FnMut(usize, &dyn project::Item),
965 ) {
966 self.project_items
967 .iter()
968 .for_each(|item| f(item.id(), item.read(cx)))
969 }
970
971 fn is_singleton(&self, _: &AppContext) -> bool {
972 self.is_singleton
973 }
974
975 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
976 self.nav_history = Some(history);
977 }
978
979 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
980 let state = *state.downcast::<String>().unwrap_or_default();
981 if state != self.state {
982 self.state = state;
983 true
984 } else {
985 false
986 }
987 }
988
989 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
990 self.push_to_nav_history(cx);
991 }
992
993 fn clone_on_split(
994 &self,
995 _workspace_id: WorkspaceId,
996 _: &mut ViewContext<Self>,
997 ) -> Option<Self>
998 where
999 Self: Sized,
1000 {
1001 Some(self.clone())
1002 }
1003
1004 fn is_dirty(&self, _: &AppContext) -> bool {
1005 self.is_dirty
1006 }
1007
1008 fn has_conflict(&self, _: &AppContext) -> bool {
1009 self.has_conflict
1010 }
1011
1012 fn can_save(&self, cx: &AppContext) -> bool {
1013 !self.project_items.is_empty()
1014 && self
1015 .project_items
1016 .iter()
1017 .all(|item| item.read(cx).entry_id.is_some())
1018 }
1019
1020 fn save(
1021 &mut self,
1022 _: ModelHandle<Project>,
1023 _: &mut ViewContext<Self>,
1024 ) -> Task<anyhow::Result<()>> {
1025 self.save_count += 1;
1026 self.is_dirty = false;
1027 Task::ready(Ok(()))
1028 }
1029
1030 fn save_as(
1031 &mut self,
1032 _: ModelHandle<Project>,
1033 _: std::path::PathBuf,
1034 _: &mut ViewContext<Self>,
1035 ) -> Task<anyhow::Result<()>> {
1036 self.save_as_count += 1;
1037 self.is_dirty = false;
1038 Task::ready(Ok(()))
1039 }
1040
1041 fn reload(
1042 &mut self,
1043 _: ModelHandle<Project>,
1044 _: &mut ViewContext<Self>,
1045 ) -> Task<anyhow::Result<()>> {
1046 self.reload_count += 1;
1047 self.is_dirty = false;
1048 Task::ready(Ok(()))
1049 }
1050
1051 fn to_item_events(_: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
1052 [ItemEvent::UpdateTab, ItemEvent::Edit].into()
1053 }
1054
1055 fn serialized_item_kind() -> Option<&'static str> {
1056 Some("TestItem")
1057 }
1058
1059 fn deserialize(
1060 _project: ModelHandle<Project>,
1061 _workspace: WeakViewHandle<Workspace>,
1062 workspace_id: WorkspaceId,
1063 _item_id: ItemId,
1064 cx: &mut ViewContext<Pane>,
1065 ) -> Task<anyhow::Result<ViewHandle<Self>>> {
1066 let view = cx.add_view(|_cx| Self::new_deserialized(workspace_id));
1067 Task::Ready(Some(anyhow::Ok(view)))
1068 }
1069 }
1070}