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