1use crate::{
2 DelayedDebouncedEditAction, FollowableViewRegistry, ItemNavHistory, SerializableItemRegistry,
3 ToolbarItemLocation, ViewId, Workspace, WorkspaceId,
4 pane::{self, Pane},
5 persistence::model::ItemId,
6 searchable::SearchableItemHandle,
7 workspace_settings::{AutosaveSetting, WorkspaceSettings},
8};
9use anyhow::Result;
10use client::{
11 Client,
12 proto::{self, PeerId},
13};
14use futures::{StreamExt, channel::mpsc};
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(Clone, Copy, Default, Debug)]
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
1034#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1035pub struct ProjectItemKind(pub &'static str);
1036
1037pub trait ProjectItem: Item {
1038 type Item: project::ProjectItem;
1039
1040 fn project_item_kind() -> Option<ProjectItemKind> {
1041 None
1042 }
1043
1044 fn for_project_item(
1045 project: Entity<Project>,
1046 pane: &Pane,
1047 item: Entity<Self::Item>,
1048 window: &mut Window,
1049 cx: &mut Context<Self>,
1050 ) -> Self
1051 where
1052 Self: Sized;
1053}
1054
1055#[derive(Debug)]
1056pub enum FollowEvent {
1057 Unfollow,
1058}
1059
1060pub enum Dedup {
1061 KeepExisting,
1062 ReplaceExisting,
1063}
1064
1065pub trait FollowableItem: Item {
1066 fn remote_id(&self) -> Option<ViewId>;
1067 fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant>;
1068 fn from_state_proto(
1069 project: Entity<Workspace>,
1070 id: ViewId,
1071 state: &mut Option<proto::view::Variant>,
1072 window: &mut Window,
1073 cx: &mut App,
1074 ) -> Option<Task<Result<Entity<Self>>>>;
1075 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1076 fn add_event_to_update_proto(
1077 &self,
1078 event: &Self::Event,
1079 update: &mut Option<proto::update_view::Variant>,
1080 window: &Window,
1081 cx: &App,
1082 ) -> bool;
1083 fn apply_update_proto(
1084 &mut self,
1085 project: &Entity<Project>,
1086 message: proto::update_view::Variant,
1087 window: &mut Window,
1088 cx: &mut Context<Self>,
1089 ) -> Task<Result<()>>;
1090 fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1091 fn set_leader_peer_id(
1092 &mut self,
1093 leader_peer_id: Option<PeerId>,
1094 window: &mut Window,
1095 cx: &mut Context<Self>,
1096 );
1097 fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1098}
1099
1100pub trait FollowableItemHandle: ItemHandle {
1101 fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1102 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1103 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, window: &mut Window, cx: &mut App);
1104 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1105 fn add_event_to_update_proto(
1106 &self,
1107 event: &dyn Any,
1108 update: &mut Option<proto::update_view::Variant>,
1109 window: &mut Window,
1110 cx: &mut App,
1111 ) -> bool;
1112 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1113 fn apply_update_proto(
1114 &self,
1115 project: &Entity<Project>,
1116 message: proto::update_view::Variant,
1117 window: &mut Window,
1118 cx: &mut App,
1119 ) -> Task<Result<()>>;
1120 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1121 fn dedup(
1122 &self,
1123 existing: &dyn FollowableItemHandle,
1124 window: &mut Window,
1125 cx: &mut App,
1126 ) -> Option<Dedup>;
1127}
1128
1129impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1130 fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1131 self.read(cx).remote_id().or_else(|| {
1132 client.peer_id().map(|creator| ViewId {
1133 creator,
1134 id: self.item_id().as_u64(),
1135 })
1136 })
1137 }
1138
1139 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1140 Box::new(self.downgrade())
1141 }
1142
1143 fn set_leader_peer_id(
1144 &self,
1145 leader_peer_id: Option<PeerId>,
1146 window: &mut Window,
1147 cx: &mut App,
1148 ) {
1149 self.update(cx, |this, cx| {
1150 this.set_leader_peer_id(leader_peer_id, window, cx)
1151 })
1152 }
1153
1154 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1155 self.read(cx).to_state_proto(window, cx)
1156 }
1157
1158 fn add_event_to_update_proto(
1159 &self,
1160 event: &dyn Any,
1161 update: &mut Option<proto::update_view::Variant>,
1162 window: &mut Window,
1163 cx: &mut App,
1164 ) -> bool {
1165 if let Some(event) = event.downcast_ref() {
1166 self.read(cx)
1167 .add_event_to_update_proto(event, update, window, cx)
1168 } else {
1169 false
1170 }
1171 }
1172
1173 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
1174 T::to_follow_event(event.downcast_ref()?)
1175 }
1176
1177 fn apply_update_proto(
1178 &self,
1179 project: &Entity<Project>,
1180 message: proto::update_view::Variant,
1181 window: &mut Window,
1182 cx: &mut App,
1183 ) -> Task<Result<()>> {
1184 self.update(cx, |this, cx| {
1185 this.apply_update_proto(project, message, window, cx)
1186 })
1187 }
1188
1189 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool {
1190 self.read(cx).is_project_item(window, cx)
1191 }
1192
1193 fn dedup(
1194 &self,
1195 existing: &dyn FollowableItemHandle,
1196 window: &mut Window,
1197 cx: &mut App,
1198 ) -> Option<Dedup> {
1199 let existing = existing.to_any().downcast::<T>().ok()?;
1200 self.read(cx).dedup(existing.read(cx), window, cx)
1201 }
1202}
1203
1204pub trait WeakFollowableItemHandle: Send + Sync {
1205 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
1206}
1207
1208impl<T: FollowableItem> WeakFollowableItemHandle for WeakEntity<T> {
1209 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
1210 Some(Box::new(self.upgrade()?))
1211 }
1212}
1213
1214#[cfg(any(test, feature = "test-support"))]
1215pub mod test {
1216 use super::{Item, ItemEvent, SerializableItem, TabContentParams};
1217 use crate::{ItemId, ItemNavHistory, Workspace, WorkspaceId};
1218 use gpui::{
1219 AnyElement, App, AppContext as _, Context, Entity, EntityId, EventEmitter, Focusable,
1220 InteractiveElement, IntoElement, Render, SharedString, Task, WeakEntity, Window,
1221 };
1222 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
1223 use std::{any::Any, cell::Cell, path::Path};
1224
1225 pub struct TestProjectItem {
1226 pub entry_id: Option<ProjectEntryId>,
1227 pub project_path: Option<ProjectPath>,
1228 pub is_dirty: bool,
1229 }
1230
1231 pub struct TestItem {
1232 pub workspace_id: Option<WorkspaceId>,
1233 pub state: String,
1234 pub label: String,
1235 pub save_count: usize,
1236 pub save_as_count: usize,
1237 pub reload_count: usize,
1238 pub is_dirty: bool,
1239 pub is_singleton: bool,
1240 pub has_conflict: bool,
1241 pub project_items: Vec<Entity<TestProjectItem>>,
1242 pub nav_history: Option<ItemNavHistory>,
1243 pub tab_descriptions: Option<Vec<&'static str>>,
1244 pub tab_detail: Cell<Option<usize>>,
1245 serialize: Option<Box<dyn Fn() -> Option<Task<anyhow::Result<()>>>>>,
1246 focus_handle: gpui::FocusHandle,
1247 }
1248
1249 impl project::ProjectItem for TestProjectItem {
1250 fn try_open(
1251 _project: &Entity<Project>,
1252 _path: &ProjectPath,
1253 _cx: &mut App,
1254 ) -> Option<Task<gpui::Result<Entity<Self>>>> {
1255 None
1256 }
1257 fn entry_id(&self, _: &App) -> Option<ProjectEntryId> {
1258 self.entry_id
1259 }
1260
1261 fn project_path(&self, _: &App) -> Option<ProjectPath> {
1262 self.project_path.clone()
1263 }
1264
1265 fn is_dirty(&self) -> bool {
1266 self.is_dirty
1267 }
1268 }
1269
1270 pub enum TestItemEvent {
1271 Edit,
1272 }
1273
1274 impl TestProjectItem {
1275 pub fn new(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1276 let entry_id = Some(ProjectEntryId::from_proto(id));
1277 let project_path = Some(ProjectPath {
1278 worktree_id: WorktreeId::from_usize(0),
1279 path: Path::new(path).into(),
1280 });
1281 cx.new(|_| Self {
1282 entry_id,
1283 project_path,
1284 is_dirty: false,
1285 })
1286 }
1287
1288 pub fn new_untitled(cx: &mut App) -> Entity<Self> {
1289 cx.new(|_| Self {
1290 project_path: None,
1291 entry_id: None,
1292 is_dirty: false,
1293 })
1294 }
1295
1296 pub fn new_dirty(id: u64, path: &str, cx: &mut App) -> Entity<Self> {
1297 let entry_id = Some(ProjectEntryId::from_proto(id));
1298 let project_path = Some(ProjectPath {
1299 worktree_id: WorktreeId::from_usize(0),
1300 path: Path::new(path).into(),
1301 });
1302 cx.new(|_| Self {
1303 entry_id,
1304 project_path,
1305 is_dirty: true,
1306 })
1307 }
1308 }
1309
1310 impl TestItem {
1311 pub fn new(cx: &mut Context<Self>) -> Self {
1312 Self {
1313 state: String::new(),
1314 label: String::new(),
1315 save_count: 0,
1316 save_as_count: 0,
1317 reload_count: 0,
1318 is_dirty: false,
1319 has_conflict: false,
1320 project_items: Vec::new(),
1321 is_singleton: true,
1322 nav_history: None,
1323 tab_descriptions: None,
1324 tab_detail: Default::default(),
1325 workspace_id: Default::default(),
1326 focus_handle: cx.focus_handle(),
1327 serialize: None,
1328 }
1329 }
1330
1331 pub fn new_deserialized(id: WorkspaceId, cx: &mut Context<Self>) -> Self {
1332 let mut this = Self::new(cx);
1333 this.workspace_id = Some(id);
1334 this
1335 }
1336
1337 pub fn with_label(mut self, state: &str) -> Self {
1338 self.label = state.to_string();
1339 self
1340 }
1341
1342 pub fn with_singleton(mut self, singleton: bool) -> Self {
1343 self.is_singleton = singleton;
1344 self
1345 }
1346
1347 pub fn with_dirty(mut self, dirty: bool) -> Self {
1348 self.is_dirty = dirty;
1349 self
1350 }
1351
1352 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1353 self.has_conflict = has_conflict;
1354 self
1355 }
1356
1357 pub fn with_project_items(mut self, items: &[Entity<TestProjectItem>]) -> Self {
1358 self.project_items.clear();
1359 self.project_items.extend(items.iter().cloned());
1360 self
1361 }
1362
1363 pub fn with_serialize(
1364 mut self,
1365 serialize: impl Fn() -> Option<Task<anyhow::Result<()>>> + 'static,
1366 ) -> Self {
1367 self.serialize = Some(Box::new(serialize));
1368 self
1369 }
1370
1371 pub fn set_state(&mut self, state: String, cx: &mut Context<Self>) {
1372 self.push_to_nav_history(cx);
1373 self.state = state;
1374 }
1375
1376 fn push_to_nav_history(&mut self, cx: &mut Context<Self>) {
1377 if let Some(history) = &mut self.nav_history {
1378 history.push(Some(Box::new(self.state.clone())), cx);
1379 }
1380 }
1381 }
1382
1383 impl Render for TestItem {
1384 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1385 gpui::div().track_focus(&self.focus_handle(cx))
1386 }
1387 }
1388
1389 impl EventEmitter<ItemEvent> for TestItem {}
1390
1391 impl Focusable for TestItem {
1392 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
1393 self.focus_handle.clone()
1394 }
1395 }
1396
1397 impl Item for TestItem {
1398 type Event = ItemEvent;
1399
1400 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1401 f(*event)
1402 }
1403
1404 fn tab_description(&self, detail: usize, _: &App) -> Option<SharedString> {
1405 self.tab_descriptions.as_ref().and_then(|descriptions| {
1406 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1407 Some(description.into())
1408 })
1409 }
1410
1411 fn telemetry_event_text(&self) -> Option<&'static str> {
1412 None
1413 }
1414
1415 fn tab_content(&self, params: TabContentParams, _window: &Window, _cx: &App) -> AnyElement {
1416 self.tab_detail.set(params.detail);
1417 gpui::div().into_any_element()
1418 }
1419
1420 fn for_each_project_item(
1421 &self,
1422 cx: &App,
1423 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
1424 ) {
1425 self.project_items
1426 .iter()
1427 .for_each(|item| f(item.entity_id(), item.read(cx)))
1428 }
1429
1430 fn is_singleton(&self, _: &App) -> bool {
1431 self.is_singleton
1432 }
1433
1434 fn set_nav_history(
1435 &mut self,
1436 history: ItemNavHistory,
1437 _window: &mut Window,
1438 _: &mut Context<Self>,
1439 ) {
1440 self.nav_history = Some(history);
1441 }
1442
1443 fn navigate(
1444 &mut self,
1445 state: Box<dyn Any>,
1446 _window: &mut Window,
1447 _: &mut Context<Self>,
1448 ) -> bool {
1449 let state = *state.downcast::<String>().unwrap_or_default();
1450 if state != self.state {
1451 self.state = state;
1452 true
1453 } else {
1454 false
1455 }
1456 }
1457
1458 fn deactivated(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
1459 self.push_to_nav_history(cx);
1460 }
1461
1462 fn clone_on_split(
1463 &self,
1464 _workspace_id: Option<WorkspaceId>,
1465 _: &mut Window,
1466 cx: &mut Context<Self>,
1467 ) -> Option<Entity<Self>>
1468 where
1469 Self: Sized,
1470 {
1471 Some(cx.new(|cx| Self {
1472 state: self.state.clone(),
1473 label: self.label.clone(),
1474 save_count: self.save_count,
1475 save_as_count: self.save_as_count,
1476 reload_count: self.reload_count,
1477 is_dirty: self.is_dirty,
1478 is_singleton: self.is_singleton,
1479 has_conflict: self.has_conflict,
1480 project_items: self.project_items.clone(),
1481 nav_history: None,
1482 tab_descriptions: None,
1483 tab_detail: Default::default(),
1484 workspace_id: self.workspace_id,
1485 focus_handle: cx.focus_handle(),
1486 serialize: None,
1487 }))
1488 }
1489
1490 fn is_dirty(&self, _: &App) -> bool {
1491 self.is_dirty
1492 }
1493
1494 fn has_conflict(&self, _: &App) -> bool {
1495 self.has_conflict
1496 }
1497
1498 fn can_save(&self, cx: &App) -> bool {
1499 !self.project_items.is_empty()
1500 && self
1501 .project_items
1502 .iter()
1503 .all(|item| item.read(cx).entry_id.is_some())
1504 }
1505
1506 fn can_save_as(&self, _cx: &App) -> bool {
1507 self.is_singleton
1508 }
1509
1510 fn save(
1511 &mut self,
1512 _: bool,
1513 _: Entity<Project>,
1514 _window: &mut Window,
1515 cx: &mut Context<Self>,
1516 ) -> Task<anyhow::Result<()>> {
1517 self.save_count += 1;
1518 self.is_dirty = false;
1519 for item in &self.project_items {
1520 item.update(cx, |item, _| {
1521 if item.is_dirty {
1522 item.is_dirty = false;
1523 }
1524 })
1525 }
1526 Task::ready(Ok(()))
1527 }
1528
1529 fn save_as(
1530 &mut self,
1531 _: Entity<Project>,
1532 _: ProjectPath,
1533 _window: &mut Window,
1534 _: &mut Context<Self>,
1535 ) -> Task<anyhow::Result<()>> {
1536 self.save_as_count += 1;
1537 self.is_dirty = false;
1538 Task::ready(Ok(()))
1539 }
1540
1541 fn reload(
1542 &mut self,
1543 _: Entity<Project>,
1544 _window: &mut Window,
1545 _: &mut Context<Self>,
1546 ) -> Task<anyhow::Result<()>> {
1547 self.reload_count += 1;
1548 self.is_dirty = false;
1549 Task::ready(Ok(()))
1550 }
1551 }
1552
1553 impl SerializableItem for TestItem {
1554 fn serialized_item_kind() -> &'static str {
1555 "TestItem"
1556 }
1557
1558 fn deserialize(
1559 _project: Entity<Project>,
1560 _workspace: WeakEntity<Workspace>,
1561 workspace_id: WorkspaceId,
1562 _item_id: ItemId,
1563 _window: &mut Window,
1564 cx: &mut App,
1565 ) -> Task<anyhow::Result<Entity<Self>>> {
1566 let entity = cx.new(|cx| Self::new_deserialized(workspace_id, cx));
1567 Task::ready(Ok(entity))
1568 }
1569
1570 fn cleanup(
1571 _workspace_id: WorkspaceId,
1572 _alive_items: Vec<ItemId>,
1573 _window: &mut Window,
1574 _cx: &mut App,
1575 ) -> Task<anyhow::Result<()>> {
1576 Task::ready(Ok(()))
1577 }
1578
1579 fn serialize(
1580 &mut self,
1581 _workspace: &mut Workspace,
1582 _item_id: ItemId,
1583 _closing: bool,
1584 _window: &mut Window,
1585 _cx: &mut Context<Self>,
1586 ) -> Option<Task<anyhow::Result<()>>> {
1587 if let Some(serialize) = self.serialize.take() {
1588 let result = serialize();
1589 self.serialize = Some(serialize);
1590 result
1591 } else {
1592 None
1593 }
1594 }
1595
1596 fn should_serialize(&self, _event: &Self::Event) -> bool {
1597 false
1598 }
1599 }
1600}