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 |workspace, mut cx| async move {
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(&mut 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 cx.observe_release_in(self, window, move |workspace, _, _, _| {
856 workspace.panes_by_item.remove(&item_id);
857 event_subscription.take();
858 send_follower_updates.take();
859 })
860 .detach();
861 }
862
863 cx.defer_in(window, |workspace, window, cx| {
864 workspace.serialize_workspace(window, cx);
865 });
866 }
867
868 fn discarded(&self, project: Entity<Project>, window: &mut Window, cx: &mut App) {
869 self.update(cx, |this, cx| this.discarded(project, window, cx));
870 }
871
872 fn deactivated(&self, window: &mut Window, cx: &mut App) {
873 self.update(cx, |this, cx| this.deactivated(window, cx));
874 }
875
876 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
877 self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
878 }
879
880 fn navigate(&self, data: Box<dyn Any>, window: &mut Window, cx: &mut App) -> bool {
881 self.update(cx, |this, cx| this.navigate(data, window, cx))
882 }
883
884 fn item_id(&self) -> EntityId {
885 self.entity_id()
886 }
887
888 fn to_any(&self) -> AnyView {
889 self.clone().into()
890 }
891
892 fn is_dirty(&self, cx: &App) -> bool {
893 self.read(cx).is_dirty(cx)
894 }
895
896 fn has_deleted_file(&self, cx: &App) -> bool {
897 self.read(cx).has_deleted_file(cx)
898 }
899
900 fn has_conflict(&self, cx: &App) -> bool {
901 self.read(cx).has_conflict(cx)
902 }
903
904 fn can_save(&self, cx: &App) -> bool {
905 self.read(cx).can_save(cx)
906 }
907
908 fn can_save_as(&self, cx: &App) -> bool {
909 self.read(cx).can_save_as(cx)
910 }
911
912 fn save(
913 &self,
914 format: bool,
915 project: Entity<Project>,
916 window: &mut Window,
917 cx: &mut App,
918 ) -> Task<Result<()>> {
919 self.update(cx, |item, cx| item.save(format, project, window, cx))
920 }
921
922 fn save_as(
923 &self,
924 project: Entity<Project>,
925 path: ProjectPath,
926 window: &mut Window,
927 cx: &mut App,
928 ) -> Task<anyhow::Result<()>> {
929 self.update(cx, |item, cx| item.save_as(project, path, window, cx))
930 }
931
932 fn reload(
933 &self,
934 project: Entity<Project>,
935 window: &mut Window,
936 cx: &mut App,
937 ) -> Task<Result<()>> {
938 self.update(cx, |item, cx| item.reload(project, window, cx))
939 }
940
941 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyView> {
942 self.read(cx).act_as_type(type_id, self, cx)
943 }
944
945 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
946 FollowableViewRegistry::to_followable_view(self.clone(), cx)
947 }
948
949 fn on_release(
950 &self,
951 cx: &mut App,
952 callback: Box<dyn FnOnce(&mut App) + Send>,
953 ) -> gpui::Subscription {
954 cx.observe_release(self, move |_, cx| callback(cx))
955 }
956
957 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
958 self.read(cx).as_searchable(self)
959 }
960
961 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
962 self.read(cx).breadcrumb_location(cx)
963 }
964
965 fn breadcrumbs(&self, theme: &Theme, cx: &App) -> Option<Vec<BreadcrumbText>> {
966 self.read(cx).breadcrumbs(theme, cx)
967 }
968
969 fn show_toolbar(&self, cx: &App) -> bool {
970 self.read(cx).show_toolbar()
971 }
972
973 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
974 self.read(cx).pixel_position_of_cursor(cx)
975 }
976
977 fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
978 Box::new(self.downgrade())
979 }
980
981 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
982 SerializableItemRegistry::view_to_serializable_item_handle(self.to_any(), cx)
983 }
984
985 fn preserve_preview(&self, cx: &App) -> bool {
986 self.read(cx).preserve_preview(cx)
987 }
988
989 fn include_in_nav_history(&self) -> bool {
990 T::include_in_nav_history()
991 }
992
993 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
994 self.update(cx, |this, cx| {
995 this.focus_handle(cx).focus(window);
996 window.dispatch_action(action, cx);
997 })
998 }
999}
1000
1001impl From<Box<dyn ItemHandle>> for AnyView {
1002 fn from(val: Box<dyn ItemHandle>) -> Self {
1003 val.to_any()
1004 }
1005}
1006
1007impl From<&Box<dyn ItemHandle>> for AnyView {
1008 fn from(val: &Box<dyn ItemHandle>) -> Self {
1009 val.to_any()
1010 }
1011}
1012
1013impl Clone for Box<dyn ItemHandle> {
1014 fn clone(&self) -> Box<dyn ItemHandle> {
1015 self.boxed_clone()
1016 }
1017}
1018
1019impl<T: Item> WeakItemHandle for WeakEntity<T> {
1020 fn id(&self) -> EntityId {
1021 self.entity_id()
1022 }
1023
1024 fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1025 Box::new(self.clone())
1026 }
1027
1028 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1029 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1030 }
1031}
1032
1033pub trait ProjectItem: Item {
1034 type Item: project::ProjectItem;
1035
1036 fn for_project_item(
1037 project: Entity<Project>,
1038 item: Entity<Self::Item>,
1039 window: &mut Window,
1040 cx: &mut Context<Self>,
1041 ) -> Self
1042 where
1043 Self: Sized;
1044}
1045
1046#[derive(Debug)]
1047pub enum FollowEvent {
1048 Unfollow,
1049}
1050
1051pub enum Dedup {
1052 KeepExisting,
1053 ReplaceExisting,
1054}
1055
1056pub trait FollowableItem: Item {
1057 fn remote_id(&self) -> Option<ViewId>;
1058 fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant>;
1059 fn from_state_proto(
1060 project: Entity<Workspace>,
1061 id: ViewId,
1062 state: &mut Option<proto::view::Variant>,
1063 window: &mut Window,
1064 cx: &mut App,
1065 ) -> Option<Task<Result<Entity<Self>>>>;
1066 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1067 fn add_event_to_update_proto(
1068 &self,
1069 event: &Self::Event,
1070 update: &mut Option<proto::update_view::Variant>,
1071 window: &Window,
1072 cx: &App,
1073 ) -> bool;
1074 fn apply_update_proto(
1075 &mut self,
1076 project: &Entity<Project>,
1077 message: proto::update_view::Variant,
1078 window: &mut Window,
1079 cx: &mut Context<Self>,
1080 ) -> Task<Result<()>>;
1081 fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1082 fn set_leader_peer_id(
1083 &mut self,
1084 leader_peer_id: Option<PeerId>,
1085 window: &mut Window,
1086 cx: &mut Context<Self>,
1087 );
1088 fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1089}
1090
1091pub trait FollowableItemHandle: ItemHandle {
1092 fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1093 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1094 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, window: &mut Window, cx: &mut App);
1095 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1096 fn add_event_to_update_proto(
1097 &self,
1098 event: &dyn Any,
1099 update: &mut Option<proto::update_view::Variant>,
1100 window: &mut Window,
1101 cx: &mut App,
1102 ) -> bool;
1103 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1104 fn apply_update_proto(
1105 &self,
1106 project: &Entity<Project>,
1107 message: proto::update_view::Variant,
1108 window: &mut Window,
1109 cx: &mut App,
1110 ) -> Task<Result<()>>;
1111 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1112 fn dedup(
1113 &self,
1114 existing: &dyn FollowableItemHandle,
1115 window: &mut Window,
1116 cx: &mut App,
1117 ) -> Option<Dedup>;
1118}
1119
1120impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1121 fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1122 self.read(cx).remote_id().or_else(|| {
1123 client.peer_id().map(|creator| ViewId {
1124 creator,
1125 id: self.item_id().as_u64(),
1126 })
1127 })
1128 }
1129
1130 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1131 Box::new(self.downgrade())
1132 }
1133
1134 fn set_leader_peer_id(
1135 &self,
1136 leader_peer_id: Option<PeerId>,
1137 window: &mut Window,
1138 cx: &mut App,
1139 ) {
1140 self.update(cx, |this, cx| {
1141 this.set_leader_peer_id(leader_peer_id, window, cx)
1142 })
1143 }
1144
1145 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1146 self.read(cx).to_state_proto(window, cx)
1147 }
1148
1149 fn add_event_to_update_proto(
1150 &self,
1151 event: &dyn Any,
1152 update: &mut Option<proto::update_view::Variant>,
1153 window: &mut Window,
1154 cx: &mut App,
1155 ) -> bool {
1156 if let Some(event) = event.downcast_ref() {
1157 self.read(cx)
1158 .add_event_to_update_proto(event, update, window, cx)
1159 } else {
1160 false
1161 }
1162 }
1163
1164 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1165 T::to_follow_event(event.downcast_ref()?)
1166 }
1167
1168 fn apply_update_proto(
1169 &self,
1170 project: &Entity<Project>,
1171 message: proto::update_view::Variant,
1172 window: &mut Window,
1173 cx: &mut App,
1174 ) -> Task<Result<()>> {
1175 self.update(cx, |this, cx| {
1176 this.apply_update_proto(project, message, window, cx)
1177 })
1178 }
1179
1180 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1181 self.read(cx).is_project_item(window, cx)
1182 }
1183
1184 fn dedup(
1185 &self,
1186 existing: &dyn FollowableItemHandle,
1187 window: &mut Window,
1188 cx: &mut App,
1189 ) -> Option<Dedup> {
1190 let existing = existing.to_any().downcast::<T>().ok()?;
1191 self.read(cx).dedup(existing.read(cx), window, cx)
1192 }
1193}
1194
1195pub trait WeakFollowableItemHandle: Send + Sync {
1196 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1197}
1198
1199impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1200 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1201 Some(Box::new(self.upgrade()?))
1202 }
1203}
1204
1205#[cfg(any(test, feature = "test-support"))]
1206pub mod test {
1207 use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1208 use crate::{ItemId, ItemNavHistory, Workspace, WorkspaceId};
1209 use gpui::{
1210 AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1211 InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1212 };
1213 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1214 use std::{any::Any, cell::Cell, path::Path};
1215
1216 pub struct TestProjectItem {
1217 pub entry_id: Option<ProjectEntryId>,
1218 pub project_path: Option<ProjectPath>,
1219 pub is_dirty: bool,
1220 }
1221
1222 pub struct TestItem {
1223 pub workspace_id: Option<WorkspaceId>,
1224 pub state: String,
1225 pub label: String,
1226 pub save_count: usize,
1227 pub save_as_count: usize,
1228 pub reload_count: usize,
1229 pub is_dirty: bool,
1230 pub is_singleton: bool,
1231 pub has_conflict: bool,
1232 pub project_items: Vec<Entity<TestProjectItem>>,
1233 pub nav_history: Option<ItemNavHistory>,
1234 pub tab_descriptions: Option<Vec<&'static str>>,
1235 pub tab_detail: Cell<Option<usize>>,
1236 serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1237 focus_handle: gpui::FocusHandle,
1238 }
1239
1240 impl project::ProjectItem for TestProjectItem {
1241 fn try_open(
1242 _project: &Entity<Project>,
1243 _path: &ProjectPath,
1244 _cx: &mut App,
1245 ) -> Option<Task<gpui::Result<Entity<Self>>>> {
1246 None
1247 }
1248 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1249 self.entry_id
1250 }
1251
1252 fn project_path(&self, _: &App) -> Option<ProjectPath> {
1253 self.project_path.clone()
1254 }
1255
1256 fn is_dirty(&self) -> bool {
1257 self.is_dirty
1258 }
1259 }
1260
1261 pub enum TestItemEvent {
1262 Edit,
1263 }
1264
1265 impl TestProjectItem {
1266 pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1267 let entry_id = Some(ProjectEntryId::from_proto(id));
1268 let project_path = Some(ProjectPath {
1269 worktree_id: WorktreeId::from_usize(0),
1270 path: Path::new(path).into(),
1271 });
1272 cx.new(|_| Self {
1273 entry_id,
1274 project_path,
1275 is_dirty: false,
1276 })
1277 }
1278
1279 pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1280 cx.new(|_| Self {
1281 project_path: None,
1282 entry_id: None,
1283 is_dirty: false,
1284 })
1285 }
1286
1287 pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1288 let entry_id = Some(ProjectEntryId::from_proto(id));
1289 let project_path = Some(ProjectPath {
1290 worktree_id: WorktreeId::from_usize(0),
1291 path: Path::new(path).into(),
1292 });
1293 cx.new(|_| Self {
1294 entry_id,
1295 project_path,
1296 is_dirty: true,
1297 })
1298 }
1299 }
1300
1301 impl TestItem {
1302 pub fn new(cx: &mut Context<Self>) -> Self {
1303 Self {
1304 state: String::new(),
1305 label: String::new(),
1306 save_count: 0,
1307 save_as_count: 0,
1308 reload_count: 0,
1309 is_dirty: false,
1310 has_conflict: false,
1311 project_items: Vec::new(),
1312 is_singleton: true,
1313 nav_history: None,
1314 tab_descriptions: None,
1315 tab_detail: Default::default(),
1316 workspace_id: Default::default(),
1317 focus_handle: cx.focus_handle(),
1318 serialize: None,
1319 }
1320 }
1321
1322 pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1323 let mut this = Self::new(cx);
1324 this.workspace_id = Some(id);
1325 this
1326 }
1327
1328 pub fn with_label(mut self, state: &str) -> Self {
1329 self.label = state.to_string();
1330 self
1331 }
1332
1333 pub fn with_singleton(mut self, singleton: bool) -> Self {
1334 self.is_singleton = singleton;
1335 self
1336 }
1337
1338 pub fn with_dirty(mut self, dirty: bool) -> Self {
1339 self.is_dirty = dirty;
1340 self
1341 }
1342
1343 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1344 self.has_conflict = has_conflict;
1345 self
1346 }
1347
1348 pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1349 self.project_items.clear();
1350 self.project_items.extend(items.iter().cloned());
1351 self
1352 }
1353
1354 pub fn with_serialize(
1355 mut self,
1356 serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1357 ) -> Self {
1358 self.serialize = Some(Box::new(serialize));
1359 self
1360 }
1361
1362 pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1363 self.push_to_nav_history(cx);
1364 self.state = state;
1365 }
1366
1367 fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1368 if let Some(history) = &mut self.nav_history {
1369 history.push(Some(Box::new(self.state.clone())), cx);
1370 }
1371 }
1372 }
1373
1374 impl Render for TestItem {
1375 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1376 gpui::div().track_focus(&self.focus_handle(cx))
1377 }
1378 }
1379
1380 impl EventEmitter<ItemEvent> for TestItem {}
1381
1382 impl Focusable for TestItem {
1383 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1384 self.focus_handle.clone()
1385 }
1386 }
1387
1388 impl Item for TestItem {
1389 type Event = ItemEvent;
1390
1391 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1392 f(*event)
1393 }
1394
1395 fn tab_description(&self, detail: usize, _: &App) -> Option<SharedString> {
1396 self.tab_descriptions.as_ref().and_then(|descriptions| {
1397 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1398 Some(description.into())
1399 })
1400 }
1401
1402 fn telemetry_event_text(&self) -> Option<&'static str> {
1403 None
1404 }
1405
1406 fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1407 self.tab_detail.set(params.detail);
1408 gpui::div().into_any_element()
1409 }
1410
1411 fn for_each_project_item(
1412 &self,
1413 cx: &App,
1414 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1415 ) {
1416 self.project_items
1417 .iter()
1418 .for_each(|item| f(item.entity_id(), item.read(cx)))
1419 }
1420
1421 fn is_singleton(&self, _: &App) -> bool {
1422 self.is_singleton
1423 }
1424
1425 fn set_nav_history(
1426 &mut self,
1427 history: ItemNavHistory,
1428 _window: &mut Window,
1429 _: &mut Context<Self>,
1430 ) {
1431 self.nav_history = Some(history);
1432 }
1433
1434 fn navigate(
1435 &mut self,
1436 state: Box<dyn Any>,
1437 _window: &mut Window,
1438 _: &mut Context<Self>,
1439 ) -> bool {
1440 let state = *state.downcast::<String>().unwrap_or_default();
1441 if state != self.state {
1442 self.state = state;
1443 true
1444 } else {
1445 false
1446 }
1447 }
1448
1449 fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1450 self.push_to_nav_history(cx);
1451 }
1452
1453 fn clone_on_split(
1454 &self,
1455 _workspace_id: Option<WorkspaceId>,
1456 _: &mut Window,
1457 cx: &mut Context<Self>,
1458 ) -> Option<Entity<Self>>
1459 where
1460 Self: Sized,
1461 {
1462 Some(cx.new(|cx| Self {
1463 state: self.state.clone(),
1464 label: self.label.clone(),
1465 save_count: self.save_count,
1466 save_as_count: self.save_as_count,
1467 reload_count: self.reload_count,
1468 is_dirty: self.is_dirty,
1469 is_singleton: self.is_singleton,
1470 has_conflict: self.has_conflict,
1471 project_items: self.project_items.clone(),
1472 nav_history: None,
1473 tab_descriptions: None,
1474 tab_detail: Default::default(),
1475 workspace_id: self.workspace_id,
1476 focus_handle: cx.focus_handle(),
1477 serialize: None,
1478 }))
1479 }
1480
1481 fn is_dirty(&self, _: &App) -> bool {
1482 self.is_dirty
1483 }
1484
1485 fn has_conflict(&self, _: &App) -> bool {
1486 self.has_conflict
1487 }
1488
1489 fn can_save(&self, cx: &App) -> bool {
1490 !self.project_items.is_empty()
1491 && self
1492 .project_items
1493 .iter()
1494 .all(|item| item.read(cx).entry_id.is_some())
1495 }
1496
1497 fn can_save_as(&self, _cx: &App) -> bool {
1498 self.is_singleton
1499 }
1500
1501 fn save(
1502 &mut self,
1503 _: bool,
1504 _: Entity<Project>,
1505 _window: &mut Window,
1506 cx: &mut Context<Self>,
1507 ) -> Task<anyhow::Result<()>> {
1508 self.save_count += 1;
1509 self.is_dirty = false;
1510 for item in &self.project_items {
1511 item.update(cx, |item, _| {
1512 if item.is_dirty {
1513 item.is_dirty = false;
1514 }
1515 })
1516 }
1517 Task::ready(Ok(()))
1518 }
1519
1520 fn save_as(
1521 &mut self,
1522 _: Entity<Project>,
1523 _: ProjectPath,
1524 _window: &mut Window,
1525 _: &mut Context<Self>,
1526 ) -> Task<anyhow::Result<()>> {
1527 self.save_as_count += 1;
1528 self.is_dirty = false;
1529 Task::ready(Ok(()))
1530 }
1531
1532 fn reload(
1533 &mut self,
1534 _: Entity<Project>,
1535 _window: &mut Window,
1536 _: &mut Context<Self>,
1537 ) -> Task<anyhow::Result<()>> {
1538 self.reload_count += 1;
1539 self.is_dirty = false;
1540 Task::ready(Ok(()))
1541 }
1542 }
1543
1544 impl SerializableItem for TestItem {
1545 fn serialized_item_kind() -> &'static str {
1546 "TestItem"
1547 }
1548
1549 fn deserialize(
1550 _project: Entity<Project>,
1551 _workspace: WeakEntity<Workspace>,
1552 workspace_id: WorkspaceId,
1553 _item_id: ItemId,
1554 _window: &mut Window,
1555 cx: &mut App,
1556 ) -> Task<anyhow::Result<Entity<Self>>> {
1557 let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1558 Task::ready(Ok(entity))
1559 }
1560
1561 fn cleanup(
1562 _workspace_id: WorkspaceId,
1563 _alive_items: Vec<ItemId>,
1564 _window: &mut Window,
1565 _cx: &mut App,
1566 ) -> Task<anyhow::Result<()>> {
1567 Task::ready(Ok(()))
1568 }
1569
1570 fn serialize(
1571 &mut self,
1572 _workspace: &mut Workspace,
1573 _item_id: ItemId,
1574 _closing: bool,
1575 _window: &mut Window,
1576 _cx: &mut Context<Self>,
1577 ) -> Option<Task<anyhow::Result<()>>> {
1578 if let Some(serialize) = self.serialize.take() {
1579 let result = serialize();
1580 self.serialize = Some(serialize);
1581 result
1582 } else {
1583 None
1584 }
1585 }
1586
1587 fn should_serialize(&self, _event: &Self::Event) -> bool {
1588 false
1589 }
1590 }
1591}