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