1use crate::{
2 CollaboratorId, DelayedDebouncedEditAction, FollowableViewRegistry, ItemNavHistory,
3 SerializableItemRegistry, ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
4 invalid_buffer_view::InvalidBufferView,
5 pane::{self, Pane},
6 persistence::model::ItemId,
7 searchable::SearchableItemHandle,
8 workspace_settings::{AutosaveSetting, WorkspaceSettings},
9};
10use anyhow::Result;
11use client::{Client, proto};
12use futures::{StreamExt, channel::mpsc};
13use gpui::{
14 Action, AnyElement, AnyView, App, Context, Entity, EntityId, EventEmitter, FocusHandle,
15 Focusable, Font, HighlightStyle, Pixels, Point, Render, SharedString, Task, WeakEntity, Window,
16};
17use project::{Project, ProjectEntryId, ProjectPath};
18pub use settings::{
19 ActivateOnClose, ClosePosition, Settings, SettingsLocation, ShowCloseButton, ShowDiagnostics,
20};
21use smallvec::SmallVec;
22use std::{
23 any::{Any, TypeId},
24 cell::RefCell,
25 ops::Range,
26 path::Path,
27 rc::Rc,
28 sync::Arc,
29 time::Duration,
30};
31use theme::Theme;
32use ui::{Color, Icon, IntoElement, Label, LabelCommon};
33use util::ResultExt;
34
35pub const LEADER_UPDATE_THROTTLE: Duration = Duration::from_millis(200);
36
37#[derive(Clone, Copy, Debug)]
38pub struct SaveOptions {
39 pub format: bool,
40 pub autosave: bool,
41}
42
43impl Default for SaveOptions {
44 fn default() -> Self {
45 Self {
46 format: true,
47 autosave: false,
48 }
49 }
50}
51
52pub struct ItemSettings {
53 pub git_status: bool,
54 pub close_position: ClosePosition,
55 pub activate_on_close: ActivateOnClose,
56 pub file_icons: bool,
57 pub show_diagnostics: ShowDiagnostics,
58 pub show_close_button: ShowCloseButton,
59}
60
61pub struct PreviewTabsSettings {
62 pub enabled: bool,
63 pub enable_preview_from_file_finder: bool,
64 pub enable_preview_from_code_navigation: bool,
65}
66
67impl Settings for ItemSettings {
68 fn from_settings(content: &settings::SettingsContent) -> Self {
69 let tabs = content.tabs.as_ref().unwrap();
70 Self {
71 git_status: tabs.git_status.unwrap(),
72 close_position: tabs.close_position.unwrap(),
73 activate_on_close: tabs.activate_on_close.unwrap(),
74 file_icons: tabs.file_icons.unwrap(),
75 show_diagnostics: tabs.show_diagnostics.unwrap(),
76 show_close_button: tabs.show_close_button.unwrap(),
77 }
78 }
79}
80
81impl Settings for PreviewTabsSettings {
82 fn from_settings(content: &settings::SettingsContent) -> Self {
83 let preview_tabs = content.preview_tabs.as_ref().unwrap();
84 Self {
85 enabled: preview_tabs.enabled.unwrap(),
86 enable_preview_from_file_finder: preview_tabs.enable_preview_from_file_finder.unwrap(),
87 enable_preview_from_code_navigation: preview_tabs
88 .enable_preview_from_code_navigation
89 .unwrap(),
90 }
91 }
92}
93
94#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
95pub enum ItemEvent {
96 CloseItem,
97 UpdateTab,
98 UpdateBreadcrumbs,
99 Edit,
100}
101
102// TODO: Combine this with existing HighlightedText struct?
103pub struct BreadcrumbText {
104 pub text: String,
105 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
106 pub font: Option<Font>,
107}
108
109#[derive(Clone, Copy, Default, Debug)]
110pub struct TabContentParams {
111 pub detail: Option<usize>,
112 pub selected: bool,
113 pub preview: bool,
114 /// Tab content should be deemphasized when active pane does not have focus.
115 pub deemphasized: bool,
116}
117
118impl TabContentParams {
119 /// Returns the text color to be used for the tab content.
120 pub fn text_color(&self) -> Color {
121 if self.deemphasized {
122 if self.selected {
123 Color::Muted
124 } else {
125 Color::Hidden
126 }
127 } else if self.selected {
128 Color::Default
129 } else {
130 Color::Muted
131 }
132 }
133}
134
135pub enum TabTooltipContent {
136 Text(SharedString),
137 Custom(Box<dyn Fn(&mut Window, &mut App) -> AnyView>),
138}
139
140#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
141pub enum ItemBufferKind {
142 Multibuffer,
143 Singleton,
144 None,
145}
146
147pub trait Item: Focusable + EventEmitter<Self::Event> + Render + Sized {
148 type Event;
149
150 /// Returns the tab contents.
151 ///
152 /// By default this returns a [`Label`] that displays that text from
153 /// `tab_content_text`.
154 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
155 let text = self.tab_content_text(params.detail.unwrap_or_default(), cx);
156
157 Label::new(text)
158 .color(params.text_color())
159 .into_any_element()
160 }
161
162 /// Returns the textual contents of the tab.
163 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString;
164
165 /// Returns the suggested filename for saving this item.
166 /// By default, returns the tab content text.
167 fn suggested_filename(&self, cx: &App) -> SharedString {
168 self.tab_content_text(0, cx)
169 }
170
171 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
172 None
173 }
174
175 /// Returns the tab tooltip text.
176 ///
177 /// Use this if you don't need to customize the tab tooltip content.
178 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
179 None
180 }
181
182 /// Returns the tab tooltip content.
183 ///
184 /// By default this returns a Tooltip text from
185 /// `tab_tooltip_text`.
186 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
187 self.tab_tooltip_text(cx).map(TabTooltipContent::Text)
188 }
189
190 fn to_item_events(_event: &Self::Event, _f: impl FnMut(ItemEvent)) {}
191
192 fn deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
193 fn discarded(&self, _project: Entity<Project>, _window: &mut Window, _cx: &mut Context<Self>) {}
194 fn on_removed(&self, _cx: &App) {}
195 fn workspace_deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
196 fn navigate(&mut self, _: Box<dyn Any>, _window: &mut Window, _: &mut Context<Self>) -> bool {
197 false
198 }
199
200 fn telemetry_event_text(&self) -> Option<&'static str> {
201 None
202 }
203
204 /// (model id, Item)
205 fn for_each_project_item(
206 &self,
207 _: &App,
208 _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
209 ) {
210 }
211 fn buffer_kind(&self, _cx: &App) -> ItemBufferKind {
212 ItemBufferKind::None
213 }
214 fn set_nav_history(&mut self, _: ItemNavHistory, _window: &mut Window, _: &mut Context<Self>) {}
215 fn clone_on_split(
216 &self,
217 _workspace_id: Option<WorkspaceId>,
218 _window: &mut Window,
219 _: &mut Context<Self>,
220 ) -> Option<Entity<Self>>
221 where
222 Self: Sized,
223 {
224 None
225 }
226 fn is_dirty(&self, _: &App) -> bool {
227 false
228 }
229 fn has_deleted_file(&self, _: &App) -> bool {
230 false
231 }
232 fn has_conflict(&self, _: &App) -> bool {
233 false
234 }
235 fn can_save(&self, _cx: &App) -> bool {
236 false
237 }
238 fn can_save_as(&self, _: &App) -> bool {
239 false
240 }
241 fn save(
242 &mut self,
243 _options: SaveOptions,
244 _project: Entity<Project>,
245 _window: &mut Window,
246 _cx: &mut Context<Self>,
247 ) -> Task<Result<()>> {
248 unimplemented!("save() must be implemented if can_save() returns true")
249 }
250 fn save_as(
251 &mut self,
252 _project: Entity<Project>,
253 _path: ProjectPath,
254 _window: &mut Window,
255 _cx: &mut Context<Self>,
256 ) -> Task<Result<()>> {
257 unimplemented!("save_as() must be implemented if can_save() returns true")
258 }
259 fn reload(
260 &mut self,
261 _project: Entity<Project>,
262 _window: &mut Window,
263 _cx: &mut Context<Self>,
264 ) -> Task<Result<()>> {
265 unimplemented!("reload() must be implemented if can_save() returns true")
266 }
267
268 fn act_as_type<'a>(
269 &'a self,
270 type_id: TypeId,
271 self_handle: &'a Entity<Self>,
272 _: &'a App,
273 ) -> Option<AnyView> {
274 if TypeId::of::<Self>() == type_id {
275 Some(self_handle.clone().into())
276 } else {
277 None
278 }
279 }
280
281 fn as_searchable(&self, _: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
282 None
283 }
284
285 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
286 ToolbarItemLocation::Hidden
287 }
288
289 fn breadcrumbs(&self, _theme: &Theme, _cx: &App) -> Option<Vec<BreadcrumbText>> {
290 None
291 }
292
293 fn added_to_workspace(
294 &mut self,
295 _workspace: &mut Workspace,
296 _window: &mut Window,
297 _cx: &mut Context<Self>,
298 ) {
299 }
300
301 fn show_toolbar(&self) -> bool {
302 true
303 }
304
305 fn pixel_position_of_cursor(&self, _: &App) -> Option<Point<Pixels>> {
306 None
307 }
308
309 fn preserve_preview(&self, _cx: &App) -> bool {
310 false
311 }
312
313 fn include_in_nav_history() -> bool {
314 true
315 }
316}
317
318pub trait SerializableItem: Item {
319 fn serialized_item_kind() -> &'static str;
320
321 fn cleanup(
322 workspace_id: WorkspaceId,
323 alive_items: Vec<ItemId>,
324 window: &mut Window,
325 cx: &mut App,
326 ) -> Task<Result<()>>;
327
328 fn deserialize(
329 _project: Entity<Project>,
330 _workspace: WeakEntity<Workspace>,
331 _workspace_id: WorkspaceId,
332 _item_id: ItemId,
333 _window: &mut Window,
334 _cx: &mut App,
335 ) -> Task<Result<Entity<Self>>>;
336
337 fn serialize(
338 &mut self,
339 workspace: &mut Workspace,
340 item_id: ItemId,
341 closing: bool,
342 window: &mut Window,
343 cx: &mut Context<Self>,
344 ) -> Option<Task<Result<()>>>;
345
346 fn should_serialize(&self, event: &Self::Event) -> bool;
347}
348
349pub trait SerializableItemHandle: ItemHandle {
350 fn serialized_item_kind(&self) -> &'static str;
351 fn serialize(
352 &self,
353 workspace: &mut Workspace,
354 closing: bool,
355 window: &mut Window,
356 cx: &mut App,
357 ) -> Option<Task<Result<()>>>;
358 fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool;
359}
360
361impl<T> SerializableItemHandle for Entity<T>
362where
363 T: SerializableItem,
364{
365 fn serialized_item_kind(&self) -> &'static str {
366 T::serialized_item_kind()
367 }
368
369 fn serialize(
370 &self,
371 workspace: &mut Workspace,
372 closing: bool,
373 window: &mut Window,
374 cx: &mut App,
375 ) -> Option<Task<Result<()>>> {
376 self.update(cx, |this, cx| {
377 this.serialize(workspace, cx.entity_id().as_u64(), closing, window, cx)
378 })
379 }
380
381 fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool {
382 event
383 .downcast_ref::<T::Event>()
384 .is_some_and(|event| self.read(cx).should_serialize(event))
385 }
386}
387
388pub trait ItemHandle: 'static + Send {
389 fn item_focus_handle(&self, cx: &App) -> FocusHandle;
390 fn subscribe_to_item_events(
391 &self,
392 window: &mut Window,
393 cx: &mut App,
394 handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
395 ) -> gpui::Subscription;
396 fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement;
397 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString;
398 fn suggested_filename(&self, cx: &App) -> SharedString;
399 fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon>;
400 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString>;
401 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent>;
402 fn telemetry_event_text(&self, cx: &App) -> Option<&'static str>;
403 fn dragged_tab_content(
404 &self,
405 params: TabContentParams,
406 window: &Window,
407 cx: &App,
408 ) -> AnyElement;
409 fn project_path(&self, cx: &App) -> Option<ProjectPath>;
410 fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]>;
411 fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]>;
412 fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]>;
413 fn for_each_project_item(
414 &self,
415 _: &App,
416 _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
417 );
418 fn buffer_kind(&self, cx: &App) -> ItemBufferKind;
419 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
420 fn clone_on_split(
421 &self,
422 workspace_id: Option<WorkspaceId>,
423 window: &mut Window,
424 cx: &mut App,
425 ) -> Option<Box<dyn ItemHandle>>;
426 fn added_to_pane(
427 &self,
428 workspace: &mut Workspace,
429 pane: Entity<Pane>,
430 window: &mut Window,
431 cx: &mut Context<Workspace>,
432 );
433 fn deactivated(&self, window: &mut Window, cx: &mut App);
434 fn on_removed(&self, cx: &App);
435 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App);
436 fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool;
437 fn item_id(&self) -> EntityId;
438 fn to_any(&self) -> AnyView;
439 fn is_dirty(&self, cx: &App) -> bool;
440 fn has_deleted_file(&self, cx: &App) -> bool;
441 fn has_conflict(&self, cx: &App) -> bool;
442 fn can_save(&self, cx: &App) -> bool;
443 fn can_save_as(&self, cx: &App) -> bool;
444 fn save(
445 &self,
446 options: SaveOptions,
447 project: Entity<Project>,
448 window: &mut Window,
449 cx: &mut App,
450 ) -> Task<Result<()>>;
451 fn save_as(
452 &self,
453 project: Entity<Project>,
454 path: ProjectPath,
455 window: &mut Window,
456 cx: &mut App,
457 ) -> Task<Result<()>>;
458 fn reload(
459 &self,
460 project: Entity<Project>,
461 window: &mut Window,
462 cx: &mut App,
463 ) -> Task<Result<()>>;
464 fn act_as_type(&self, type_id: TypeId, cx: &App) -> Option<AnyView>;
465 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>>;
466 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>>;
467 fn on_release(
468 &self,
469 cx: &mut App,
470 callback: Box<dyn FnOnce(&mut App) + Send>,
471 ) -> gpui::Subscription;
472 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>>;
473 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation;
474 fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>>;
475 fn show_toolbar(&self, cx: &App) -> bool;
476 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>>;
477 fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
478 fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings;
479 fn preserve_preview(&self, cx: &App) -> bool;
480 fn include_in_nav_history(&self) -> bool;
481 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App);
482 fn can_autosave(&self, cx: &App) -> bool {
483 let is_deleted = self.project_entry_ids(cx).is_empty();
484 self.is_dirty(cx) && !self.has_conflict(cx) && self.can_save(cx) && !is_deleted
485 }
486}
487
488pub trait WeakItemHandle: Send + Sync {
489 fn id(&self) -> EntityId;
490 fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
491 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
492}
493
494impl dyn ItemHandle {
495 pub fn downcast<V: 'static>(&self) -> Option<Entity<V>> {
496 self.to_any().downcast().ok()
497 }
498
499 pub fn act_as<V: 'static>(&self, cx: &App) -> Option<Entity<V>> {
500 self.act_as_type(TypeId::of::<V>(), cx)
501 .and_then(|t| t.downcast().ok())
502 }
503}
504
505impl<T: Item> ItemHandle for Entity<T> {
506 fn subscribe_to_item_events(
507 &self,
508 window: &mut Window,
509 cx: &mut App,
510 handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
511 ) -> gpui::Subscription {
512 window.subscribe(self, cx, move |_, event, window, cx| {
513 T::to_item_events(event, |item_event| handler(item_event, window, cx));
514 })
515 }
516
517 fn item_focus_handle(&self, cx: &App) -> FocusHandle {
518 self.read(cx).focus_handle(cx)
519 }
520
521 fn telemetry_event_text(&self, cx: &App) -> Option<&'static str> {
522 self.read(cx).telemetry_event_text()
523 }
524
525 fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
526 self.read(cx).tab_content(params, window, cx)
527 }
528 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
529 self.read(cx).tab_content_text(detail, cx)
530 }
531
532 fn suggested_filename(&self, cx: &App) -> SharedString {
533 self.read(cx).suggested_filename(cx)
534 }
535
536 fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon> {
537 self.read(cx).tab_icon(window, cx)
538 }
539
540 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
541 self.read(cx).tab_tooltip_content(cx)
542 }
543
544 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
545 self.read(cx).tab_tooltip_text(cx)
546 }
547
548 fn dragged_tab_content(
549 &self,
550 params: TabContentParams,
551 window: &Window,
552 cx: &App,
553 ) -> AnyElement {
554 self.read(cx).tab_content(
555 TabContentParams {
556 selected: true,
557 ..params
558 },
559 window,
560 cx,
561 )
562 }
563
564 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
565 let this = self.read(cx);
566 let mut result = None;
567 if this.buffer_kind(cx) == ItemBufferKind::Singleton {
568 this.for_each_project_item(cx, &mut |_, item| {
569 result = item.project_path(cx);
570 });
571 }
572 result
573 }
574
575 fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings {
576 if let Some(project_path) = self.project_path(cx) {
577 WorkspaceSettings::get(
578 Some(SettingsLocation {
579 worktree_id: project_path.worktree_id,
580 path: &project_path.path,
581 }),
582 cx,
583 )
584 } else {
585 WorkspaceSettings::get_global(cx)
586 }
587 }
588
589 fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]> {
590 let mut result = SmallVec::new();
591 self.read(cx).for_each_project_item(cx, &mut |_, item| {
592 if let Some(id) = item.entry_id(cx) {
593 result.push(id);
594 }
595 });
596 result
597 }
598
599 fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]> {
600 let mut result = SmallVec::new();
601 self.read(cx).for_each_project_item(cx, &mut |_, item| {
602 if let Some(id) = item.project_path(cx) {
603 result.push(id);
604 }
605 });
606 result
607 }
608
609 fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]> {
610 let mut result = SmallVec::new();
611 self.read(cx).for_each_project_item(cx, &mut |id, _| {
612 result.push(id);
613 });
614 result
615 }
616
617 fn for_each_project_item(
618 &self,
619 cx: &App,
620 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
621 ) {
622 self.read(cx).for_each_project_item(cx, f)
623 }
624
625 fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
626 self.read(cx).buffer_kind(cx)
627 }
628
629 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
630 Box::new(self.clone())
631 }
632
633 fn clone_on_split(
634 &self,
635 workspace_id: Option<WorkspaceId>,
636 window: &mut Window,
637 cx: &mut App,
638 ) -> Option<Box<dyn ItemHandle>> {
639 self.update(cx, |item, cx| item.clone_on_split(workspace_id, window, cx))
640 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
641 }
642
643 fn added_to_pane(
644 &self,
645 workspace: &mut Workspace,
646 pane: Entity<Pane>,
647 window: &mut Window,
648 cx: &mut Context<Workspace>,
649 ) {
650 let weak_item = self.downgrade();
651 let history = pane.read(cx).nav_history_for_item(self);
652 self.update(cx, |this, cx| {
653 this.set_nav_history(history, window, cx);
654 this.added_to_workspace(workspace, window, cx);
655 });
656
657 if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
658 workspace
659 .enqueue_item_serialization(serializable_item)
660 .log_err();
661 }
662
663 if workspace
664 .panes_by_item
665 .insert(self.item_id(), pane.downgrade())
666 .is_none()
667 {
668 let mut pending_autosave = DelayedDebouncedEditAction::new();
669 let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
670 let pending_update = Rc::new(RefCell::new(None));
671
672 let mut send_follower_updates = None;
673 if let Some(item) = self.to_followable_item_handle(cx) {
674 let is_project_item = item.is_project_item(window, cx);
675 let item = item.downgrade();
676
677 send_follower_updates = Some(cx.spawn_in(window, {
678 let pending_update = pending_update.clone();
679 async move |workspace, cx| {
680 while let Some(mut leader_id) = pending_update_rx.next().await {
681 while let Ok(Some(id)) = pending_update_rx.try_next() {
682 leader_id = id;
683 }
684
685 workspace.update_in(cx, |workspace, window, cx| {
686 let Some(item) = item.upgrade() else { return };
687 workspace.update_followers(
688 is_project_item,
689 proto::update_followers::Variant::UpdateView(
690 proto::UpdateView {
691 id: item
692 .remote_id(workspace.client(), window, cx)
693 .and_then(|id| id.to_proto()),
694 variant: pending_update.borrow_mut().take(),
695 leader_id,
696 },
697 ),
698 window,
699 cx,
700 );
701 })?;
702 cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
703 }
704 anyhow::Ok(())
705 }
706 }));
707 }
708
709 let mut event_subscription = Some(cx.subscribe_in(
710 self,
711 window,
712 move |workspace, item: &Entity<T>, event, window, cx| {
713 let pane = if let Some(pane) = workspace
714 .panes_by_item
715 .get(&item.item_id())
716 .and_then(|pane| pane.upgrade())
717 {
718 pane
719 } else {
720 return;
721 };
722
723 if let Some(item) = item.to_followable_item_handle(cx) {
724 let leader_id = workspace.leader_for_pane(&pane);
725
726 if let Some(leader_id) = leader_id
727 && let Some(FollowEvent::Unfollow) = item.to_follow_event(event)
728 {
729 workspace.unfollow(leader_id, window, cx);
730 }
731
732 if item.item_focus_handle(cx).contains_focused(window, cx) {
733 match leader_id {
734 Some(CollaboratorId::Agent) => {}
735 Some(CollaboratorId::PeerId(leader_peer_id)) => {
736 item.add_event_to_update_proto(
737 event,
738 &mut pending_update.borrow_mut(),
739 window,
740 cx,
741 );
742 pending_update_tx.unbounded_send(Some(leader_peer_id)).ok();
743 }
744 None => {
745 item.add_event_to_update_proto(
746 event,
747 &mut pending_update.borrow_mut(),
748 window,
749 cx,
750 );
751 pending_update_tx.unbounded_send(None).ok();
752 }
753 }
754 }
755 }
756
757 if let Some(item) = item.to_serializable_item_handle(cx)
758 && item.should_serialize(event, cx)
759 {
760 workspace.enqueue_item_serialization(item).ok();
761 }
762
763 T::to_item_events(event, |event| match event {
764 ItemEvent::CloseItem => {
765 pane.update(cx, |pane, cx| {
766 pane.close_item_by_id(
767 item.item_id(),
768 crate::SaveIntent::Close,
769 window,
770 cx,
771 )
772 })
773 .detach_and_log_err(cx);
774 }
775
776 ItemEvent::UpdateTab => {
777 workspace.update_item_dirty_state(item, window, cx);
778
779 if item.has_deleted_file(cx)
780 && !item.is_dirty(cx)
781 && item.workspace_settings(cx).close_on_file_delete
782 {
783 let item_id = item.item_id();
784 let close_item_task = pane.update(cx, |pane, cx| {
785 pane.close_item_by_id(
786 item_id,
787 crate::SaveIntent::Close,
788 window,
789 cx,
790 )
791 });
792 cx.spawn_in(window, {
793 let pane = pane.clone();
794 async move |_workspace, cx| {
795 close_item_task.await?;
796 pane.update(cx, |pane, _cx| {
797 pane.nav_history_mut().remove_item(item_id);
798 })
799 }
800 })
801 .detach_and_log_err(cx);
802 } else {
803 pane.update(cx, |_, cx| {
804 cx.emit(pane::Event::ChangeItemTitle);
805 cx.notify();
806 });
807 }
808 }
809
810 ItemEvent::Edit => {
811 let autosave = item.workspace_settings(cx).autosave;
812
813 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
814 let delay = Duration::from_millis(milliseconds.0);
815 let item = item.clone();
816 pending_autosave.fire_new(
817 delay,
818 window,
819 cx,
820 move |workspace, window, cx| {
821 Pane::autosave_item(
822 &item,
823 workspace.project().clone(),
824 window,
825 cx,
826 )
827 },
828 );
829 }
830 pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
831 }
832
833 _ => {}
834 });
835 },
836 ));
837
838 cx.on_blur(
839 &self.read(cx).focus_handle(cx),
840 window,
841 move |workspace, window, cx| {
842 if let Some(item) = weak_item.upgrade()
843 && item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange
844 {
845 Pane::autosave_item(&item, workspace.project.clone(), window, cx)
846 .detach_and_log_err(cx);
847 }
848 },
849 )
850 .detach();
851
852 let item_id = self.item_id();
853 workspace.update_item_dirty_state(self, window, cx);
854 cx.observe_release_in(self, window, move |workspace, _, _, _| {
855 workspace.panes_by_item.remove(&item_id);
856 event_subscription.take();
857 send_follower_updates.take();
858 })
859 .detach();
860 }
861
862 cx.defer_in(window, |workspace, window, cx| {
863 workspace.serialize_workspace(window, cx);
864 });
865 }
866
867 fn deactivated(&self, window: &mut Window, cx: &mut App) {
868 self.update(cx, |this, cx| this.deactivated(window, cx));
869 }
870
871 fn on_removed(&self, cx: &App) {
872 self.read(cx).on_removed(cx);
873 }
874
875 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
876 self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
877 }
878
879 fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool {
880 self.update(cx, |this, cx| this.navigate(data, window, cx))
881 }
882
883 fn item_id(&self) -> EntityId {
884 self.entity_id()
885 }
886
887 fn to_any(&self) -> AnyView {
888 self.clone().into()
889 }
890
891 fn is_dirty(&self, cx: &App) -> bool {
892 self.read(cx).is_dirty(cx)
893 }
894
895 fn has_deleted_file(&self, cx: &App) -> bool {
896 self.read(cx).has_deleted_file(cx)
897 }
898
899 fn has_conflict(&self, cx: &App) -> bool {
900 self.read(cx).has_conflict(cx)
901 }
902
903 fn can_save(&self, cx: &App) -> bool {
904 self.read(cx).can_save(cx)
905 }
906
907 fn can_save_as(&self, cx: &App) -> bool {
908 self.read(cx).can_save_as(cx)
909 }
910
911 fn save(
912 &self,
913 options: SaveOptions,
914 project: Entity<Project>,
915 window: &mut Window,
916 cx: &mut App,
917 ) -> Task<Result<()>> {
918 self.update(cx, |item, cx| item.save(options, project, window, cx))
919 }
920
921 fn save_as(
922 &self,
923 project: Entity<Project>,
924 path: ProjectPath,
925 window: &mut Window,
926 cx: &mut App,
927 ) -> Task<anyhow::Result<()>> {
928 self.update(cx, |item, cx| item.save_as(project, path, window, cx))
929 }
930
931 fn reload(
932 &self,
933 project: Entity<Project>,
934 window: &mut Window,
935 cx: &mut App,
936 ) -> Task<Result<()>> {
937 self.update(cx, |item, cx| item.reload(project, window, cx))
938 }
939
940 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyView> {
941 self.read(cx).act_as_type(type_id, self, cx)
942 }
943
944 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
945 FollowableViewRegistry::to_followable_view(self.clone(), cx)
946 }
947
948 fn on_release(
949 &self,
950 cx: &mut App,
951 callback: Box<dyn FnOnce(&mut App) + Send>,
952 ) -> gpui::Subscription {
953 cx.observe_release(self, move |_, cx| callback(cx))
954 }
955
956 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
957 self.read(cx).as_searchable(self)
958 }
959
960 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
961 self.read(cx).breadcrumb_location(cx)
962 }
963
964 fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
965 self.read(cx).breadcrumbs(theme, cx)
966 }
967
968 fn show_toolbar(&self, cx: &App) -> bool {
969 self.read(cx).show_toolbar()
970 }
971
972 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
973 self.read(cx).pixel_position_of_cursor(cx)
974 }
975
976 fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
977 Box::new(self.downgrade())
978 }
979
980 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
981 SerializableItemRegistry::view_to_serializable_item_handle(self.to_any(), cx)
982 }
983
984 fn preserve_preview(&self, cx: &App) -> bool {
985 self.read(cx).preserve_preview(cx)
986 }
987
988 fn include_in_nav_history(&self) -> bool {
989 T::include_in_nav_history()
990 }
991
992 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
993 self.update(cx, |this, cx| {
994 this.focus_handle(cx).focus(window);
995 window.dispatch_action(action, cx);
996 })
997 }
998}
999
1000impl From<Box<dyn ItemHandle>> for AnyView {
1001 fn from(val: Box<dyn ItemHandle>) -> Self {
1002 val.to_any()
1003 }
1004}
1005
1006impl From<&Box<dyn ItemHandle>> for AnyView {
1007 fn from(val: &Box<dyn ItemHandle>) -> Self {
1008 val.to_any()
1009 }
1010}
1011
1012impl Clone for Box<dyn ItemHandle> {
1013 fn clone(&self) -> Box<dyn ItemHandle> {
1014 self.boxed_clone()
1015 }
1016}
1017
1018impl<T: Item> WeakItemHandle for WeakEntity<T> {
1019 fn id(&self) -> EntityId {
1020 self.entity_id()
1021 }
1022
1023 fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1024 Box::new(self.clone())
1025 }
1026
1027 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1028 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1029 }
1030}
1031
1032#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1033pub struct ProjectItemKind(pub &'static str);
1034
1035pub trait ProjectItem: Item {
1036 type Item: project::ProjectItem;
1037
1038 fn project_item_kind() -> Option<ProjectItemKind> {
1039 None
1040 }
1041
1042 fn for_project_item(
1043 project: Entity<Project>,
1044 pane: Option<&Pane>,
1045 item: Entity<Self::Item>,
1046 window: &mut Window,
1047 cx: &mut Context<Self>,
1048 ) -> Self
1049 where
1050 Self: Sized;
1051
1052 /// A fallback handler, which will be called after [`project::ProjectItem::try_open`] fails,
1053 /// with the error from that failure as an argument.
1054 /// Allows to open an item that can gracefully display and handle errors.
1055 fn for_broken_project_item(
1056 _abs_path: &Path,
1057 _is_local: bool,
1058 _e: &anyhow::Error,
1059 _window: &mut Window,
1060 _cx: &mut App,
1061 ) -> Option<InvalidBufferView>
1062 where
1063 Self: Sized,
1064 {
1065 None
1066 }
1067}
1068
1069#[derive(Debug)]
1070pub enum FollowEvent {
1071 Unfollow,
1072}
1073
1074pub enum Dedup {
1075 KeepExisting,
1076 ReplaceExisting,
1077}
1078
1079pub trait FollowableItem: Item {
1080 fn remote_id(&self) -> Option<ViewId>;
1081 fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant>;
1082 fn from_state_proto(
1083 project: Entity<Workspace>,
1084 id: ViewId,
1085 state: &mut Option<proto::view::Variant>,
1086 window: &mut Window,
1087 cx: &mut App,
1088 ) -> Option<Task<Result<Entity<Self>>>>;
1089 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1090 fn add_event_to_update_proto(
1091 &self,
1092 event: &Self::Event,
1093 update: &mut Option<proto::update_view::Variant>,
1094 window: &Window,
1095 cx: &App,
1096 ) -> bool;
1097 fn apply_update_proto(
1098 &mut self,
1099 project: &Entity<Project>,
1100 message: proto::update_view::Variant,
1101 window: &mut Window,
1102 cx: &mut Context<Self>,
1103 ) -> Task<Result<()>>;
1104 fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1105 fn set_leader_id(
1106 &mut self,
1107 leader_peer_id: Option<CollaboratorId>,
1108 window: &mut Window,
1109 cx: &mut Context<Self>,
1110 );
1111 fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1112 fn update_agent_location(
1113 &mut self,
1114 _location: language::Anchor,
1115 _window: &mut Window,
1116 _cx: &mut Context<Self>,
1117 ) {
1118 }
1119}
1120
1121pub trait FollowableItemHandle: ItemHandle {
1122 fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1123 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1124 fn set_leader_id(
1125 &self,
1126 leader_peer_id: Option<CollaboratorId>,
1127 window: &mut Window,
1128 cx: &mut App,
1129 );
1130 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1131 fn add_event_to_update_proto(
1132 &self,
1133 event: &dyn Any,
1134 update: &mut Option<proto::update_view::Variant>,
1135 window: &mut Window,
1136 cx: &mut App,
1137 ) -> bool;
1138 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1139 fn apply_update_proto(
1140 &self,
1141 project: &Entity<Project>,
1142 message: proto::update_view::Variant,
1143 window: &mut Window,
1144 cx: &mut App,
1145 ) -> Task<Result<()>>;
1146 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1147 fn dedup(
1148 &self,
1149 existing: &dyn FollowableItemHandle,
1150 window: &mut Window,
1151 cx: &mut App,
1152 ) -> Option<Dedup>;
1153 fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App);
1154}
1155
1156impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1157 fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1158 self.read(cx).remote_id().or_else(|| {
1159 client.peer_id().map(|creator| ViewId {
1160 creator: CollaboratorId::PeerId(creator),
1161 id: self.item_id().as_u64(),
1162 })
1163 })
1164 }
1165
1166 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1167 Box::new(self.downgrade())
1168 }
1169
1170 fn set_leader_id(&self, leader_id: Option<CollaboratorId>, window: &mut Window, cx: &mut App) {
1171 self.update(cx, |this, cx| this.set_leader_id(leader_id, window, cx))
1172 }
1173
1174 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1175 self.read(cx).to_state_proto(window, cx)
1176 }
1177
1178 fn add_event_to_update_proto(
1179 &self,
1180 event: &dyn Any,
1181 update: &mut Option<proto::update_view::Variant>,
1182 window: &mut Window,
1183 cx: &mut App,
1184 ) -> bool {
1185 if let Some(event) = event.downcast_ref() {
1186 self.read(cx)
1187 .add_event_to_update_proto(event, update, window, cx)
1188 } else {
1189 false
1190 }
1191 }
1192
1193 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1194 T::to_follow_event(event.downcast_ref()?)
1195 }
1196
1197 fn apply_update_proto(
1198 &self,
1199 project: &Entity<Project>,
1200 message: proto::update_view::Variant,
1201 window: &mut Window,
1202 cx: &mut App,
1203 ) -> Task<Result<()>> {
1204 self.update(cx, |this, cx| {
1205 this.apply_update_proto(project, message, window, cx)
1206 })
1207 }
1208
1209 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1210 self.read(cx).is_project_item(window, cx)
1211 }
1212
1213 fn dedup(
1214 &self,
1215 existing: &dyn FollowableItemHandle,
1216 window: &mut Window,
1217 cx: &mut App,
1218 ) -> Option<Dedup> {
1219 let existing = existing.to_any().downcast::<T>().ok()?;
1220 self.read(cx).dedup(existing.read(cx), window, cx)
1221 }
1222
1223 fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App) {
1224 self.update(cx, |this, cx| {
1225 this.update_agent_location(location, window, cx)
1226 })
1227 }
1228}
1229
1230pub trait WeakFollowableItemHandle: Send + Sync {
1231 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1232}
1233
1234impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1235 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1236 Some(Box::new(self.upgrade()?))
1237 }
1238}
1239
1240#[cfg(any(test, feature = "test-support"))]
1241pub mod test {
1242 use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1243 use crate::{
1244 ItemId, ItemNavHistory, Workspace, WorkspaceId,
1245 item::{ItemBufferKind, SaveOptions},
1246 };
1247 use gpui::{
1248 AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1249 InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1250 };
1251 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1252 use std::{any::Any, cell::Cell};
1253 use util::rel_path::rel_path;
1254
1255 pub struct TestProjectItem {
1256 pub entry_id: Option<ProjectEntryId>,
1257 pub project_path: Option<ProjectPath>,
1258 pub is_dirty: bool,
1259 }
1260
1261 pub struct TestItem {
1262 pub workspace_id: Option<WorkspaceId>,
1263 pub state: String,
1264 pub label: String,
1265 pub save_count: usize,
1266 pub save_as_count: usize,
1267 pub reload_count: usize,
1268 pub is_dirty: bool,
1269 pub buffer_kind: ItemBufferKind,
1270 pub has_conflict: bool,
1271 pub has_deleted_file: bool,
1272 pub project_items: Vec<Entity<TestProjectItem>>,
1273 pub nav_history: Option<ItemNavHistory>,
1274 pub tab_descriptions: Option<Vec<&'static str>>,
1275 pub tab_detail: Cell<Option<usize>>,
1276 serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1277 focus_handle: gpui::FocusHandle,
1278 }
1279
1280 impl project::ProjectItem for TestProjectItem {
1281 fn try_open(
1282 _project: &Entity<Project>,
1283 _path: &ProjectPath,
1284 _cx: &mut App,
1285 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
1286 None
1287 }
1288 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1289 self.entry_id
1290 }
1291
1292 fn project_path(&self, _: &App) -> Option<ProjectPath> {
1293 self.project_path.clone()
1294 }
1295
1296 fn is_dirty(&self) -> bool {
1297 self.is_dirty
1298 }
1299 }
1300
1301 pub enum TestItemEvent {
1302 Edit,
1303 }
1304
1305 impl TestProjectItem {
1306 pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1307 let entry_id = Some(ProjectEntryId::from_proto(id));
1308 let project_path = Some(ProjectPath {
1309 worktree_id: WorktreeId::from_usize(0),
1310 path: rel_path(path).into(),
1311 });
1312 cx.new(|_| Self {
1313 entry_id,
1314 project_path,
1315 is_dirty: false,
1316 })
1317 }
1318
1319 pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1320 cx.new(|_| Self {
1321 project_path: None,
1322 entry_id: None,
1323 is_dirty: false,
1324 })
1325 }
1326
1327 pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1328 let entry_id = Some(ProjectEntryId::from_proto(id));
1329 let project_path = Some(ProjectPath {
1330 worktree_id: WorktreeId::from_usize(0),
1331 path: rel_path(path).into(),
1332 });
1333 cx.new(|_| Self {
1334 entry_id,
1335 project_path,
1336 is_dirty: true,
1337 })
1338 }
1339 }
1340
1341 impl TestItem {
1342 pub fn new(cx: &mut Context<Self>) -> Self {
1343 Self {
1344 state: String::new(),
1345 label: String::new(),
1346 save_count: 0,
1347 save_as_count: 0,
1348 reload_count: 0,
1349 is_dirty: false,
1350 has_conflict: false,
1351 has_deleted_file: false,
1352 project_items: Vec::new(),
1353 buffer_kind: ItemBufferKind::Singleton,
1354 nav_history: None,
1355 tab_descriptions: None,
1356 tab_detail: Default::default(),
1357 workspace_id: Default::default(),
1358 focus_handle: cx.focus_handle(),
1359 serialize: None,
1360 }
1361 }
1362
1363 pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1364 let mut this = Self::new(cx);
1365 this.workspace_id = Some(id);
1366 this
1367 }
1368
1369 pub fn with_label(mut self, state: &str) -> Self {
1370 self.label = state.to_string();
1371 self
1372 }
1373
1374 pub fn with_buffer_kind(mut self, buffer_kind: ItemBufferKind) -> Self {
1375 self.buffer_kind = buffer_kind;
1376 self
1377 }
1378
1379 pub fn set_has_deleted_file(&mut self, deleted: bool) {
1380 self.has_deleted_file = deleted;
1381 }
1382
1383 pub fn with_dirty(mut self, dirty: bool) -> Self {
1384 self.is_dirty = dirty;
1385 self
1386 }
1387
1388 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1389 self.has_conflict = has_conflict;
1390 self
1391 }
1392
1393 pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1394 self.project_items.clear();
1395 self.project_items.extend(items.iter().cloned());
1396 self
1397 }
1398
1399 pub fn with_serialize(
1400 mut self,
1401 serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1402 ) -> Self {
1403 self.serialize = Some(Box::new(serialize));
1404 self
1405 }
1406
1407 pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1408 self.push_to_nav_history(cx);
1409 self.state = state;
1410 }
1411
1412 fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1413 if let Some(history) = &mut self.nav_history {
1414 history.push(Some(Box::new(self.state.clone())), cx);
1415 }
1416 }
1417 }
1418
1419 impl Render for TestItem {
1420 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1421 gpui::div().track_focus(&self.focus_handle(cx))
1422 }
1423 }
1424
1425 impl EventEmitter<ItemEvent> for TestItem {}
1426
1427 impl Focusable for TestItem {
1428 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1429 self.focus_handle.clone()
1430 }
1431 }
1432
1433 impl Item for TestItem {
1434 type Event = ItemEvent;
1435
1436 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1437 f(*event)
1438 }
1439
1440 fn tab_content_text(&self, detail: usize, _cx: &App) -> SharedString {
1441 self.tab_descriptions
1442 .as_ref()
1443 .and_then(|descriptions| {
1444 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1445 description.into()
1446 })
1447 .unwrap_or_default()
1448 .into()
1449 }
1450
1451 fn telemetry_event_text(&self) -> Option<&'static str> {
1452 None
1453 }
1454
1455 fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1456 self.tab_detail.set(params.detail);
1457 gpui::div().into_any_element()
1458 }
1459
1460 fn for_each_project_item(
1461 &self,
1462 cx: &App,
1463 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1464 ) {
1465 self.project_items
1466 .iter()
1467 .for_each(|item| f(item.entity_id(), item.read(cx)))
1468 }
1469
1470 fn buffer_kind(&self, _: &App) -> ItemBufferKind {
1471 self.buffer_kind
1472 }
1473
1474 fn set_nav_history(
1475 &mut self,
1476 history: ItemNavHistory,
1477 _window: &mut Window,
1478 _: &mut Context<Self>,
1479 ) {
1480 self.nav_history = Some(history);
1481 }
1482
1483 fn navigate(
1484 &mut self,
1485 state: Box<dyn Any>,
1486 _window: &mut Window,
1487 _: &mut Context<Self>,
1488 ) -> bool {
1489 let state = *state.downcast::<String>().unwrap_or_default();
1490 if state != self.state {
1491 self.state = state;
1492 true
1493 } else {
1494 false
1495 }
1496 }
1497
1498 fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1499 self.push_to_nav_history(cx);
1500 }
1501
1502 fn clone_on_split(
1503 &self,
1504 _workspace_id: Option<WorkspaceId>,
1505 _: &mut Window,
1506 cx: &mut Context<Self>,
1507 ) -> Option<Entity<Self>>
1508 where
1509 Self: Sized,
1510 {
1511 Some(cx.new(|cx| Self {
1512 state: self.state.clone(),
1513 label: self.label.clone(),
1514 save_count: self.save_count,
1515 save_as_count: self.save_as_count,
1516 reload_count: self.reload_count,
1517 is_dirty: self.is_dirty,
1518 buffer_kind: self.buffer_kind,
1519 has_conflict: self.has_conflict,
1520 has_deleted_file: self.has_deleted_file,
1521 project_items: self.project_items.clone(),
1522 nav_history: None,
1523 tab_descriptions: None,
1524 tab_detail: Default::default(),
1525 workspace_id: self.workspace_id,
1526 focus_handle: cx.focus_handle(),
1527 serialize: None,
1528 }))
1529 }
1530
1531 fn is_dirty(&self, _: &App) -> bool {
1532 self.is_dirty
1533 }
1534
1535 fn has_conflict(&self, _: &App) -> bool {
1536 self.has_conflict
1537 }
1538
1539 fn has_deleted_file(&self, _: &App) -> bool {
1540 self.has_deleted_file
1541 }
1542
1543 fn can_save(&self, cx: &App) -> bool {
1544 !self.project_items.is_empty()
1545 && self
1546 .project_items
1547 .iter()
1548 .all(|item| item.read(cx).entry_id.is_some())
1549 }
1550
1551 fn can_save_as(&self, _cx: &App) -> bool {
1552 self.buffer_kind == ItemBufferKind::Singleton
1553 }
1554
1555 fn save(
1556 &mut self,
1557 _: SaveOptions,
1558 _: Entity<Project>,
1559 _window: &mut Window,
1560 cx: &mut Context<Self>,
1561 ) -> Task<anyhow::Result<()>> {
1562 self.save_count += 1;
1563 self.is_dirty = false;
1564 for item in &self.project_items {
1565 item.update(cx, |item, _| {
1566 if item.is_dirty {
1567 item.is_dirty = false;
1568 }
1569 })
1570 }
1571 Task::ready(Ok(()))
1572 }
1573
1574 fn save_as(
1575 &mut self,
1576 _: Entity<Project>,
1577 _: ProjectPath,
1578 _window: &mut Window,
1579 _: &mut Context<Self>,
1580 ) -> Task<anyhow::Result<()>> {
1581 self.save_as_count += 1;
1582 self.is_dirty = false;
1583 Task::ready(Ok(()))
1584 }
1585
1586 fn reload(
1587 &mut self,
1588 _: Entity<Project>,
1589 _window: &mut Window,
1590 _: &mut Context<Self>,
1591 ) -> Task<anyhow::Result<()>> {
1592 self.reload_count += 1;
1593 self.is_dirty = false;
1594 Task::ready(Ok(()))
1595 }
1596 }
1597
1598 impl SerializableItem for TestItem {
1599 fn serialized_item_kind() -> &'static str {
1600 "TestItem"
1601 }
1602
1603 fn deserialize(
1604 _project: Entity<Project>,
1605 _workspace: WeakEntity<Workspace>,
1606 workspace_id: WorkspaceId,
1607 _item_id: ItemId,
1608 _window: &mut Window,
1609 cx: &mut App,
1610 ) -> Task<anyhow::Result<Entity<Self>>> {
1611 let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1612 Task::ready(Ok(entity))
1613 }
1614
1615 fn cleanup(
1616 _workspace_id: WorkspaceId,
1617 _alive_items: Vec<ItemId>,
1618 _window: &mut Window,
1619 _cx: &mut App,
1620 ) -> Task<anyhow::Result<()>> {
1621 Task::ready(Ok(()))
1622 }
1623
1624 fn serialize(
1625 &mut self,
1626 _workspace: &mut Workspace,
1627 _item_id: ItemId,
1628 _closing: bool,
1629 _window: &mut Window,
1630 _cx: &mut Context<Self>,
1631 ) -> Option<Task<anyhow::Result<()>>> {
1632 if let Some(serialize) = self.serialize.take() {
1633 let result = serialize();
1634 self.serialize = Some(serialize);
1635 result
1636 } else {
1637 None
1638 }
1639 }
1640
1641 fn should_serialize(&self, _event: &Self::Event) -> bool {
1642 false
1643 }
1644 }
1645}