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