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