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