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 /// Whether to show the Git file status on a tab item.
64 ///
65 /// Default: true
66 git_status: Option<bool>,
67 /// Position of the close button in a tab.
68 ///
69 /// Default: right
70 close_position: Option<ClosePosition>,
71}
72
73impl Settings for ItemSettings {
74 const KEY: Option<&'static str> = Some("tabs");
75
76 type FileContent = ItemSettingsContent;
77
78 fn load(
79 default_value: &Self::FileContent,
80 user_values: &[&Self::FileContent],
81 _: &mut AppContext,
82 ) -> Result<Self> {
83 Self::load_via_json_merge(default_value, user_values)
84 }
85}
86
87#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
88pub enum ItemEvent {
89 CloseItem,
90 UpdateTab,
91 UpdateBreadcrumbs,
92 Edit,
93}
94
95// TODO: Combine this with existing HighlightedText struct?
96pub struct BreadcrumbText {
97 pub text: String,
98 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
99}
100
101pub trait Item: FocusableView + EventEmitter<Self::Event> {
102 type Event;
103
104 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
105 fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
106 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
107 false
108 }
109 fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
110 None
111 }
112 fn tab_description(&self, _: usize, _: &AppContext) -> Option<SharedString> {
113 None
114 }
115 fn tab_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement;
116
117 fn telemetry_event_text(&self) -> Option<&'static str>;
118
119 /// (model id, Item)
120 fn for_each_project_item(
121 &self,
122 _: &AppContext,
123 _: &mut dyn FnMut(EntityId, &dyn project::Item),
124 ) {
125 }
126 fn is_singleton(&self, _cx: &AppContext) -> bool {
127 false
128 }
129 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
130 fn clone_on_split(
131 &self,
132 _workspace_id: WorkspaceId,
133 _: &mut ViewContext<Self>,
134 ) -> Option<View<Self>>
135 where
136 Self: Sized,
137 {
138 None
139 }
140 fn is_dirty(&self, _: &AppContext) -> bool {
141 false
142 }
143 fn has_conflict(&self, _: &AppContext) -> bool {
144 false
145 }
146 fn can_save(&self, _cx: &AppContext) -> bool {
147 false
148 }
149 fn save(&mut self, _project: Model<Project>, _cx: &mut ViewContext<Self>) -> Task<Result<()>> {
150 unimplemented!("save() must be implemented if can_save() returns true")
151 }
152 fn save_as(
153 &mut self,
154 _project: Model<Project>,
155 _abs_path: PathBuf,
156 _cx: &mut ViewContext<Self>,
157 ) -> Task<Result<()>> {
158 unimplemented!("save_as() must be implemented if can_save() returns true")
159 }
160 fn reload(
161 &mut self,
162 _project: Model<Project>,
163 _cx: &mut ViewContext<Self>,
164 ) -> Task<Result<()>> {
165 unimplemented!("reload() must be implemented if can_save() returns true")
166 }
167
168 fn to_item_events(event: &Self::Event, f: impl FnMut(ItemEvent));
169
170 fn act_as_type<'a>(
171 &'a self,
172 type_id: TypeId,
173 self_handle: &'a View<Self>,
174 _: &'a AppContext,
175 ) -> Option<AnyView> {
176 if TypeId::of::<Self>() == type_id {
177 Some(self_handle.clone().into())
178 } else {
179 None
180 }
181 }
182
183 fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
184 None
185 }
186
187 fn breadcrumb_location(&self) -> ToolbarItemLocation {
188 ToolbarItemLocation::Hidden
189 }
190
191 fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
192 None
193 }
194
195 fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
196
197 fn serialized_item_kind() -> Option<&'static str> {
198 None
199 }
200
201 fn deserialize(
202 _project: Model<Project>,
203 _workspace: WeakView<Workspace>,
204 _workspace_id: WorkspaceId,
205 _item_id: ItemId,
206 _cx: &mut ViewContext<Pane>,
207 ) -> Task<Result<View<Self>>> {
208 unimplemented!(
209 "deserialize() must be implemented if serialized_item_kind() returns Some(_)"
210 )
211 }
212 fn show_toolbar(&self) -> bool {
213 true
214 }
215 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Point<Pixels>> {
216 None
217 }
218}
219
220pub trait ItemHandle: 'static + Send {
221 fn subscribe_to_item_events(
222 &self,
223 cx: &mut WindowContext,
224 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
225 ) -> gpui::Subscription;
226 fn focus_handle(&self, cx: &WindowContext) -> FocusHandle;
227 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>;
228 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>;
229 fn tab_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement;
230 fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str>;
231 fn dragged_tab_content(&self, detail: Option<usize>, cx: &WindowContext) -> AnyElement;
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<[EntityId; 3]>;
235 fn for_each_project_item(
236 &self,
237 _: &AppContext,
238 _: &mut dyn FnMut(EntityId, &dyn project::Item),
239 );
240 fn is_singleton(&self, cx: &AppContext) -> bool;
241 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
242 fn clone_on_split(
243 &self,
244 workspace_id: WorkspaceId,
245 cx: &mut WindowContext,
246 ) -> Option<Box<dyn ItemHandle>>;
247 fn added_to_pane(
248 &self,
249 workspace: &mut Workspace,
250 pane: View<Pane>,
251 cx: &mut ViewContext<Workspace>,
252 );
253 fn deactivated(&self, cx: &mut WindowContext);
254 fn workspace_deactivated(&self, cx: &mut WindowContext);
255 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
256 fn item_id(&self) -> EntityId;
257 fn to_any(&self) -> AnyView;
258 fn is_dirty(&self, cx: &AppContext) -> bool;
259 fn has_conflict(&self, cx: &AppContext) -> bool;
260 fn can_save(&self, cx: &AppContext) -> bool;
261 fn save(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
262 fn save_as(
263 &self,
264 project: Model<Project>,
265 abs_path: PathBuf,
266 cx: &mut WindowContext,
267 ) -> Task<Result<()>>;
268 fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
269 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyView>;
270 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
271 fn on_release(
272 &self,
273 cx: &mut AppContext,
274 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
275 ) -> gpui::Subscription;
276 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
277 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
278 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
279 fn serialized_item_kind(&self) -> Option<&'static str>;
280 fn show_toolbar(&self, cx: &AppContext) -> bool;
281 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>>;
282}
283
284pub trait WeakItemHandle: Send + Sync {
285 fn id(&self) -> EntityId;
286 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
287}
288
289impl dyn ItemHandle {
290 pub fn downcast<V: 'static>(&self) -> Option<View<V>> {
291 self.to_any().downcast().ok()
292 }
293
294 pub fn act_as<V: 'static>(&self, cx: &AppContext) -> Option<View<V>> {
295 self.act_as_type(TypeId::of::<V>(), cx)
296 .and_then(|t| t.downcast().ok())
297 }
298}
299
300impl<T: Item> ItemHandle for View<T> {
301 fn subscribe_to_item_events(
302 &self,
303 cx: &mut WindowContext,
304 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
305 ) -> gpui::Subscription {
306 cx.subscribe(self, move |_, event, cx| {
307 T::to_item_events(event, |item_event| handler(item_event, cx));
308 })
309 }
310
311 fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
312 self.focus_handle(cx)
313 }
314
315 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
316 self.read(cx).tab_tooltip_text(cx)
317 }
318
319 fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str> {
320 self.read(cx).telemetry_event_text()
321 }
322
323 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
324 self.read(cx).tab_description(detail, cx)
325 }
326
327 fn tab_content(&self, detail: Option<usize>, selected: bool, cx: &WindowContext) -> AnyElement {
328 self.read(cx).tab_content(detail, selected, cx)
329 }
330
331 fn dragged_tab_content(&self, detail: Option<usize>, cx: &WindowContext) -> AnyElement {
332 self.read(cx).tab_content(detail, true, cx)
333 }
334
335 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
336 let this = self.read(cx);
337 let mut result = None;
338 if this.is_singleton(cx) {
339 this.for_each_project_item(cx, &mut |_, item| {
340 result = item.project_path(cx);
341 });
342 }
343 result
344 }
345
346 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
347 let mut result = SmallVec::new();
348 self.read(cx).for_each_project_item(cx, &mut |_, item| {
349 if let Some(id) = item.entry_id(cx) {
350 result.push(id);
351 }
352 });
353 result
354 }
355
356 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]> {
357 let mut result = SmallVec::new();
358 self.read(cx).for_each_project_item(cx, &mut |id, _| {
359 result.push(id);
360 });
361 result
362 }
363
364 fn for_each_project_item(
365 &self,
366 cx: &AppContext,
367 f: &mut dyn FnMut(EntityId, &dyn project::Item),
368 ) {
369 self.read(cx).for_each_project_item(cx, f)
370 }
371
372 fn is_singleton(&self, cx: &AppContext) -> bool {
373 self.read(cx).is_singleton(cx)
374 }
375
376 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
377 Box::new(self.clone())
378 }
379
380 fn clone_on_split(
381 &self,
382 workspace_id: WorkspaceId,
383 cx: &mut WindowContext,
384 ) -> Option<Box<dyn ItemHandle>> {
385 self.update(cx, |item, cx| item.clone_on_split(workspace_id, cx))
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: View<Pane>,
393 cx: &mut ViewContext<Workspace>,
394 ) {
395 let weak_item = self.downgrade();
396 let history = pane.read(cx).nav_history_for_item(self);
397 self.update(cx, |this, cx| {
398 this.set_nav_history(history, cx);
399 this.added_to_workspace(workspace, cx);
400 });
401
402 if let Some(followed_item) = self.to_followable_item_handle(cx) {
403 if let Some(message) = followed_item.to_state_proto(cx) {
404 workspace.update_followers(
405 followed_item.is_project_item(cx),
406 proto::update_followers::Variant::CreateView(proto::View {
407 id: followed_item
408 .remote_id(&workspace.app_state.client, cx)
409 .map(|id| id.to_proto()),
410 variant: Some(message),
411 leader_id: workspace.leader_for_pane(&pane),
412 }),
413 cx,
414 );
415 }
416 }
417
418 if workspace
419 .panes_by_item
420 .insert(self.item_id(), pane.downgrade())
421 .is_none()
422 {
423 let mut pending_autosave = DelayedDebouncedEditAction::new();
424 let pending_update = Rc::new(RefCell::new(None));
425 let pending_update_scheduled = Arc::new(AtomicBool::new(false));
426
427 let mut event_subscription =
428 Some(cx.subscribe(self, move |workspace, item, event, cx| {
429 let pane = if let Some(pane) = workspace
430 .panes_by_item
431 .get(&item.item_id())
432 .and_then(|pane| pane.upgrade())
433 {
434 pane
435 } else {
436 log::error!("unexpected item event after pane was dropped");
437 return;
438 };
439
440 if let Some(item) = item.to_followable_item_handle(cx) {
441 let is_project_item = item.is_project_item(cx);
442 let leader_id = workspace.leader_for_pane(&pane);
443
444 let follow_event = item.to_follow_event(event);
445 if leader_id.is_some()
446 && matches!(follow_event, Some(FollowEvent::Unfollow))
447 {
448 workspace.unfollow(&pane, cx);
449 }
450
451 if item.add_event_to_update_proto(
452 event,
453 &mut *pending_update.borrow_mut(),
454 cx,
455 ) && !pending_update_scheduled.load(Ordering::SeqCst)
456 {
457 pending_update_scheduled.store(true, Ordering::SeqCst);
458 cx.defer({
459 let pending_update = pending_update.clone();
460 let pending_update_scheduled = pending_update_scheduled.clone();
461 move |this, cx| {
462 pending_update_scheduled.store(false, Ordering::SeqCst);
463 this.update_followers(
464 is_project_item,
465 proto::update_followers::Variant::UpdateView(
466 proto::UpdateView {
467 id: item
468 .remote_id(&this.app_state.client, cx)
469 .map(|id| id.to_proto()),
470 variant: pending_update.borrow_mut().take(),
471 leader_id,
472 },
473 ),
474 cx,
475 );
476 }
477 });
478 }
479 }
480
481 T::to_item_events(event, |event| match event {
482 ItemEvent::CloseItem => {
483 pane.update(cx, |pane, cx| {
484 pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
485 })
486 .detach_and_log_err(cx);
487 return;
488 }
489
490 ItemEvent::UpdateTab => {
491 pane.update(cx, |_, cx| {
492 cx.emit(pane::Event::ChangeItemTitle);
493 cx.notify();
494 });
495 }
496
497 ItemEvent::Edit => {
498 let autosave = WorkspaceSettings::get_global(cx).autosave;
499 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
500 let delay = Duration::from_millis(milliseconds);
501 let item = item.clone();
502 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
503 Pane::autosave_item(&item, workspace.project().clone(), cx)
504 });
505 }
506 }
507
508 _ => {}
509 });
510 }));
511
512 cx.on_blur(&self.focus_handle(cx), move |workspace, cx| {
513 if WorkspaceSettings::get_global(cx).autosave == AutosaveSetting::OnFocusChange {
514 if let Some(item) = weak_item.upgrade() {
515 Pane::autosave_item(&item, workspace.project.clone(), cx)
516 .detach_and_log_err(cx);
517 }
518 }
519 })
520 .detach();
521
522 let item_id = self.item_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 item_id(&self) -> EntityId {
548 self.entity_id()
549 }
550
551 fn to_any(&self) -> AnyView {
552 self.clone().into()
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: Model<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: Model<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: Model<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<AnyView> {
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.to_any();
592 Some(builders.get(&item.entity_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) + Send>,
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<Point<Pixels>> {
627 self.read(cx).pixel_position_of_cursor(cx)
628 }
629}
630
631impl From<Box<dyn ItemHandle>> for AnyView {
632 fn from(val: Box<dyn ItemHandle>) -> Self {
633 val.to_any()
634 }
635}
636
637impl From<&Box<dyn ItemHandle>> for AnyView {
638 fn from(val: &Box<dyn ItemHandle>) -> Self {
639 val.to_any()
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 WeakView<T> {
650 fn id(&self) -> EntityId {
651 self.entity_id()
652 }
653
654 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
655 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
656 }
657}
658
659pub trait ProjectItem: Item {
660 type Item: project::Item;
661
662 fn for_project_item(
663 project: Model<Project>,
664 item: Model<Self::Item>,
665 cx: &mut ViewContext<Self>,
666 ) -> Self
667 where
668 Self: Sized;
669}
670
671pub enum FollowEvent {
672 Unfollow,
673}
674
675pub trait FollowableItem: Item {
676 fn remote_id(&self) -> Option<ViewId>;
677 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
678 fn from_state_proto(
679 pane: View<Pane>,
680 project: View<Workspace>,
681 id: ViewId,
682 state: &mut Option<proto::view::Variant>,
683 cx: &mut WindowContext,
684 ) -> Option<Task<Result<View<Self>>>>;
685 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
686 fn add_event_to_update_proto(
687 &self,
688 event: &Self::Event,
689 update: &mut Option<proto::update_view::Variant>,
690 cx: &WindowContext,
691 ) -> bool;
692 fn apply_update_proto(
693 &mut self,
694 project: &Model<Project>,
695 message: proto::update_view::Variant,
696 cx: &mut ViewContext<Self>,
697 ) -> Task<Result<()>>;
698 fn is_project_item(&self, cx: &WindowContext) -> bool;
699 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
700}
701
702pub trait FollowableItemHandle: ItemHandle {
703 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
704 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
705 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
706 fn add_event_to_update_proto(
707 &self,
708 event: &dyn Any,
709 update: &mut Option<proto::update_view::Variant>,
710 cx: &WindowContext,
711 ) -> bool;
712 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
713 fn apply_update_proto(
714 &self,
715 project: &Model<Project>,
716 message: proto::update_view::Variant,
717 cx: &mut WindowContext,
718 ) -> Task<Result<()>>;
719 fn is_project_item(&self, cx: &WindowContext) -> bool;
720}
721
722impl<T: FollowableItem> FollowableItemHandle for View<T> {
723 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
724 self.read(cx).remote_id().or_else(|| {
725 client.peer_id().map(|creator| ViewId {
726 creator,
727 id: self.item_id().as_u64(),
728 })
729 })
730 }
731
732 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
733 self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
734 }
735
736 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
737 self.read(cx).to_state_proto(cx)
738 }
739
740 fn add_event_to_update_proto(
741 &self,
742 event: &dyn Any,
743 update: &mut Option<proto::update_view::Variant>,
744 cx: &WindowContext,
745 ) -> bool {
746 if let Some(event) = event.downcast_ref() {
747 self.read(cx).add_event_to_update_proto(event, update, cx)
748 } else {
749 false
750 }
751 }
752
753 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
754 T::to_follow_event(event.downcast_ref()?)
755 }
756
757 fn apply_update_proto(
758 &self,
759 project: &Model<Project>,
760 message: proto::update_view::Variant,
761 cx: &mut WindowContext,
762 ) -> Task<Result<()>> {
763 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
764 }
765
766 fn is_project_item(&self, cx: &WindowContext) -> bool {
767 self.read(cx).is_project_item(cx)
768 }
769}
770
771#[cfg(any(test, feature = "test-support"))]
772pub mod test {
773 use super::{Item, ItemEvent};
774 use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
775 use gpui::{
776 AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
777 InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
778 VisualContext, WeakView,
779 };
780 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
781 use std::{any::Any, cell::Cell, path::Path};
782
783 pub struct TestProjectItem {
784 pub entry_id: Option<ProjectEntryId>,
785 pub project_path: Option<ProjectPath>,
786 }
787
788 pub struct TestItem {
789 pub workspace_id: WorkspaceId,
790 pub state: String,
791 pub label: String,
792 pub save_count: usize,
793 pub save_as_count: usize,
794 pub reload_count: usize,
795 pub is_dirty: bool,
796 pub is_singleton: bool,
797 pub has_conflict: bool,
798 pub project_items: Vec<Model<TestProjectItem>>,
799 pub nav_history: Option<ItemNavHistory>,
800 pub tab_descriptions: Option<Vec<&'static str>>,
801 pub tab_detail: Cell<Option<usize>>,
802 focus_handle: gpui::FocusHandle,
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 TestProjectItem {
820 pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
821 let entry_id = Some(ProjectEntryId::from_proto(id));
822 let project_path = Some(ProjectPath {
823 worktree_id: WorktreeId::from_usize(0),
824 path: Path::new(path).into(),
825 });
826 cx.new_model(|_| Self {
827 entry_id,
828 project_path,
829 })
830 }
831
832 pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
833 cx.new_model(|_| Self {
834 project_path: None,
835 entry_id: None,
836 })
837 }
838 }
839
840 impl TestItem {
841 pub fn new(cx: &mut ViewContext<Self>) -> Self {
842 Self {
843 state: String::new(),
844 label: String::new(),
845 save_count: 0,
846 save_as_count: 0,
847 reload_count: 0,
848 is_dirty: false,
849 has_conflict: false,
850 project_items: Vec::new(),
851 is_singleton: true,
852 nav_history: None,
853 tab_descriptions: None,
854 tab_detail: Default::default(),
855 workspace_id: 0,
856 focus_handle: cx.focus_handle(),
857 }
858 }
859
860 pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
861 let mut this = Self::new(cx);
862 this.workspace_id = id;
863 this
864 }
865
866 pub fn with_label(mut self, state: &str) -> Self {
867 self.label = state.to_string();
868 self
869 }
870
871 pub fn with_singleton(mut self, singleton: bool) -> Self {
872 self.is_singleton = singleton;
873 self
874 }
875
876 pub fn with_dirty(mut self, dirty: bool) -> Self {
877 self.is_dirty = dirty;
878 self
879 }
880
881 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
882 self.has_conflict = has_conflict;
883 self
884 }
885
886 pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
887 self.project_items.clear();
888 self.project_items.extend(items.iter().cloned());
889 self
890 }
891
892 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
893 self.push_to_nav_history(cx);
894 self.state = state;
895 }
896
897 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
898 if let Some(history) = &mut self.nav_history {
899 history.push(Some(Box::new(self.state.clone())), cx);
900 }
901 }
902 }
903
904 impl Render for TestItem {
905 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
906 gpui::div().track_focus(&self.focus_handle)
907 }
908 }
909
910 impl EventEmitter<ItemEvent> for TestItem {}
911
912 impl FocusableView for TestItem {
913 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
914 self.focus_handle.clone()
915 }
916 }
917
918 impl Item for TestItem {
919 type Event = ItemEvent;
920
921 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
922 f(*event)
923 }
924
925 fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
926 self.tab_descriptions.as_ref().and_then(|descriptions| {
927 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
928 Some(description.into())
929 })
930 }
931
932 fn telemetry_event_text(&self) -> Option<&'static str> {
933 None
934 }
935
936 fn tab_content(
937 &self,
938 detail: Option<usize>,
939 _selected: bool,
940 _cx: &ui::prelude::WindowContext,
941 ) -> AnyElement {
942 self.tab_detail.set(detail);
943 gpui::div().into_any_element()
944 }
945
946 fn for_each_project_item(
947 &self,
948 cx: &AppContext,
949 f: &mut dyn FnMut(EntityId, &dyn project::Item),
950 ) {
951 self.project_items
952 .iter()
953 .for_each(|item| f(item.entity_id(), item.read(cx)))
954 }
955
956 fn is_singleton(&self, _: &AppContext) -> bool {
957 self.is_singleton
958 }
959
960 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
961 self.nav_history = Some(history);
962 }
963
964 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
965 let state = *state.downcast::<String>().unwrap_or_default();
966 if state != self.state {
967 self.state = state;
968 true
969 } else {
970 false
971 }
972 }
973
974 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
975 self.push_to_nav_history(cx);
976 }
977
978 fn clone_on_split(
979 &self,
980 _workspace_id: WorkspaceId,
981 cx: &mut ViewContext<Self>,
982 ) -> Option<View<Self>>
983 where
984 Self: Sized,
985 {
986 Some(cx.new_view(|cx| Self {
987 state: self.state.clone(),
988 label: self.label.clone(),
989 save_count: self.save_count,
990 save_as_count: self.save_as_count,
991 reload_count: self.reload_count,
992 is_dirty: self.is_dirty,
993 is_singleton: self.is_singleton,
994 has_conflict: self.has_conflict,
995 project_items: self.project_items.clone(),
996 nav_history: None,
997 tab_descriptions: None,
998 tab_detail: Default::default(),
999 workspace_id: self.workspace_id,
1000 focus_handle: cx.focus_handle(),
1001 }))
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 _: Model<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 _: Model<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 _: Model<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 serialized_item_kind() -> Option<&'static str> {
1052 Some("TestItem")
1053 }
1054
1055 fn deserialize(
1056 _project: Model<Project>,
1057 _workspace: WeakView<Workspace>,
1058 workspace_id: WorkspaceId,
1059 _item_id: ItemId,
1060 cx: &mut ViewContext<Pane>,
1061 ) -> Task<anyhow::Result<View<Self>>> {
1062 let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1063 Task::Ready(Some(anyhow::Ok(view)))
1064 }
1065 }
1066}