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