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 /// Returns additional actions to add to the tab's context menu.
370 /// Each entry is a label and an action to dispatch.
371 fn tab_extra_context_menu_actions(
372 &self,
373 _window: &mut Window,
374 _cx: &mut Context<Self>,
375 ) -> Vec<(SharedString, Box<dyn Action>)> {
376 Vec::new()
377 }
378}
379
380pub trait SerializableItem: Item {
381 fn serialized_item_kind() -> &'static str;
382
383 fn cleanup(
384 workspace_id: WorkspaceId,
385 alive_items: Vec<ItemId>,
386 window: &mut Window,
387 cx: &mut App,
388 ) -> Task<Result<()>>;
389
390 fn deserialize(
391 _project: Entity<Project>,
392 _workspace: WeakEntity<Workspace>,
393 _workspace_id: WorkspaceId,
394 _item_id: ItemId,
395 _window: &mut Window,
396 _cx: &mut App,
397 ) -> Task<Result<Entity<Self>>>;
398
399 fn serialize(
400 &mut self,
401 workspace: &mut Workspace,
402 item_id: ItemId,
403 closing: bool,
404 window: &mut Window,
405 cx: &mut Context<Self>,
406 ) -> Option<Task<Result<()>>>;
407
408 fn should_serialize(&self, event: &Self::Event) -> bool;
409}
410
411pub trait SerializableItemHandle: ItemHandle {
412 fn serialized_item_kind(&self) -> &'static str;
413 fn serialize(
414 &self,
415 workspace: &mut Workspace,
416 closing: bool,
417 window: &mut Window,
418 cx: &mut App,
419 ) -> Option<Task<Result<()>>>;
420 fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool;
421}
422
423impl<T> SerializableItemHandle for Entity<T>
424where
425 T: SerializableItem,
426{
427 fn serialized_item_kind(&self) -> &'static str {
428 T::serialized_item_kind()
429 }
430
431 fn serialize(
432 &self,
433 workspace: &mut Workspace,
434 closing: bool,
435 window: &mut Window,
436 cx: &mut App,
437 ) -> Option<Task<Result<()>>> {
438 self.update(cx, |this, cx| {
439 this.serialize(workspace, cx.entity_id().as_u64(), closing, window, cx)
440 })
441 }
442
443 fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool {
444 event
445 .downcast_ref::<T::Event>()
446 .is_some_and(|event| self.read(cx).should_serialize(event))
447 }
448}
449
450pub trait ItemHandle: 'static + Send {
451 fn item_focus_handle(&self, cx: &App) -> FocusHandle;
452 fn subscribe_to_item_events(
453 &self,
454 window: &mut Window,
455 cx: &mut App,
456 handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
457 ) -> gpui::Subscription;
458 fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement;
459 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString;
460 fn suggested_filename(&self, cx: &App) -> SharedString;
461 fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon>;
462 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString>;
463 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent>;
464 fn telemetry_event_text(&self, cx: &App) -> Option<&'static str>;
465 fn dragged_tab_content(
466 &self,
467 params: TabContentParams,
468 window: &Window,
469 cx: &App,
470 ) -> AnyElement;
471 fn project_path(&self, cx: &App) -> Option<ProjectPath>;
472 fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]>;
473 fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]>;
474 fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]>;
475 fn for_each_project_item(
476 &self,
477 _: &App,
478 _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
479 );
480 fn buffer_kind(&self, cx: &App) -> ItemBufferKind;
481 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
482 fn can_split(&self, cx: &App) -> bool;
483 fn clone_on_split(
484 &self,
485 workspace_id: Option<WorkspaceId>,
486 window: &mut Window,
487 cx: &mut App,
488 ) -> Task<Option<Box<dyn ItemHandle>>>;
489 fn added_to_pane(
490 &self,
491 workspace: &mut Workspace,
492 pane: Entity<Pane>,
493 window: &mut Window,
494 cx: &mut Context<Workspace>,
495 );
496 fn deactivated(&self, window: &mut Window, cx: &mut App);
497 fn on_removed(&self, cx: &mut App);
498 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App);
499 fn navigate(&self, data: Arc<dyn Any + Send>, window: &mut Window, cx: &mut App) -> bool;
500 fn item_id(&self) -> EntityId;
501 fn to_any_view(&self) -> AnyView;
502 fn is_dirty(&self, cx: &App) -> bool;
503 fn capability(&self, cx: &App) -> Capability;
504 fn toggle_read_only(&self, window: &mut Window, cx: &mut App);
505 fn has_deleted_file(&self, cx: &App) -> bool;
506 fn has_conflict(&self, cx: &App) -> bool;
507 fn can_save(&self, cx: &App) -> bool;
508 fn can_save_as(&self, cx: &App) -> bool;
509 fn save(
510 &self,
511 options: SaveOptions,
512 project: Entity<Project>,
513 window: &mut Window,
514 cx: &mut App,
515 ) -> Task<Result<()>>;
516 fn save_as(
517 &self,
518 project: Entity<Project>,
519 path: ProjectPath,
520 window: &mut Window,
521 cx: &mut App,
522 ) -> Task<Result<()>>;
523 fn reload(
524 &self,
525 project: Entity<Project>,
526 window: &mut Window,
527 cx: &mut App,
528 ) -> Task<Result<()>>;
529 fn act_as_type(&self, type_id: TypeId, cx: &App) -> Option<AnyEntity>;
530 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>>;
531 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>>;
532 fn on_release(
533 &self,
534 cx: &mut App,
535 callback: Box<dyn FnOnce(&mut App) + Send>,
536 ) -> gpui::Subscription;
537 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>>;
538 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation;
539 fn breadcrumbs(&self, cx: &App) -> Option<Vec<BreadcrumbText>>;
540 fn breadcrumb_prefix(&self, window: &mut Window, cx: &mut App) -> Option<gpui::AnyElement>;
541 fn show_toolbar(&self, cx: &App) -> bool;
542 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>>;
543 fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
544 fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings;
545 fn preserve_preview(&self, cx: &App) -> bool;
546 fn include_in_nav_history(&self) -> bool;
547 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App);
548 fn tab_extra_context_menu_actions(
549 &self,
550 window: &mut Window,
551 cx: &mut App,
552 ) -> Vec<(SharedString, Box<dyn Action>)>;
553 fn can_autosave(&self, cx: &App) -> bool {
554 let is_deleted = self.project_entry_ids(cx).is_empty();
555 self.is_dirty(cx) && !self.has_conflict(cx) && self.can_save(cx) && !is_deleted
556 }
557}
558
559pub trait WeakItemHandle: Send + Sync {
560 fn id(&self) -> EntityId;
561 fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
562 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
563}
564
565impl dyn ItemHandle {
566 pub fn downcast<V: 'static>(&self) -> Option<Entity<V>> {
567 self.to_any_view().downcast().ok()
568 }
569
570 pub fn act_as<V: 'static>(&self, cx: &App) -> Option<Entity<V>> {
571 self.act_as_type(TypeId::of::<V>(), cx)
572 .and_then(|t| t.downcast().ok())
573 }
574}
575
576impl<T: Item> ItemHandle for Entity<T> {
577 fn subscribe_to_item_events(
578 &self,
579 window: &mut Window,
580 cx: &mut App,
581 handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
582 ) -> gpui::Subscription {
583 window.subscribe(self, cx, move |_, event, window, cx| {
584 T::to_item_events(event, &mut |item_event| handler(item_event, window, cx));
585 })
586 }
587
588 fn item_focus_handle(&self, cx: &App) -> FocusHandle {
589 self.read(cx).focus_handle(cx)
590 }
591
592 fn telemetry_event_text(&self, cx: &App) -> Option<&'static str> {
593 self.read(cx).telemetry_event_text()
594 }
595
596 fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
597 self.read(cx).tab_content(params, window, cx)
598 }
599 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
600 self.read(cx).tab_content_text(detail, cx)
601 }
602
603 fn suggested_filename(&self, cx: &App) -> SharedString {
604 self.read(cx).suggested_filename(cx)
605 }
606
607 fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon> {
608 self.read(cx).tab_icon(window, cx)
609 }
610
611 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
612 self.read(cx).tab_tooltip_content(cx)
613 }
614
615 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
616 self.read(cx).tab_tooltip_text(cx)
617 }
618
619 fn dragged_tab_content(
620 &self,
621 params: TabContentParams,
622 window: &Window,
623 cx: &App,
624 ) -> AnyElement {
625 self.read(cx).tab_content(
626 TabContentParams {
627 selected: true,
628 ..params
629 },
630 window,
631 cx,
632 )
633 }
634
635 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
636 let this = self.read(cx);
637 let mut result = None;
638 if this.buffer_kind(cx) == ItemBufferKind::Singleton {
639 this.for_each_project_item(cx, &mut |_, item| {
640 result = item.project_path(cx);
641 });
642 }
643 result
644 }
645
646 fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings {
647 if let Some(project_path) = self.project_path(cx) {
648 WorkspaceSettings::get(
649 Some(SettingsLocation {
650 worktree_id: project_path.worktree_id,
651 path: &project_path.path,
652 }),
653 cx,
654 )
655 } else {
656 WorkspaceSettings::get_global(cx)
657 }
658 }
659
660 fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]> {
661 let mut result = SmallVec::new();
662 self.read(cx).for_each_project_item(cx, &mut |_, item| {
663 if let Some(id) = item.entry_id(cx) {
664 result.push(id);
665 }
666 });
667 result
668 }
669
670 fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]> {
671 let mut result = SmallVec::new();
672 self.read(cx).for_each_project_item(cx, &mut |_, item| {
673 if let Some(id) = item.project_path(cx) {
674 result.push(id);
675 }
676 });
677 result
678 }
679
680 fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]> {
681 let mut result = SmallVec::new();
682 self.read(cx).for_each_project_item(cx, &mut |id, _| {
683 result.push(id);
684 });
685 result
686 }
687
688 fn for_each_project_item(
689 &self,
690 cx: &App,
691 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
692 ) {
693 self.read(cx).for_each_project_item(cx, f)
694 }
695
696 fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
697 self.read(cx).buffer_kind(cx)
698 }
699
700 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
701 Box::new(self.clone())
702 }
703
704 fn can_split(&self, cx: &App) -> bool {
705 self.read(cx).can_split()
706 }
707
708 fn clone_on_split(
709 &self,
710 workspace_id: Option<WorkspaceId>,
711 window: &mut Window,
712 cx: &mut App,
713 ) -> Task<Option<Box<dyn ItemHandle>>> {
714 let task = self.update(cx, |item, cx| item.clone_on_split(workspace_id, window, cx));
715 cx.background_spawn(async move {
716 task.await
717 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
718 })
719 }
720
721 fn added_to_pane(
722 &self,
723 workspace: &mut Workspace,
724 pane: Entity<Pane>,
725 window: &mut Window,
726 cx: &mut Context<Workspace>,
727 ) {
728 let weak_item = self.downgrade();
729 let history = pane.read(cx).nav_history_for_item(self);
730 self.update(cx, |this, cx| {
731 this.set_nav_history(history, window, cx);
732 this.added_to_workspace(workspace, window, cx);
733 });
734
735 if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
736 workspace
737 .enqueue_item_serialization(serializable_item)
738 .log_err();
739 }
740
741 let new_pane_id = pane.entity_id();
742 let old_item_pane = workspace
743 .panes_by_item
744 .insert(self.item_id(), pane.downgrade());
745
746 if old_item_pane.as_ref().is_none_or(|old_pane| {
747 old_pane
748 .upgrade()
749 .is_some_and(|old_pane| old_pane.entity_id() != new_pane_id)
750 }) {
751 self.update(cx, |this, cx| {
752 this.pane_changed(new_pane_id, cx);
753 });
754 }
755
756 if old_item_pane.is_none() {
757 let mut pending_autosave = DelayedDebouncedEditAction::new();
758 let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
759 let pending_update = Rc::new(RefCell::new(None));
760
761 let mut send_follower_updates = None;
762 if let Some(item) = self.to_followable_item_handle(cx) {
763 let is_project_item = item.is_project_item(window, cx);
764 let item = item.downgrade();
765
766 send_follower_updates = Some(cx.spawn_in(window, {
767 let pending_update = pending_update.clone();
768 async move |workspace, cx| {
769 while let Some(mut leader_id) = pending_update_rx.next().await {
770 while let Ok(Some(id)) = pending_update_rx.try_next() {
771 leader_id = id;
772 }
773
774 workspace.update_in(cx, |workspace, window, cx| {
775 let Some(item) = item.upgrade() else { return };
776 workspace.update_followers(
777 is_project_item,
778 proto::update_followers::Variant::UpdateView(
779 proto::UpdateView {
780 id: item
781 .remote_id(workspace.client(), window, cx)
782 .and_then(|id| id.to_proto()),
783 variant: pending_update.borrow_mut().take(),
784 leader_id,
785 },
786 ),
787 window,
788 cx,
789 );
790 })?;
791 cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
792 }
793 anyhow::Ok(())
794 }
795 }));
796 }
797
798 let mut event_subscription = Some(cx.subscribe_in(
799 self,
800 window,
801 move |workspace, item: &Entity<T>, event, window, cx| {
802 let pane = if let Some(pane) = workspace
803 .panes_by_item
804 .get(&item.item_id())
805 .and_then(|pane| pane.upgrade())
806 {
807 pane
808 } else {
809 return;
810 };
811
812 if let Some(item) = item.to_followable_item_handle(cx) {
813 let leader_id = workspace.leader_for_pane(&pane);
814
815 if let Some(leader_id) = leader_id
816 && let Some(FollowEvent::Unfollow) = item.to_follow_event(event)
817 {
818 workspace.unfollow(leader_id, window, cx);
819 }
820
821 if item.item_focus_handle(cx).contains_focused(window, cx) {
822 match leader_id {
823 Some(CollaboratorId::Agent) => {}
824 Some(CollaboratorId::PeerId(leader_peer_id)) => {
825 item.add_event_to_update_proto(
826 event,
827 &mut pending_update.borrow_mut(),
828 window,
829 cx,
830 );
831 pending_update_tx.unbounded_send(Some(leader_peer_id)).ok();
832 }
833 None => {
834 item.add_event_to_update_proto(
835 event,
836 &mut pending_update.borrow_mut(),
837 window,
838 cx,
839 );
840 pending_update_tx.unbounded_send(None).ok();
841 }
842 }
843 }
844 }
845
846 if let Some(item) = item.to_serializable_item_handle(cx)
847 && item.should_serialize(event, cx)
848 {
849 workspace.enqueue_item_serialization(item).ok();
850 }
851
852 T::to_item_events(event, &mut |event| match event {
853 ItemEvent::CloseItem => {
854 pane.update(cx, |pane, cx| {
855 pane.close_item_by_id(
856 item.item_id(),
857 crate::SaveIntent::Close,
858 window,
859 cx,
860 )
861 })
862 .detach_and_log_err(cx);
863 }
864
865 ItemEvent::UpdateTab => {
866 workspace.update_item_dirty_state(item, window, cx);
867
868 if item.has_deleted_file(cx)
869 && !item.is_dirty(cx)
870 && item.workspace_settings(cx).close_on_file_delete
871 {
872 let item_id = item.item_id();
873 let close_item_task = pane.update(cx, |pane, cx| {
874 pane.close_item_by_id(
875 item_id,
876 crate::SaveIntent::Close,
877 window,
878 cx,
879 )
880 });
881 cx.spawn_in(window, {
882 let pane = pane.clone();
883 async move |_workspace, cx| {
884 close_item_task.await?;
885 pane.update(cx, |pane, _cx| {
886 pane.nav_history_mut().remove_item(item_id);
887 });
888 anyhow::Ok(())
889 }
890 })
891 .detach_and_log_err(cx);
892 } else {
893 pane.update(cx, |_, cx| {
894 cx.emit(pane::Event::ChangeItemTitle);
895 cx.notify();
896 });
897 }
898 }
899
900 ItemEvent::Edit => {
901 let autosave = item.workspace_settings(cx).autosave;
902
903 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
904 let delay = Duration::from_millis(milliseconds.0);
905 let item = item.clone();
906 pending_autosave.fire_new(
907 delay,
908 window,
909 cx,
910 move |workspace, window, cx| {
911 Pane::autosave_item(
912 &item,
913 workspace.project().clone(),
914 window,
915 cx,
916 )
917 },
918 );
919 }
920 pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
921 }
922
923 _ => {}
924 });
925 },
926 ));
927
928 cx.on_blur(
929 &self.read(cx).focus_handle(cx),
930 window,
931 move |workspace, window, cx| {
932 if let Some(item) = weak_item.upgrade()
933 && item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange
934 {
935 // Only trigger autosave if focus has truly left the item.
936 // If focus is still within the item's hierarchy (e.g., moved to a context menu),
937 // don't trigger autosave to avoid unwanted formatting and cursor jumps.
938 // Also skip autosave if focus moved to a modal (e.g., command palette),
939 // since the user is still interacting with the workspace.
940 let focus_handle = item.item_focus_handle(cx);
941 if !focus_handle.contains_focused(window, cx)
942 && !workspace.has_active_modal(window, cx)
943 {
944 Pane::autosave_item(&item, workspace.project.clone(), window, cx)
945 .detach_and_log_err(cx);
946 }
947 }
948 },
949 )
950 .detach();
951
952 let item_id = self.item_id();
953 workspace.update_item_dirty_state(self, window, cx);
954 cx.observe_release_in(self, window, move |workspace, _, _, _| {
955 workspace.panes_by_item.remove(&item_id);
956 event_subscription.take();
957 send_follower_updates.take();
958 })
959 .detach();
960 }
961
962 cx.defer_in(window, |workspace, window, cx| {
963 workspace.serialize_workspace(window, cx);
964 });
965 }
966
967 fn deactivated(&self, window: &mut Window, cx: &mut App) {
968 self.update(cx, |this, cx| this.deactivated(window, cx));
969 }
970
971 fn on_removed(&self, cx: &mut App) {
972 self.update(cx, |item, cx| item.on_removed(cx));
973 }
974
975 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
976 self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
977 }
978
979 fn navigate(&self, data: Arc<dyn Any + Send>, window: &mut Window, cx: &mut App) -> bool {
980 self.update(cx, |this, cx| this.navigate(data, window, cx))
981 }
982
983 fn item_id(&self) -> EntityId {
984 self.entity_id()
985 }
986
987 fn to_any_view(&self) -> AnyView {
988 self.clone().into()
989 }
990
991 fn is_dirty(&self, cx: &App) -> bool {
992 self.read(cx).is_dirty(cx)
993 }
994
995 fn capability(&self, cx: &App) -> Capability {
996 self.read(cx).capability(cx)
997 }
998
999 fn toggle_read_only(&self, window: &mut Window, cx: &mut App) {
1000 self.update(cx, |this, cx| {
1001 this.toggle_read_only(window, cx);
1002 })
1003 }
1004
1005 fn has_deleted_file(&self, cx: &App) -> bool {
1006 self.read(cx).has_deleted_file(cx)
1007 }
1008
1009 fn has_conflict(&self, cx: &App) -> bool {
1010 self.read(cx).has_conflict(cx)
1011 }
1012
1013 fn can_save(&self, cx: &App) -> bool {
1014 self.read(cx).can_save(cx)
1015 }
1016
1017 fn can_save_as(&self, cx: &App) -> bool {
1018 self.read(cx).can_save_as(cx)
1019 }
1020
1021 fn save(
1022 &self,
1023 options: SaveOptions,
1024 project: Entity<Project>,
1025 window: &mut Window,
1026 cx: &mut App,
1027 ) -> Task<Result<()>> {
1028 self.update(cx, |item, cx| item.save(options, project, window, cx))
1029 }
1030
1031 fn save_as(
1032 &self,
1033 project: Entity<Project>,
1034 path: ProjectPath,
1035 window: &mut Window,
1036 cx: &mut App,
1037 ) -> Task<anyhow::Result<()>> {
1038 self.update(cx, |item, cx| item.save_as(project, path, window, cx))
1039 }
1040
1041 fn reload(
1042 &self,
1043 project: Entity<Project>,
1044 window: &mut Window,
1045 cx: &mut App,
1046 ) -> Task<Result<()>> {
1047 self.update(cx, |item, cx| item.reload(project, window, cx))
1048 }
1049
1050 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyEntity> {
1051 self.read(cx).act_as_type(type_id, self, cx)
1052 }
1053
1054 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
1055 FollowableViewRegistry::to_followable_view(self.clone(), cx)
1056 }
1057
1058 fn on_release(
1059 &self,
1060 cx: &mut App,
1061 callback: Box<dyn FnOnce(&mut App) + Send>,
1062 ) -> gpui::Subscription {
1063 cx.observe_release(self, move |_, cx| callback(cx))
1064 }
1065
1066 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
1067 self.read(cx).as_searchable(self, cx)
1068 }
1069
1070 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1071 self.read(cx).breadcrumb_location(cx)
1072 }
1073
1074 fn breadcrumbs(&self, cx: &App) -> Option<Vec<BreadcrumbText>> {
1075 self.read(cx).breadcrumbs(cx)
1076 }
1077
1078 fn breadcrumb_prefix(&self, window: &mut Window, cx: &mut App) -> Option<gpui::AnyElement> {
1079 self.update(cx, |item, cx| item.breadcrumb_prefix(window, cx))
1080 }
1081
1082 fn show_toolbar(&self, cx: &App) -> bool {
1083 self.read(cx).show_toolbar()
1084 }
1085
1086 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
1087 self.read(cx).pixel_position_of_cursor(cx)
1088 }
1089
1090 fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
1091 Box::new(self.downgrade())
1092 }
1093
1094 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
1095 SerializableItemRegistry::view_to_serializable_item_handle(self.to_any_view(), cx)
1096 }
1097
1098 fn preserve_preview(&self, cx: &App) -> bool {
1099 self.read(cx).preserve_preview(cx)
1100 }
1101
1102 fn include_in_nav_history(&self) -> bool {
1103 T::include_in_nav_history()
1104 }
1105
1106 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
1107 self.update(cx, |this, cx| {
1108 this.focus_handle(cx).focus(window, cx);
1109 window.dispatch_action(action, cx);
1110 })
1111 }
1112
1113 fn tab_extra_context_menu_actions(
1114 &self,
1115 window: &mut Window,
1116 cx: &mut App,
1117 ) -> Vec<(SharedString, Box<dyn Action>)> {
1118 self.update(cx, |this, cx| {
1119 this.tab_extra_context_menu_actions(window, cx)
1120 })
1121 }
1122}
1123
1124impl From<Box<dyn ItemHandle>> for AnyView {
1125 fn from(val: Box<dyn ItemHandle>) -> Self {
1126 val.to_any_view()
1127 }
1128}
1129
1130impl From<&Box<dyn ItemHandle>> for AnyView {
1131 fn from(val: &Box<dyn ItemHandle>) -> Self {
1132 val.to_any_view()
1133 }
1134}
1135
1136impl Clone for Box<dyn ItemHandle> {
1137 fn clone(&self) -> Box<dyn ItemHandle> {
1138 self.boxed_clone()
1139 }
1140}
1141
1142impl<T: Item> WeakItemHandle for WeakEntity<T> {
1143 fn id(&self) -> EntityId {
1144 self.entity_id()
1145 }
1146
1147 fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1148 Box::new(self.clone())
1149 }
1150
1151 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1152 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1153 }
1154}
1155
1156#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1157pub struct ProjectItemKind(pub &'static str);
1158
1159pub trait ProjectItem: Item {
1160 type Item: project::ProjectItem;
1161
1162 fn project_item_kind() -> Option<ProjectItemKind> {
1163 None
1164 }
1165
1166 fn for_project_item(
1167 project: Entity<Project>,
1168 pane: Option<&Pane>,
1169 item: Entity<Self::Item>,
1170 window: &mut Window,
1171 cx: &mut Context<Self>,
1172 ) -> Self
1173 where
1174 Self: Sized;
1175
1176 /// A fallback handler, which will be called after [`project::ProjectItem::try_open`] fails,
1177 /// with the error from that failure as an argument.
1178 /// Allows to open an item that can gracefully display and handle errors.
1179 fn for_broken_project_item(
1180 _abs_path: &Path,
1181 _is_local: bool,
1182 _e: &anyhow::Error,
1183 _window: &mut Window,
1184 _cx: &mut App,
1185 ) -> Option<InvalidItemView>
1186 where
1187 Self: Sized,
1188 {
1189 None
1190 }
1191}
1192
1193#[derive(Debug)]
1194pub enum FollowEvent {
1195 Unfollow,
1196}
1197
1198pub enum Dedup {
1199 KeepExisting,
1200 ReplaceExisting,
1201}
1202
1203pub trait FollowableItem: Item {
1204 fn remote_id(&self) -> Option<ViewId>;
1205 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1206 fn from_state_proto(
1207 project: Entity<Workspace>,
1208 id: ViewId,
1209 state: &mut Option<proto::view::Variant>,
1210 window: &mut Window,
1211 cx: &mut App,
1212 ) -> Option<Task<Result<Entity<Self>>>>;
1213 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1214 fn add_event_to_update_proto(
1215 &self,
1216 event: &Self::Event,
1217 update: &mut Option<proto::update_view::Variant>,
1218 window: &mut Window,
1219 cx: &mut App,
1220 ) -> bool;
1221 fn apply_update_proto(
1222 &mut self,
1223 project: &Entity<Project>,
1224 message: proto::update_view::Variant,
1225 window: &mut Window,
1226 cx: &mut Context<Self>,
1227 ) -> Task<Result<()>>;
1228 fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1229 fn set_leader_id(
1230 &mut self,
1231 leader_peer_id: Option<CollaboratorId>,
1232 window: &mut Window,
1233 cx: &mut Context<Self>,
1234 );
1235 fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1236 fn update_agent_location(
1237 &mut self,
1238 _location: language::Anchor,
1239 _window: &mut Window,
1240 _cx: &mut Context<Self>,
1241 ) {
1242 }
1243}
1244
1245pub trait FollowableItemHandle: ItemHandle {
1246 fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1247 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1248 fn set_leader_id(
1249 &self,
1250 leader_peer_id: Option<CollaboratorId>,
1251 window: &mut Window,
1252 cx: &mut App,
1253 );
1254 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
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 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1263 fn apply_update_proto(
1264 &self,
1265 project: &Entity<Project>,
1266 message: proto::update_view::Variant,
1267 window: &mut Window,
1268 cx: &mut App,
1269 ) -> Task<Result<()>>;
1270 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1271 fn dedup(
1272 &self,
1273 existing: &dyn FollowableItemHandle,
1274 window: &mut Window,
1275 cx: &mut App,
1276 ) -> Option<Dedup>;
1277 fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App);
1278}
1279
1280impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1281 fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1282 self.read(cx).remote_id().or_else(|| {
1283 client.peer_id().map(|creator| ViewId {
1284 creator: CollaboratorId::PeerId(creator),
1285 id: self.item_id().as_u64(),
1286 })
1287 })
1288 }
1289
1290 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1291 Box::new(self.downgrade())
1292 }
1293
1294 fn set_leader_id(&self, leader_id: Option<CollaboratorId>, window: &mut Window, cx: &mut App) {
1295 self.update(cx, |this, cx| this.set_leader_id(leader_id, window, cx))
1296 }
1297
1298 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1299 self.update(cx, |this, cx| this.to_state_proto(window, cx))
1300 }
1301
1302 fn add_event_to_update_proto(
1303 &self,
1304 event: &dyn Any,
1305 update: &mut Option<proto::update_view::Variant>,
1306 window: &mut Window,
1307 cx: &mut App,
1308 ) -> bool {
1309 if let Some(event) = event.downcast_ref() {
1310 self.update(cx, |this, cx| {
1311 this.add_event_to_update_proto(event, update, window, cx)
1312 })
1313 } else {
1314 false
1315 }
1316 }
1317
1318 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1319 T::to_follow_event(event.downcast_ref()?)
1320 }
1321
1322 fn apply_update_proto(
1323 &self,
1324 project: &Entity<Project>,
1325 message: proto::update_view::Variant,
1326 window: &mut Window,
1327 cx: &mut App,
1328 ) -> Task<Result<()>> {
1329 self.update(cx, |this, cx| {
1330 this.apply_update_proto(project, message, window, cx)
1331 })
1332 }
1333
1334 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1335 self.read(cx).is_project_item(window, cx)
1336 }
1337
1338 fn dedup(
1339 &self,
1340 existing: &dyn FollowableItemHandle,
1341 window: &mut Window,
1342 cx: &mut App,
1343 ) -> Option<Dedup> {
1344 let existing = existing.to_any_view().downcast::<T>().ok()?;
1345 self.read(cx).dedup(existing.read(cx), window, cx)
1346 }
1347
1348 fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App) {
1349 self.update(cx, |this, cx| {
1350 this.update_agent_location(location, window, cx)
1351 })
1352 }
1353}
1354
1355pub trait WeakFollowableItemHandle: Send + Sync {
1356 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1357}
1358
1359impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1360 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1361 Some(Box::new(self.upgrade()?))
1362 }
1363}
1364
1365#[cfg(any(test, feature = "test-support"))]
1366pub mod test {
1367 use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1368 use crate::{
1369 ItemId, ItemNavHistory, Workspace, WorkspaceId,
1370 item::{ItemBufferKind, SaveOptions},
1371 };
1372 use gpui::{
1373 AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1374 InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1375 };
1376 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1377 use std::{any::Any, cell::Cell, sync::Arc};
1378 use util::rel_path::rel_path;
1379
1380 pub struct TestProjectItem {
1381 pub entry_id: Option<ProjectEntryId>,
1382 pub project_path: Option<ProjectPath>,
1383 pub is_dirty: bool,
1384 }
1385
1386 pub struct TestItem {
1387 pub workspace_id: Option<WorkspaceId>,
1388 pub state: String,
1389 pub label: String,
1390 pub save_count: usize,
1391 pub save_as_count: usize,
1392 pub reload_count: usize,
1393 pub is_dirty: bool,
1394 pub buffer_kind: ItemBufferKind,
1395 pub has_conflict: bool,
1396 pub has_deleted_file: bool,
1397 pub project_items: Vec<Entity<TestProjectItem>>,
1398 pub nav_history: Option<ItemNavHistory>,
1399 pub tab_descriptions: Option<Vec<&'static str>>,
1400 pub tab_detail: Cell<Option<usize>>,
1401 serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1402 focus_handle: gpui::FocusHandle,
1403 }
1404
1405 impl project::ProjectItem for TestProjectItem {
1406 fn try_open(
1407 _project: &Entity<Project>,
1408 _path: &ProjectPath,
1409 _cx: &mut App,
1410 ) -> Option<Task<anyhow::Result<Entity<Self>>>> {
1411 None
1412 }
1413 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1414 self.entry_id
1415 }
1416
1417 fn project_path(&self, _: &App) -> Option<ProjectPath> {
1418 self.project_path.clone()
1419 }
1420
1421 fn is_dirty(&self) -> bool {
1422 self.is_dirty
1423 }
1424 }
1425
1426 pub enum TestItemEvent {
1427 Edit,
1428 }
1429
1430 impl TestProjectItem {
1431 pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1432 let entry_id = Some(ProjectEntryId::from_proto(id));
1433 let project_path = Some(ProjectPath {
1434 worktree_id: WorktreeId::from_usize(0),
1435 path: rel_path(path).into(),
1436 });
1437 cx.new(|_| Self {
1438 entry_id,
1439 project_path,
1440 is_dirty: false,
1441 })
1442 }
1443
1444 pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1445 cx.new(|_| Self {
1446 project_path: None,
1447 entry_id: None,
1448 is_dirty: false,
1449 })
1450 }
1451
1452 pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1453 let entry_id = Some(ProjectEntryId::from_proto(id));
1454 let project_path = Some(ProjectPath {
1455 worktree_id: WorktreeId::from_usize(0),
1456 path: rel_path(path).into(),
1457 });
1458 cx.new(|_| Self {
1459 entry_id,
1460 project_path,
1461 is_dirty: true,
1462 })
1463 }
1464 }
1465
1466 impl TestItem {
1467 pub fn new(cx: &mut Context<Self>) -> Self {
1468 Self {
1469 state: String::new(),
1470 label: String::new(),
1471 save_count: 0,
1472 save_as_count: 0,
1473 reload_count: 0,
1474 is_dirty: false,
1475 has_conflict: false,
1476 has_deleted_file: false,
1477 project_items: Vec::new(),
1478 buffer_kind: ItemBufferKind::Singleton,
1479 nav_history: None,
1480 tab_descriptions: None,
1481 tab_detail: Default::default(),
1482 workspace_id: Default::default(),
1483 focus_handle: cx.focus_handle(),
1484 serialize: None,
1485 }
1486 }
1487
1488 pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1489 let mut this = Self::new(cx);
1490 this.workspace_id = Some(id);
1491 this
1492 }
1493
1494 pub fn with_label(mut self, state: &str) -> Self {
1495 self.label = state.to_string();
1496 self
1497 }
1498
1499 pub fn with_buffer_kind(mut self, buffer_kind: ItemBufferKind) -> Self {
1500 self.buffer_kind = buffer_kind;
1501 self
1502 }
1503
1504 pub fn set_has_deleted_file(&mut self, deleted: bool) {
1505 self.has_deleted_file = deleted;
1506 }
1507
1508 pub fn with_dirty(mut self, dirty: bool) -> Self {
1509 self.is_dirty = dirty;
1510 self
1511 }
1512
1513 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1514 self.has_conflict = has_conflict;
1515 self
1516 }
1517
1518 pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1519 self.project_items.clear();
1520 self.project_items.extend(items.iter().cloned());
1521 self
1522 }
1523
1524 pub fn with_serialize(
1525 mut self,
1526 serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1527 ) -> Self {
1528 self.serialize = Some(Box::new(serialize));
1529 self
1530 }
1531
1532 pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1533 self.push_to_nav_history(cx);
1534 self.state = state;
1535 }
1536
1537 fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1538 if let Some(history) = &mut self.nav_history {
1539 history.push(Some(Box::new(self.state.clone())), cx);
1540 }
1541 }
1542 }
1543
1544 impl Render for TestItem {
1545 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1546 gpui::div().track_focus(&self.focus_handle(cx))
1547 }
1548 }
1549
1550 impl EventEmitter<ItemEvent> for TestItem {}
1551
1552 impl Focusable for TestItem {
1553 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1554 self.focus_handle.clone()
1555 }
1556 }
1557
1558 impl Item for TestItem {
1559 type Event = ItemEvent;
1560
1561 fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(ItemEvent)) {
1562 f(*event)
1563 }
1564
1565 fn tab_content_text(&self, detail: usize, _cx: &App) -> SharedString {
1566 self.tab_descriptions
1567 .as_ref()
1568 .and_then(|descriptions| {
1569 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1570 description.into()
1571 })
1572 .unwrap_or_default()
1573 .into()
1574 }
1575
1576 fn telemetry_event_text(&self) -> Option<&'static str> {
1577 None
1578 }
1579
1580 fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1581 self.tab_detail.set(params.detail);
1582 gpui::div().into_any_element()
1583 }
1584
1585 fn for_each_project_item(
1586 &self,
1587 cx: &App,
1588 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1589 ) {
1590 self.project_items
1591 .iter()
1592 .for_each(|item| f(item.entity_id(), item.read(cx)))
1593 }
1594
1595 fn buffer_kind(&self, _: &App) -> ItemBufferKind {
1596 self.buffer_kind
1597 }
1598
1599 fn set_nav_history(
1600 &mut self,
1601 history: ItemNavHistory,
1602 _window: &mut Window,
1603 _: &mut Context<Self>,
1604 ) {
1605 self.nav_history = Some(history);
1606 }
1607
1608 fn navigate(
1609 &mut self,
1610 state: Arc<dyn Any + Send>,
1611 _window: &mut Window,
1612 _: &mut Context<Self>,
1613 ) -> bool {
1614 if let Some(state) = state.downcast_ref::<Box<String>>() {
1615 let state = *state.clone();
1616 if state != self.state {
1617 false
1618 } else {
1619 self.state = state;
1620 true
1621 }
1622 } else {
1623 false
1624 }
1625 }
1626
1627 fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1628 self.push_to_nav_history(cx);
1629 }
1630
1631 fn can_split(&self) -> bool {
1632 true
1633 }
1634
1635 fn clone_on_split(
1636 &self,
1637 _workspace_id: Option<WorkspaceId>,
1638 _: &mut Window,
1639 cx: &mut Context<Self>,
1640 ) -> Task<Option<Entity<Self>>>
1641 where
1642 Self: Sized,
1643 {
1644 Task::ready(Some(cx.new(|cx| Self {
1645 state: self.state.clone(),
1646 label: self.label.clone(),
1647 save_count: self.save_count,
1648 save_as_count: self.save_as_count,
1649 reload_count: self.reload_count,
1650 is_dirty: self.is_dirty,
1651 buffer_kind: self.buffer_kind,
1652 has_conflict: self.has_conflict,
1653 has_deleted_file: self.has_deleted_file,
1654 project_items: self.project_items.clone(),
1655 nav_history: None,
1656 tab_descriptions: None,
1657 tab_detail: Default::default(),
1658 workspace_id: self.workspace_id,
1659 focus_handle: cx.focus_handle(),
1660 serialize: None,
1661 })))
1662 }
1663
1664 fn is_dirty(&self, _: &App) -> bool {
1665 self.is_dirty
1666 }
1667
1668 fn has_conflict(&self, _: &App) -> bool {
1669 self.has_conflict
1670 }
1671
1672 fn has_deleted_file(&self, _: &App) -> bool {
1673 self.has_deleted_file
1674 }
1675
1676 fn can_save(&self, cx: &App) -> bool {
1677 !self.project_items.is_empty()
1678 && self
1679 .project_items
1680 .iter()
1681 .all(|item| item.read(cx).entry_id.is_some())
1682 }
1683
1684 fn can_save_as(&self, _cx: &App) -> bool {
1685 self.buffer_kind == ItemBufferKind::Singleton
1686 }
1687
1688 fn save(
1689 &mut self,
1690 _: SaveOptions,
1691 _: Entity<Project>,
1692 _window: &mut Window,
1693 cx: &mut Context<Self>,
1694 ) -> Task<anyhow::Result<()>> {
1695 self.save_count += 1;
1696 self.is_dirty = false;
1697 for item in &self.project_items {
1698 item.update(cx, |item, _| {
1699 if item.is_dirty {
1700 item.is_dirty = false;
1701 }
1702 })
1703 }
1704 Task::ready(Ok(()))
1705 }
1706
1707 fn save_as(
1708 &mut self,
1709 _: Entity<Project>,
1710 _: ProjectPath,
1711 _window: &mut Window,
1712 _: &mut Context<Self>,
1713 ) -> Task<anyhow::Result<()>> {
1714 self.save_as_count += 1;
1715 self.is_dirty = false;
1716 Task::ready(Ok(()))
1717 }
1718
1719 fn reload(
1720 &mut self,
1721 _: Entity<Project>,
1722 _window: &mut Window,
1723 _: &mut Context<Self>,
1724 ) -> Task<anyhow::Result<()>> {
1725 self.reload_count += 1;
1726 self.is_dirty = false;
1727 Task::ready(Ok(()))
1728 }
1729 }
1730
1731 impl SerializableItem for TestItem {
1732 fn serialized_item_kind() -> &'static str {
1733 "TestItem"
1734 }
1735
1736 fn deserialize(
1737 _project: Entity<Project>,
1738 _workspace: WeakEntity<Workspace>,
1739 workspace_id: WorkspaceId,
1740 _item_id: ItemId,
1741 _window: &mut Window,
1742 cx: &mut App,
1743 ) -> Task<anyhow::Result<Entity<Self>>> {
1744 let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1745 Task::ready(Ok(entity))
1746 }
1747
1748 fn cleanup(
1749 _workspace_id: WorkspaceId,
1750 _alive_items: Vec<ItemId>,
1751 _window: &mut Window,
1752 _cx: &mut App,
1753 ) -> Task<anyhow::Result<()>> {
1754 Task::ready(Ok(()))
1755 }
1756
1757 fn serialize(
1758 &mut self,
1759 _workspace: &mut Workspace,
1760 _item_id: ItemId,
1761 _closing: bool,
1762 _window: &mut Window,
1763 _cx: &mut Context<Self>,
1764 ) -> Option<Task<anyhow::Result<()>>> {
1765 if let Some(serialize) = self.serialize.take() {
1766 let result = serialize();
1767 self.serialize = Some(serialize);
1768 result
1769 } else {
1770 None
1771 }
1772 }
1773
1774 fn should_serialize(&self, _event: &Self::Event) -> bool {
1775 false
1776 }
1777 }
1778}