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