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