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