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