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