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