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