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