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