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