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