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 ui::{Color, Icon, IntoElement, Label, LabelCommon};
35use util::ResultExt;
36
37pub const LEADER_UPDATE_THROTTLE: Duration = Duration::from_millis(200);
38
39#[derive(Clone, Copy, Debug)]
40pub struct SaveOptions {
41 pub format: bool,
42 pub autosave: bool,
43}
44
45impl Default for SaveOptions {
46 fn default() -> Self {
47 Self {
48 format: true,
49 autosave: false,
50 }
51 }
52}
53
54#[derive(RegisterSetting)]
55pub struct ItemSettings {
56 pub git_status: bool,
57 pub close_position: ClosePosition,
58 pub activate_on_close: ActivateOnClose,
59 pub file_icons: bool,
60 pub show_diagnostics: ShowDiagnostics,
61 pub show_close_button: ShowCloseButton,
62}
63
64#[derive(RegisterSetting)]
65pub struct PreviewTabsSettings {
66 pub enabled: bool,
67 pub enable_preview_from_project_panel: bool,
68 pub enable_preview_from_file_finder: bool,
69 pub enable_preview_from_multibuffer: bool,
70 pub enable_preview_multibuffer_from_code_navigation: bool,
71 pub enable_preview_file_from_code_navigation: bool,
72 pub enable_keep_preview_on_code_navigation: bool,
73}
74
75impl Settings for ItemSettings {
76 fn from_settings(content: &settings::SettingsContent) -> Self {
77 let tabs = content.tabs.as_ref().unwrap();
78 Self {
79 git_status: tabs.git_status.unwrap()
80 && content
81 .git
82 .unwrap()
83 .enabled
84 .unwrap()
85 .is_git_status_enabled(),
86 close_position: tabs.close_position.unwrap(),
87 activate_on_close: tabs.activate_on_close.unwrap(),
88 file_icons: tabs.file_icons.unwrap(),
89 show_diagnostics: tabs.show_diagnostics.unwrap(),
90 show_close_button: tabs.show_close_button.unwrap(),
91 }
92 }
93}
94
95impl Settings for PreviewTabsSettings {
96 fn from_settings(content: &settings::SettingsContent) -> Self {
97 let preview_tabs = content.preview_tabs.as_ref().unwrap();
98 Self {
99 enabled: preview_tabs.enabled.unwrap(),
100 enable_preview_from_project_panel: preview_tabs
101 .enable_preview_from_project_panel
102 .unwrap(),
103 enable_preview_from_file_finder: preview_tabs.enable_preview_from_file_finder.unwrap(),
104 enable_preview_from_multibuffer: preview_tabs.enable_preview_from_multibuffer.unwrap(),
105 enable_preview_multibuffer_from_code_navigation: preview_tabs
106 .enable_preview_multibuffer_from_code_navigation
107 .unwrap(),
108 enable_preview_file_from_code_navigation: preview_tabs
109 .enable_preview_file_from_code_navigation
110 .unwrap(),
111 enable_keep_preview_on_code_navigation: preview_tabs
112 .enable_keep_preview_on_code_navigation
113 .unwrap(),
114 }
115 }
116}
117
118#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
119pub enum ItemEvent {
120 CloseItem,
121 UpdateTab,
122 UpdateBreadcrumbs,
123 Edit,
124}
125
126// TODO: Combine this with existing HighlightedText struct?
127#[derive(Debug)]
128pub struct BreadcrumbText {
129 pub text: String,
130 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
131 pub font: Option<Font>,
132}
133
134#[derive(Clone, Copy, Default, Debug)]
135pub struct TabContentParams {
136 pub detail: Option<usize>,
137 pub selected: bool,
138 pub preview: bool,
139 /// Tab content should be deemphasized when active pane does not have focus.
140 pub deemphasized: bool,
141}
142
143impl TabContentParams {
144 /// Returns the text color to be used for the tab content.
145 pub fn text_color(&self) -> Color {
146 if self.deemphasized {
147 if self.selected {
148 Color::Muted
149 } else {
150 Color::Hidden
151 }
152 } else if self.selected {
153 Color::Default
154 } else {
155 Color::Muted
156 }
157 }
158}
159
160pub enum TabTooltipContent {
161 Text(SharedString),
162 Custom(Box<dyn Fn(&mut Window, &mut App) -> AnyView>),
163}
164
165#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
166pub enum ItemBufferKind {
167 Multibuffer,
168 Singleton,
169 None,
170}
171
172pub trait Item: Focusable + EventEmitter<Self::Event> + Render + Sized {
173 type Event;
174
175 /// Returns the tab contents.
176 ///
177 /// By default this returns a [`Label`] that displays that text from
178 /// `tab_content_text`.
179 fn tab_content(&self, params: TabContentParams, _window: &Window, cx: &App) -> AnyElement {
180 let text = self.tab_content_text(params.detail.unwrap_or_default(), cx);
181
182 Label::new(text)
183 .color(params.text_color())
184 .into_any_element()
185 }
186
187 /// Returns the textual contents of the tab.
188 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString;
189
190 /// Returns the suggested filename for saving this item.
191 /// By default, returns the tab content text.
192 fn suggested_filename(&self, cx: &App) -> SharedString {
193 self.tab_content_text(0, cx)
194 }
195
196 fn tab_icon(&self, _window: &Window, _cx: &App) -> Option<Icon> {
197 None
198 }
199
200 /// Returns the tab tooltip text.
201 ///
202 /// Use this if you don't need to customize the tab tooltip content.
203 fn tab_tooltip_text(&self, _: &App) -> Option<SharedString> {
204 None
205 }
206
207 /// Returns the tab tooltip content.
208 ///
209 /// By default this returns a Tooltip text from
210 /// `tab_tooltip_text`.
211 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
212 self.tab_tooltip_text(cx).map(TabTooltipContent::Text)
213 }
214
215 fn to_item_events(_event: &Self::Event, _f: &mut dyn FnMut(ItemEvent)) {}
216
217 fn deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
218 fn discarded(&self, _project: Entity<Project>, _window: &mut Window, _cx: &mut Context<Self>) {}
219 fn on_removed(&self, _cx: &mut Context<Self>) {}
220 fn workspace_deactivated(&mut self, _window: &mut Window, _: &mut Context<Self>) {}
221 fn navigate(
222 &mut self,
223 _: Arc<dyn Any + Send>,
224 _window: &mut Window,
225 _: &mut Context<Self>,
226 ) -> bool {
227 false
228 }
229
230 fn telemetry_event_text(&self) -> Option<&'static str> {
231 None
232 }
233
234 /// (model id, Item)
235 fn for_each_project_item(
236 &self,
237 _: &App,
238 _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
239 ) {
240 }
241 fn buffer_kind(&self, _cx: &App) -> ItemBufferKind {
242 ItemBufferKind::None
243 }
244 fn set_nav_history(&mut self, _: ItemNavHistory, _window: &mut Window, _: &mut Context<Self>) {}
245
246 fn can_split(&self) -> bool {
247 false
248 }
249 fn clone_on_split(
250 &self,
251 workspace_id: Option<WorkspaceId>,
252 window: &mut Window,
253 cx: &mut Context<Self>,
254 ) -> Task<Option<Entity<Self>>>
255 where
256 Self: Sized,
257 {
258 _ = (workspace_id, window, cx);
259 unimplemented!("clone_on_split() must be implemented if can_split() returns true")
260 }
261 fn is_dirty(&self, _: &App) -> bool {
262 false
263 }
264 fn capability(&self, _: &App) -> Capability {
265 Capability::ReadWrite
266 }
267
268 fn toggle_read_only(&mut self, _window: &mut Window, _cx: &mut Context<Self>) {}
269
270 fn has_deleted_file(&self, _: &App) -> bool {
271 false
272 }
273 fn has_conflict(&self, _: &App) -> bool {
274 false
275 }
276 fn can_save(&self, _cx: &App) -> bool {
277 false
278 }
279 fn can_save_as(&self, _: &App) -> bool {
280 false
281 }
282 fn save(
283 &mut self,
284 _options: SaveOptions,
285 _project: Entity<Project>,
286 _window: &mut Window,
287 _cx: &mut Context<Self>,
288 ) -> Task<Result<()>> {
289 unimplemented!("save() must be implemented if can_save() returns true")
290 }
291 fn save_as(
292 &mut self,
293 _project: Entity<Project>,
294 _path: ProjectPath,
295 _window: &mut Window,
296 _cx: &mut Context<Self>,
297 ) -> Task<Result<()>> {
298 unimplemented!("save_as() must be implemented if can_save() returns true")
299 }
300 fn reload(
301 &mut self,
302 _project: Entity<Project>,
303 _window: &mut Window,
304 _cx: &mut Context<Self>,
305 ) -> Task<Result<()>> {
306 unimplemented!("reload() must be implemented if can_save() returns true")
307 }
308
309 fn act_as_type<'a>(
310 &'a self,
311 type_id: TypeId,
312 self_handle: &'a Entity<Self>,
313 _: &'a App,
314 ) -> Option<AnyEntity> {
315 if TypeId::of::<Self>() == type_id {
316 Some(self_handle.clone().into())
317 } else {
318 None
319 }
320 }
321
322 fn as_searchable(&self, _: &Entity<Self>, _: &App) -> Option<Box<dyn SearchableItemHandle>> {
323 None
324 }
325
326 fn breadcrumb_location(&self, _: &App) -> ToolbarItemLocation {
327 ToolbarItemLocation::Hidden
328 }
329
330 fn breadcrumbs(&self, _cx: &App) -> Option<Vec<BreadcrumbText>> {
331 None
332 }
333
334 /// Returns optional elements to render to the left of the breadcrumb.
335 fn breadcrumb_prefix(
336 &self,
337 _window: &mut Window,
338 _cx: &mut Context<Self>,
339 ) -> Option<gpui::AnyElement> {
340 None
341 }
342
343 fn added_to_workspace(
344 &mut self,
345 _workspace: &mut Workspace,
346 _window: &mut Window,
347 _cx: &mut Context<Self>,
348 ) {
349 }
350
351 fn show_toolbar(&self) -> bool {
352 true
353 }
354
355 fn pixel_position_of_cursor(&self, _: &App) -> Option<Point<Pixels>> {
356 None
357 }
358
359 fn preserve_preview(&self, _cx: &App) -> bool {
360 false
361 }
362
363 fn include_in_nav_history() -> bool {
364 true
365 }
366
367 /// Returns additional actions to add to the tab's context menu.
368 /// Each entry is a label and an action to dispatch.
369 fn tab_extra_context_menu_actions(
370 &self,
371 _window: &mut Window,
372 _cx: &mut Context<Self>,
373 ) -> Vec<(SharedString, Box<dyn Action>)> {
374 Vec::new()
375 }
376}
377
378pub trait SerializableItem: Item {
379 fn serialized_item_kind() -> &'static str;
380
381 fn cleanup(
382 workspace_id: WorkspaceId,
383 alive_items: Vec<ItemId>,
384 window: &mut Window,
385 cx: &mut App,
386 ) -> Task<Result<()>>;
387
388 fn deserialize(
389 _project: Entity<Project>,
390 _workspace: WeakEntity<Workspace>,
391 _workspace_id: WorkspaceId,
392 _item_id: ItemId,
393 _window: &mut Window,
394 _cx: &mut App,
395 ) -> Task<Result<Entity<Self>>>;
396
397 fn serialize(
398 &mut self,
399 workspace: &mut Workspace,
400 item_id: ItemId,
401 closing: bool,
402 window: &mut Window,
403 cx: &mut Context<Self>,
404 ) -> Option<Task<Result<()>>>;
405
406 fn should_serialize(&self, event: &Self::Event) -> bool;
407}
408
409pub trait SerializableItemHandle: ItemHandle {
410 fn serialized_item_kind(&self) -> &'static str;
411 fn serialize(
412 &self,
413 workspace: &mut Workspace,
414 closing: bool,
415 window: &mut Window,
416 cx: &mut App,
417 ) -> Option<Task<Result<()>>>;
418 fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool;
419}
420
421impl<T> SerializableItemHandle for Entity<T>
422where
423 T: SerializableItem,
424{
425 fn serialized_item_kind(&self) -> &'static str {
426 T::serialized_item_kind()
427 }
428
429 fn serialize(
430 &self,
431 workspace: &mut Workspace,
432 closing: bool,
433 window: &mut Window,
434 cx: &mut App,
435 ) -> Option<Task<Result<()>>> {
436 self.update(cx, |this, cx| {
437 this.serialize(workspace, cx.entity_id().as_u64(), closing, window, cx)
438 })
439 }
440
441 fn should_serialize(&self, event: &dyn Any, cx: &App) -> bool {
442 event
443 .downcast_ref::<T::Event>()
444 .is_some_and(|event| self.read(cx).should_serialize(event))
445 }
446}
447
448pub trait ItemHandle: 'static + Send {
449 fn item_focus_handle(&self, cx: &App) -> FocusHandle;
450 fn subscribe_to_item_events(
451 &self,
452 window: &mut Window,
453 cx: &mut App,
454 handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
455 ) -> gpui::Subscription;
456 fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement;
457 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString;
458 fn suggested_filename(&self, cx: &App) -> SharedString;
459 fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon>;
460 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString>;
461 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent>;
462 fn telemetry_event_text(&self, cx: &App) -> Option<&'static str>;
463 fn dragged_tab_content(
464 &self,
465 params: TabContentParams,
466 window: &Window,
467 cx: &App,
468 ) -> AnyElement;
469 fn project_path(&self, cx: &App) -> Option<ProjectPath>;
470 fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]>;
471 fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]>;
472 fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]>;
473 fn for_each_project_item(
474 &self,
475 _: &App,
476 _: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
477 );
478 fn buffer_kind(&self, cx: &App) -> ItemBufferKind;
479 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
480 fn can_split(&self, cx: &App) -> bool;
481 fn clone_on_split(
482 &self,
483 workspace_id: Option<WorkspaceId>,
484 window: &mut Window,
485 cx: &mut App,
486 ) -> Task<Option<Box<dyn ItemHandle>>>;
487 fn added_to_pane(
488 &self,
489 workspace: &mut Workspace,
490 pane: Entity<Pane>,
491 window: &mut Window,
492 cx: &mut Context<Workspace>,
493 );
494 fn deactivated(&self, window: &mut Window, cx: &mut App);
495 fn on_removed(&self, cx: &mut App);
496 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App);
497 fn navigate(&self, data: Arc<dyn Any + Send>, window: &mut Window, cx: &mut App) -> bool;
498 fn item_id(&self) -> EntityId;
499 fn to_any_view(&self) -> AnyView;
500 fn is_dirty(&self, cx: &App) -> bool;
501 fn capability(&self, cx: &App) -> Capability;
502 fn toggle_read_only(&self, window: &mut Window, cx: &mut App);
503 fn has_deleted_file(&self, cx: &App) -> bool;
504 fn has_conflict(&self, cx: &App) -> bool;
505 fn can_save(&self, cx: &App) -> bool;
506 fn can_save_as(&self, cx: &App) -> bool;
507 fn save(
508 &self,
509 options: SaveOptions,
510 project: Entity<Project>,
511 window: &mut Window,
512 cx: &mut App,
513 ) -> Task<Result<()>>;
514 fn save_as(
515 &self,
516 project: Entity<Project>,
517 path: ProjectPath,
518 window: &mut Window,
519 cx: &mut App,
520 ) -> Task<Result<()>>;
521 fn reload(
522 &self,
523 project: Entity<Project>,
524 window: &mut Window,
525 cx: &mut App,
526 ) -> Task<Result<()>>;
527 fn act_as_type(&self, type_id: TypeId, cx: &App) -> Option<AnyEntity>;
528 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>>;
529 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>>;
530 fn on_release(
531 &self,
532 cx: &mut App,
533 callback: Box<dyn FnOnce(&mut App) + Send>,
534 ) -> gpui::Subscription;
535 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>>;
536 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation;
537 fn breadcrumbs(&self, cx: &App) -> Option<Vec<BreadcrumbText>>;
538 fn breadcrumb_prefix(&self, window: &mut Window, cx: &mut App) -> Option<gpui::AnyElement>;
539 fn show_toolbar(&self, cx: &App) -> bool;
540 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>>;
541 fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
542 fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings;
543 fn preserve_preview(&self, cx: &App) -> bool;
544 fn include_in_nav_history(&self) -> bool;
545 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App);
546 fn tab_extra_context_menu_actions(
547 &self,
548 window: &mut Window,
549 cx: &mut App,
550 ) -> Vec<(SharedString, Box<dyn Action>)>;
551 fn can_autosave(&self, cx: &App) -> bool {
552 let is_deleted = self.project_entry_ids(cx).is_empty();
553 self.is_dirty(cx) && !self.has_conflict(cx) && self.can_save(cx) && !is_deleted
554 }
555}
556
557pub trait WeakItemHandle: Send + Sync {
558 fn id(&self) -> EntityId;
559 fn boxed_clone(&self) -> Box<dyn WeakItemHandle>;
560 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
561}
562
563impl dyn ItemHandle {
564 pub fn downcast<V: 'static>(&self) -> Option<Entity<V>> {
565 self.to_any_view().downcast().ok()
566 }
567
568 pub fn act_as<V: 'static>(&self, cx: &App) -> Option<Entity<V>> {
569 self.act_as_type(TypeId::of::<V>(), cx)
570 .and_then(|t| t.downcast().ok())
571 }
572}
573
574impl<T: Item> ItemHandle for Entity<T> {
575 fn subscribe_to_item_events(
576 &self,
577 window: &mut Window,
578 cx: &mut App,
579 handler: Box<dyn Fn(ItemEvent, &mut Window, &mut App)>,
580 ) -> gpui::Subscription {
581 window.subscribe(self, cx, move |_, event, window, cx| {
582 T::to_item_events(event, &mut |item_event| handler(item_event, window, cx));
583 })
584 }
585
586 fn item_focus_handle(&self, cx: &App) -> FocusHandle {
587 self.read(cx).focus_handle(cx)
588 }
589
590 fn telemetry_event_text(&self, cx: &App) -> Option<&'static str> {
591 self.read(cx).telemetry_event_text()
592 }
593
594 fn tab_content(&self, params: TabContentParams, window: &Window, cx: &App) -> AnyElement {
595 self.read(cx).tab_content(params, window, cx)
596 }
597 fn tab_content_text(&self, detail: usize, cx: &App) -> SharedString {
598 self.read(cx).tab_content_text(detail, cx)
599 }
600
601 fn suggested_filename(&self, cx: &App) -> SharedString {
602 self.read(cx).suggested_filename(cx)
603 }
604
605 fn tab_icon(&self, window: &Window, cx: &App) -> Option<Icon> {
606 self.read(cx).tab_icon(window, cx)
607 }
608
609 fn tab_tooltip_content(&self, cx: &App) -> Option<TabTooltipContent> {
610 self.read(cx).tab_tooltip_content(cx)
611 }
612
613 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
614 self.read(cx).tab_tooltip_text(cx)
615 }
616
617 fn dragged_tab_content(
618 &self,
619 params: TabContentParams,
620 window: &Window,
621 cx: &App,
622 ) -> AnyElement {
623 self.read(cx).tab_content(
624 TabContentParams {
625 selected: true,
626 ..params
627 },
628 window,
629 cx,
630 )
631 }
632
633 fn project_path(&self, cx: &App) -> Option<ProjectPath> {
634 let this = self.read(cx);
635 let mut result = None;
636 if this.buffer_kind(cx) == ItemBufferKind::Singleton {
637 this.for_each_project_item(cx, &mut |_, item| {
638 result = item.project_path(cx);
639 });
640 }
641 result
642 }
643
644 fn workspace_settings<'a>(&self, cx: &'a App) -> &'a WorkspaceSettings {
645 if let Some(project_path) = self.project_path(cx) {
646 WorkspaceSettings::get(
647 Some(SettingsLocation {
648 worktree_id: project_path.worktree_id,
649 path: &project_path.path,
650 }),
651 cx,
652 )
653 } else {
654 WorkspaceSettings::get_global(cx)
655 }
656 }
657
658 fn project_entry_ids(&self, cx: &App) -> SmallVec<[ProjectEntryId; 3]> {
659 let mut result = SmallVec::new();
660 self.read(cx).for_each_project_item(cx, &mut |_, item| {
661 if let Some(id) = item.entry_id(cx) {
662 result.push(id);
663 }
664 });
665 result
666 }
667
668 fn project_paths(&self, cx: &App) -> SmallVec<[ProjectPath; 3]> {
669 let mut result = SmallVec::new();
670 self.read(cx).for_each_project_item(cx, &mut |_, item| {
671 if let Some(id) = item.project_path(cx) {
672 result.push(id);
673 }
674 });
675 result
676 }
677
678 fn project_item_model_ids(&self, cx: &App) -> SmallVec<[EntityId; 3]> {
679 let mut result = SmallVec::new();
680 self.read(cx).for_each_project_item(cx, &mut |id, _| {
681 result.push(id);
682 });
683 result
684 }
685
686 fn for_each_project_item(
687 &self,
688 cx: &App,
689 f: &mut dyn FnMut(EntityId, &dyn project::ProjectItem),
690 ) {
691 self.read(cx).for_each_project_item(cx, f)
692 }
693
694 fn buffer_kind(&self, cx: &App) -> ItemBufferKind {
695 self.read(cx).buffer_kind(cx)
696 }
697
698 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
699 Box::new(self.clone())
700 }
701
702 fn can_split(&self, cx: &App) -> bool {
703 self.read(cx).can_split()
704 }
705
706 fn clone_on_split(
707 &self,
708 workspace_id: Option<WorkspaceId>,
709 window: &mut Window,
710 cx: &mut App,
711 ) -> Task<Option<Box<dyn ItemHandle>>> {
712 let task = self.update(cx, |item, cx| item.clone_on_split(workspace_id, window, cx));
713 cx.background_spawn(async move {
714 task.await
715 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
716 })
717 }
718
719 fn added_to_pane(
720 &self,
721 workspace: &mut Workspace,
722 pane: Entity<Pane>,
723 window: &mut Window,
724 cx: &mut Context<Workspace>,
725 ) {
726 let weak_item = self.downgrade();
727 let history = pane.read(cx).nav_history_for_item(self);
728 self.update(cx, |this, cx| {
729 this.set_nav_history(history, window, cx);
730 this.added_to_workspace(workspace, window, cx);
731 });
732
733 if let Some(serializable_item) = self.to_serializable_item_handle(cx) {
734 workspace
735 .enqueue_item_serialization(serializable_item)
736 .log_err();
737 }
738
739 if workspace
740 .panes_by_item
741 .insert(self.item_id(), pane.downgrade())
742 .is_none()
743 {
744 let mut pending_autosave = DelayedDebouncedEditAction::new();
745 let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
746 let pending_update = Rc::new(RefCell::new(None));
747
748 let mut send_follower_updates = None;
749 if let Some(item) = self.to_followable_item_handle(cx) {
750 let is_project_item = item.is_project_item(window, cx);
751 let item = item.downgrade();
752
753 send_follower_updates = Some(cx.spawn_in(window, {
754 let pending_update = pending_update.clone();
755 async move |workspace, cx| {
756 while let Some(mut leader_id) = pending_update_rx.next().await {
757 while let Ok(Some(id)) = pending_update_rx.try_next() {
758 leader_id = id;
759 }
760
761 workspace.update_in(cx, |workspace, window, cx| {
762 let Some(item) = item.upgrade() else { return };
763 workspace.update_followers(
764 is_project_item,
765 proto::update_followers::Variant::UpdateView(
766 proto::UpdateView {
767 id: item
768 .remote_id(workspace.client(), window, cx)
769 .and_then(|id| id.to_proto()),
770 variant: pending_update.borrow_mut().take(),
771 leader_id,
772 },
773 ),
774 window,
775 cx,
776 );
777 })?;
778 cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
779 }
780 anyhow::Ok(())
781 }
782 }));
783 }
784
785 let mut event_subscription = Some(cx.subscribe_in(
786 self,
787 window,
788 move |workspace, item: &Entity<T>, event, window, cx| {
789 let pane = if let Some(pane) = workspace
790 .panes_by_item
791 .get(&item.item_id())
792 .and_then(|pane| pane.upgrade())
793 {
794 pane
795 } else {
796 return;
797 };
798
799 if let Some(item) = item.to_followable_item_handle(cx) {
800 let leader_id = workspace.leader_for_pane(&pane);
801
802 if let Some(leader_id) = leader_id
803 && let Some(FollowEvent::Unfollow) = item.to_follow_event(event)
804 {
805 workspace.unfollow(leader_id, window, cx);
806 }
807
808 if item.item_focus_handle(cx).contains_focused(window, cx) {
809 match leader_id {
810 Some(CollaboratorId::Agent) => {}
811 Some(CollaboratorId::PeerId(leader_peer_id)) => {
812 item.add_event_to_update_proto(
813 event,
814 &mut pending_update.borrow_mut(),
815 window,
816 cx,
817 );
818 pending_update_tx.unbounded_send(Some(leader_peer_id)).ok();
819 }
820 None => {
821 item.add_event_to_update_proto(
822 event,
823 &mut pending_update.borrow_mut(),
824 window,
825 cx,
826 );
827 pending_update_tx.unbounded_send(None).ok();
828 }
829 }
830 }
831 }
832
833 if let Some(item) = item.to_serializable_item_handle(cx)
834 && item.should_serialize(event, cx)
835 {
836 workspace.enqueue_item_serialization(item).ok();
837 }
838
839 T::to_item_events(event, &mut |event| match event {
840 ItemEvent::CloseItem => {
841 pane.update(cx, |pane, cx| {
842 pane.close_item_by_id(
843 item.item_id(),
844 crate::SaveIntent::Close,
845 window,
846 cx,
847 )
848 })
849 .detach_and_log_err(cx);
850 }
851
852 ItemEvent::UpdateTab => {
853 workspace.update_item_dirty_state(item, window, cx);
854
855 if item.has_deleted_file(cx)
856 && !item.is_dirty(cx)
857 && item.workspace_settings(cx).close_on_file_delete
858 {
859 let item_id = item.item_id();
860 let close_item_task = pane.update(cx, |pane, cx| {
861 pane.close_item_by_id(
862 item_id,
863 crate::SaveIntent::Close,
864 window,
865 cx,
866 )
867 });
868 cx.spawn_in(window, {
869 let pane = pane.clone();
870 async move |_workspace, cx| {
871 close_item_task.await?;
872 pane.update(cx, |pane, _cx| {
873 pane.nav_history_mut().remove_item(item_id);
874 });
875 anyhow::Ok(())
876 }
877 })
878 .detach_and_log_err(cx);
879 } else {
880 pane.update(cx, |_, cx| {
881 cx.emit(pane::Event::ChangeItemTitle);
882 cx.notify();
883 });
884 }
885 }
886
887 ItemEvent::Edit => {
888 let autosave = item.workspace_settings(cx).autosave;
889
890 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
891 let delay = Duration::from_millis(milliseconds.0);
892 let item = item.clone();
893 pending_autosave.fire_new(
894 delay,
895 window,
896 cx,
897 move |workspace, window, cx| {
898 Pane::autosave_item(
899 &item,
900 workspace.project().clone(),
901 window,
902 cx,
903 )
904 },
905 );
906 }
907 pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
908 }
909
910 _ => {}
911 });
912 },
913 ));
914
915 cx.on_blur(
916 &self.read(cx).focus_handle(cx),
917 window,
918 move |workspace, window, cx| {
919 if let Some(item) = weak_item.upgrade()
920 && item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange
921 {
922 // Only trigger autosave if focus has truly left the item.
923 // If focus is still within the item's hierarchy (e.g., moved to a context menu),
924 // don't trigger autosave to avoid unwanted formatting and cursor jumps.
925 // Also skip autosave if focus moved to a modal (e.g., command palette),
926 // since the user is still interacting with the workspace.
927 let focus_handle = item.item_focus_handle(cx);
928 if !focus_handle.contains_focused(window, cx)
929 && !workspace.has_active_modal(window, cx)
930 {
931 Pane::autosave_item(&item, workspace.project.clone(), window, cx)
932 .detach_and_log_err(cx);
933 }
934 }
935 },
936 )
937 .detach();
938
939 let item_id = self.item_id();
940 workspace.update_item_dirty_state(self, window, cx);
941 cx.observe_release_in(self, window, move |workspace, _, _, _| {
942 workspace.panes_by_item.remove(&item_id);
943 event_subscription.take();
944 send_follower_updates.take();
945 })
946 .detach();
947 }
948
949 cx.defer_in(window, |workspace, window, cx| {
950 workspace.serialize_workspace(window, cx);
951 });
952 }
953
954 fn deactivated(&self, window: &mut Window, cx: &mut App) {
955 self.update(cx, |this, cx| this.deactivated(window, cx));
956 }
957
958 fn on_removed(&self, cx: &mut App) {
959 self.update(cx, |item, cx| item.on_removed(cx));
960 }
961
962 fn workspace_deactivated(&self, window: &mut Window, cx: &mut App) {
963 self.update(cx, |this, cx| this.workspace_deactivated(window, cx));
964 }
965
966 fn navigate(&self, data: Arc<dyn Any + Send>, window: &mut Window, cx: &mut App) -> bool {
967 self.update(cx, |this, cx| this.navigate(data, window, cx))
968 }
969
970 fn item_id(&self) -> EntityId {
971 self.entity_id()
972 }
973
974 fn to_any_view(&self) -> AnyView {
975 self.clone().into()
976 }
977
978 fn is_dirty(&self, cx: &App) -> bool {
979 self.read(cx).is_dirty(cx)
980 }
981
982 fn capability(&self, cx: &App) -> Capability {
983 self.read(cx).capability(cx)
984 }
985
986 fn toggle_read_only(&self, window: &mut Window, cx: &mut App) {
987 self.update(cx, |this, cx| {
988 this.toggle_read_only(window, cx);
989 })
990 }
991
992 fn has_deleted_file(&self, cx: &App) -> bool {
993 self.read(cx).has_deleted_file(cx)
994 }
995
996 fn has_conflict(&self, cx: &App) -> bool {
997 self.read(cx).has_conflict(cx)
998 }
999
1000 fn can_save(&self, cx: &App) -> bool {
1001 self.read(cx).can_save(cx)
1002 }
1003
1004 fn can_save_as(&self, cx: &App) -> bool {
1005 self.read(cx).can_save_as(cx)
1006 }
1007
1008 fn save(
1009 &self,
1010 options: SaveOptions,
1011 project: Entity<Project>,
1012 window: &mut Window,
1013 cx: &mut App,
1014 ) -> Task<Result<()>> {
1015 self.update(cx, |item, cx| item.save(options, project, window, cx))
1016 }
1017
1018 fn save_as(
1019 &self,
1020 project: Entity<Project>,
1021 path: ProjectPath,
1022 window: &mut Window,
1023 cx: &mut App,
1024 ) -> Task<anyhow::Result<()>> {
1025 self.update(cx, |item, cx| item.save_as(project, path, window, cx))
1026 }
1027
1028 fn reload(
1029 &self,
1030 project: Entity<Project>,
1031 window: &mut Window,
1032 cx: &mut App,
1033 ) -> Task<Result<()>> {
1034 self.update(cx, |item, cx| item.reload(project, window, cx))
1035 }
1036
1037 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a App) -> Option<AnyEntity> {
1038 self.read(cx).act_as_type(type_id, self, cx)
1039 }
1040
1041 fn to_followable_item_handle(&self, cx: &App) -> Option<Box<dyn FollowableItemHandle>> {
1042 FollowableViewRegistry::to_followable_view(self.clone(), cx)
1043 }
1044
1045 fn on_release(
1046 &self,
1047 cx: &mut App,
1048 callback: Box<dyn FnOnce(&mut App) + Send>,
1049 ) -> gpui::Subscription {
1050 cx.observe_release(self, move |_, cx| callback(cx))
1051 }
1052
1053 fn to_searchable_item_handle(&self, cx: &App) -> Option<Box<dyn SearchableItemHandle>> {
1054 self.read(cx).as_searchable(self, cx)
1055 }
1056
1057 fn breadcrumb_location(&self, cx: &App) -> ToolbarItemLocation {
1058 self.read(cx).breadcrumb_location(cx)
1059 }
1060
1061 fn breadcrumbs(&self, cx: &App) -> Option<Vec<BreadcrumbText>> {
1062 self.read(cx).breadcrumbs(cx)
1063 }
1064
1065 fn breadcrumb_prefix(&self, window: &mut Window, cx: &mut App) -> Option<gpui::AnyElement> {
1066 self.update(cx, |item, cx| item.breadcrumb_prefix(window, cx))
1067 }
1068
1069 fn show_toolbar(&self, cx: &App) -> bool {
1070 self.read(cx).show_toolbar()
1071 }
1072
1073 fn pixel_position_of_cursor(&self, cx: &App) -> Option<Point<Pixels>> {
1074 self.read(cx).pixel_position_of_cursor(cx)
1075 }
1076
1077 fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
1078 Box::new(self.downgrade())
1079 }
1080
1081 fn to_serializable_item_handle(&self, cx: &App) -> Option<Box<dyn SerializableItemHandle>> {
1082 SerializableItemRegistry::view_to_serializable_item_handle(self.to_any_view(), cx)
1083 }
1084
1085 fn preserve_preview(&self, cx: &App) -> bool {
1086 self.read(cx).preserve_preview(cx)
1087 }
1088
1089 fn include_in_nav_history(&self) -> bool {
1090 T::include_in_nav_history()
1091 }
1092
1093 fn relay_action(&self, action: Box<dyn Action>, window: &mut Window, cx: &mut App) {
1094 self.update(cx, |this, cx| {
1095 this.focus_handle(cx).focus(window, cx);
1096 window.dispatch_action(action, cx);
1097 })
1098 }
1099
1100 fn tab_extra_context_menu_actions(
1101 &self,
1102 window: &mut Window,
1103 cx: &mut App,
1104 ) -> Vec<(SharedString, Box<dyn Action>)> {
1105 self.update(cx, |this, cx| {
1106 this.tab_extra_context_menu_actions(window, cx)
1107 })
1108 }
1109}
1110
1111impl From<Box<dyn ItemHandle>> for AnyView {
1112 fn from(val: Box<dyn ItemHandle>) -> Self {
1113 val.to_any_view()
1114 }
1115}
1116
1117impl From<&Box<dyn ItemHandle>> for AnyView {
1118 fn from(val: &Box<dyn ItemHandle>) -> Self {
1119 val.to_any_view()
1120 }
1121}
1122
1123impl Clone for Box<dyn ItemHandle> {
1124 fn clone(&self) -> Box<dyn ItemHandle> {
1125 self.boxed_clone()
1126 }
1127}
1128
1129impl<T: Item> WeakItemHandle for WeakEntity<T> {
1130 fn id(&self) -> EntityId {
1131 self.entity_id()
1132 }
1133
1134 fn boxed_clone(&self) -> Box<dyn WeakItemHandle> {
1135 Box::new(self.clone())
1136 }
1137
1138 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
1139 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
1140 }
1141}
1142
1143#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1144pub struct ProjectItemKind(pub &'static str);
1145
1146pub trait ProjectItem: Item {
1147 type Item: project::ProjectItem;
1148
1149 fn project_item_kind() -> Option<ProjectItemKind> {
1150 None
1151 }
1152
1153 fn for_project_item(
1154 project: Entity<Project>,
1155 pane: Option<&Pane>,
1156 item: Entity<Self::Item>,
1157 window: &mut Window,
1158 cx: &mut Context<Self>,
1159 ) -> Self
1160 where
1161 Self: Sized;
1162
1163 /// A fallback handler, which will be called after [`project::ProjectItem::try_open`] fails,
1164 /// with the error from that failure as an argument.
1165 /// Allows to open an item that can gracefully display and handle errors.
1166 fn for_broken_project_item(
1167 _abs_path: &Path,
1168 _is_local: bool,
1169 _e: &anyhow::Error,
1170 _window: &mut Window,
1171 _cx: &mut App,
1172 ) -> Option<InvalidItemView>
1173 where
1174 Self: Sized,
1175 {
1176 None
1177 }
1178}
1179
1180#[derive(Debug)]
1181pub enum FollowEvent {
1182 Unfollow,
1183}
1184
1185pub enum Dedup {
1186 KeepExisting,
1187 ReplaceExisting,
1188}
1189
1190pub trait FollowableItem: Item {
1191 fn remote_id(&self) -> Option<ViewId>;
1192 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1193 fn from_state_proto(
1194 project: Entity<Workspace>,
1195 id: ViewId,
1196 state: &mut Option<proto::view::Variant>,
1197 window: &mut Window,
1198 cx: &mut App,
1199 ) -> Option<Task<Result<Entity<Self>>>>;
1200 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
1201 fn add_event_to_update_proto(
1202 &self,
1203 event: &Self::Event,
1204 update: &mut Option<proto::update_view::Variant>,
1205 window: &mut Window,
1206 cx: &mut App,
1207 ) -> bool;
1208 fn apply_update_proto(
1209 &mut self,
1210 project: &Entity<Project>,
1211 message: proto::update_view::Variant,
1212 window: &mut Window,
1213 cx: &mut Context<Self>,
1214 ) -> Task<Result<()>>;
1215 fn is_project_item(&self, window: &Window, cx: &App) -> bool;
1216 fn set_leader_id(
1217 &mut self,
1218 leader_peer_id: Option<CollaboratorId>,
1219 window: &mut Window,
1220 cx: &mut Context<Self>,
1221 );
1222 fn dedup(&self, existing: &Self, window: &Window, cx: &App) -> Option<Dedup>;
1223 fn update_agent_location(
1224 &mut self,
1225 _location: language::Anchor,
1226 _window: &mut Window,
1227 _cx: &mut Context<Self>,
1228 ) {
1229 }
1230}
1231
1232pub trait FollowableItemHandle: ItemHandle {
1233 fn remote_id(&self, client: &Arc<Client>, window: &mut Window, cx: &mut App) -> Option<ViewId>;
1234 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
1235 fn set_leader_id(
1236 &self,
1237 leader_peer_id: Option<CollaboratorId>,
1238 window: &mut Window,
1239 cx: &mut App,
1240 );
1241 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant>;
1242 fn add_event_to_update_proto(
1243 &self,
1244 event: &dyn Any,
1245 update: &mut Option<proto::update_view::Variant>,
1246 window: &mut Window,
1247 cx: &mut App,
1248 ) -> bool;
1249 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
1250 fn apply_update_proto(
1251 &self,
1252 project: &Entity<Project>,
1253 message: proto::update_view::Variant,
1254 window: &mut Window,
1255 cx: &mut App,
1256 ) -> Task<Result<()>>;
1257 fn is_project_item(&self, window: &mut Window, cx: &mut App) -> bool;
1258 fn dedup(
1259 &self,
1260 existing: &dyn FollowableItemHandle,
1261 window: &mut Window,
1262 cx: &mut App,
1263 ) -> Option<Dedup>;
1264 fn update_agent_location(&self, location: language::Anchor, window: &mut Window, cx: &mut App);
1265}
1266
1267impl<T: FollowableItem> FollowableItemHandle for Entity<T> {
1268 fn remote_id(&self, client: &Arc<Client>, _: &mut Window, cx: &mut App) -> Option<ViewId> {
1269 self.read(cx).remote_id().or_else(|| {
1270 client.peer_id().map(|creator| ViewId {
1271 creator: CollaboratorId::PeerId(creator),
1272 id: self.item_id().as_u64(),
1273 })
1274 })
1275 }
1276
1277 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
1278 Box::new(self.downgrade())
1279 }
1280
1281 fn set_leader_id(&self, leader_id: Option<CollaboratorId>, window: &mut Window, cx: &mut App) {
1282 self.update(cx, |this, cx| this.set_leader_id(leader_id, window, cx))
1283 }
1284
1285 fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
1286 self.update(cx, |this, cx| this.to_state_proto(window, cx))
1287 }
1288
1289 fn add_event_to_update_proto(
1290 &self,
1291 event: &dyn Any,
1292 update: &mut Option<proto::update_view::Variant>,
1293 window: &mut Window,
1294 cx: &mut App,
1295 ) -> bool {
1296 if let Some(event) = event.downcast_ref() {
1297 self.update(cx, |this, cx| {
1298 this.add_event_to_update_proto(event, update, window, cx)
1299 })
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, f: &mut dyn 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}