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