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