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