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