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