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