1use crate::{
2 pane::{self, Pane},
3 persistence::model::ItemId,
4 searchable::SearchableItemHandle,
5 workspace_settings::{AutosaveSetting, WorkspaceSettings},
6 DelayedDebouncedEditAction, FollowableItemBuilders, ItemNavHistory, ToolbarItemLocation,
7 ViewId, Workspace, WorkspaceId,
8};
9use anyhow::Result;
10use client::{
11 proto::{self, PeerId},
12 Client,
13};
14use futures::{channel::mpsc, StreamExt};
15use gpui::{
16 AnyElement, AnyView, AppContext, Entity, EntityId, EventEmitter, FocusHandle, FocusableView,
17 Font, HighlightStyle, Model, Pixels, Point, SharedString, Task, View, ViewContext, WeakView,
18 WindowContext,
19};
20use project::{Project, ProjectEntryId, ProjectPath};
21use schemars::JsonSchema;
22use serde::{Deserialize, Serialize};
23use settings::{Settings, SettingsLocation, SettingsSources};
24use smallvec::SmallVec;
25use std::{
26 any::{Any, TypeId},
27 cell::RefCell,
28 ops::Range,
29 rc::Rc,
30 sync::Arc,
31 time::Duration,
32};
33use theme::Theme;
34use ui::Element as _;
35
36pub const LEADER_UPDATE_THROTTLE: Duration = Duration::from_millis(200);
37
38#[derive(Deserialize)]
39pub struct ItemSettings {
40 pub git_status: bool,
41 pub close_position: ClosePosition,
42}
43
44#[derive(Deserialize)]
45pub struct PreviewTabsSettings {
46 pub enabled: bool,
47 pub enable_preview_from_file_finder: bool,
48 pub enable_preview_from_code_navigation: bool,
49}
50
51#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
52#[serde(rename_all = "lowercase")]
53pub enum ClosePosition {
54 Left,
55 #[default]
56 Right,
57}
58
59impl ClosePosition {
60 pub fn right(&self) -> bool {
61 match self {
62 ClosePosition::Left => false,
63 ClosePosition::Right => true,
64 }
65 }
66}
67
68#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
69pub struct ItemSettingsContent {
70 /// Whether to show the Git file status on a tab item.
71 ///
72 /// Default: false
73 git_status: Option<bool>,
74 /// Position of the close button in a tab.
75 ///
76 /// Default: right
77 close_position: Option<ClosePosition>,
78}
79
80#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
81pub struct PreviewTabsSettingsContent {
82 /// Whether to show opened editors as preview tabs.
83 /// Preview tabs do not stay open, are reused until explicitly set to be kept open opened (via double-click or editing) and show file names in italic.
84 ///
85 /// Default: true
86 enabled: Option<bool>,
87 /// Whether to open tabs in preview mode when selected from the file finder.
88 ///
89 /// Default: false
90 enable_preview_from_file_finder: Option<bool>,
91 /// Whether a preview tab gets replaced when code navigation is used to navigate away from the tab.
92 ///
93 /// Default: false
94 enable_preview_from_code_navigation: Option<bool>,
95}
96
97impl Settings for ItemSettings {
98 const KEY: Option<&'static str> = Some("tabs");
99
100 type FileContent = ItemSettingsContent;
101
102 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
103 sources.json_merge()
104 }
105}
106
107impl Settings for PreviewTabsSettings {
108 const KEY: Option<&'static str> = Some("preview_tabs");
109
110 type FileContent = PreviewTabsSettingsContent;
111
112 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
113 sources.json_merge()
114 }
115}
116
117#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
118pub enum ItemEvent {
119 CloseItem,
120 UpdateTab,
121 UpdateBreadcrumbs,
122 Edit,
123}
124
125// TODO: Combine this with existing HighlightedText struct?
126pub struct BreadcrumbText {
127 pub text: String,
128 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
129 pub font: Option<Font>,
130}
131
132#[derive(Debug, Clone, Copy)]
133pub struct TabContentParams {
134 pub detail: Option<usize>,
135 pub selected: bool,
136 pub preview: bool,
137}
138
139pub trait Item: FocusableView + EventEmitter<Self::Event> {
140 type Event;
141 fn tab_content(&self, _params: TabContentParams, _cx: &WindowContext) -> AnyElement {
142 gpui::Empty.into_any()
143 }
144 fn to_item_events(_event: &Self::Event, _f: impl FnMut(ItemEvent)) {}
145
146 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
147 fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
148 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
149 false
150 }
151 fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
152 None
153 }
154 fn tab_description(&self, _: usize, _: &AppContext) -> Option<SharedString> {
155 None
156 }
157
158 fn telemetry_event_text(&self) -> Option<&'static str> {
159 None
160 }
161
162 /// (model id, Item)
163 fn for_each_project_item(
164 &self,
165 _: &AppContext,
166 _: &mut dyn FnMut(EntityId, &dyn project::Item),
167 ) {
168 }
169 fn is_singleton(&self, _cx: &AppContext) -> bool {
170 false
171 }
172 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
173 fn clone_on_split(
174 &self,
175 _workspace_id: Option<WorkspaceId>,
176 _: &mut ViewContext<Self>,
177 ) -> Option<View<Self>>
178 where
179 Self: Sized,
180 {
181 None
182 }
183 fn is_dirty(&self, _: &AppContext) -> bool {
184 false
185 }
186 fn has_conflict(&self, _: &AppContext) -> bool {
187 false
188 }
189 fn can_save(&self, _cx: &AppContext) -> bool {
190 false
191 }
192 fn save(
193 &mut self,
194 _format: bool,
195 _project: Model<Project>,
196 _cx: &mut ViewContext<Self>,
197 ) -> Task<Result<()>> {
198 unimplemented!("save() must be implemented if can_save() returns true")
199 }
200 fn save_as(
201 &mut self,
202 _project: Model<Project>,
203 _path: ProjectPath,
204 _cx: &mut ViewContext<Self>,
205 ) -> Task<Result<()>> {
206 unimplemented!("save_as() must be implemented if can_save() returns true")
207 }
208 fn reload(
209 &mut self,
210 _project: Model<Project>,
211 _cx: &mut ViewContext<Self>,
212 ) -> Task<Result<()>> {
213 unimplemented!("reload() must be implemented if can_save() returns true")
214 }
215
216 fn act_as_type<'a>(
217 &'a self,
218 type_id: TypeId,
219 self_handle: &'a View<Self>,
220 _: &'a AppContext,
221 ) -> Option<AnyView> {
222 if TypeId::of::<Self>() == type_id {
223 Some(self_handle.clone().into())
224 } else {
225 None
226 }
227 }
228
229 fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
230 None
231 }
232
233 fn breadcrumb_location(&self) -> ToolbarItemLocation {
234 ToolbarItemLocation::Hidden
235 }
236
237 fn breadcrumbs(&self, _theme: &Theme, _cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
238 None
239 }
240
241 fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
242
243 fn serialized_item_kind() -> Option<&'static str> {
244 None
245 }
246
247 fn deserialize(
248 _project: Model<Project>,
249 _workspace: WeakView<Workspace>,
250 _workspace_id: WorkspaceId,
251 _item_id: ItemId,
252 _cx: &mut ViewContext<Pane>,
253 ) -> Task<Result<View<Self>>> {
254 unimplemented!(
255 "deserialize() must be implemented if serialized_item_kind() returns Some(_)"
256 )
257 }
258 fn show_toolbar(&self) -> bool {
259 true
260 }
261 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Point<Pixels>> {
262 None
263 }
264}
265
266pub trait ItemHandle: 'static + Send {
267 fn subscribe_to_item_events(
268 &self,
269 cx: &mut WindowContext,
270 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
271 ) -> gpui::Subscription;
272 fn focus_handle(&self, cx: &WindowContext) -> FocusHandle;
273 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>;
274 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>;
275 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement;
276 fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str>;
277 fn dragged_tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement;
278 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
279 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
280 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]>;
281 fn for_each_project_item(
282 &self,
283 _: &AppContext,
284 _: &mut dyn FnMut(EntityId, &dyn project::Item),
285 );
286 fn is_singleton(&self, cx: &AppContext) -> bool;
287 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
288 fn clone_on_split(
289 &self,
290 workspace_id: Option<WorkspaceId>,
291 cx: &mut WindowContext,
292 ) -> Option<Box<dyn ItemHandle>>;
293 fn added_to_pane(
294 &self,
295 workspace: &mut Workspace,
296 pane: View<Pane>,
297 cx: &mut ViewContext<Workspace>,
298 );
299 fn deactivated(&self, cx: &mut WindowContext);
300 fn workspace_deactivated(&self, cx: &mut WindowContext);
301 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
302 fn item_id(&self) -> EntityId;
303 fn to_any(&self) -> AnyView;
304 fn is_dirty(&self, cx: &AppContext) -> bool;
305 fn has_conflict(&self, cx: &AppContext) -> bool;
306 fn can_save(&self, cx: &AppContext) -> bool;
307 fn save(
308 &self,
309 format: bool,
310 project: Model<Project>,
311 cx: &mut WindowContext,
312 ) -> Task<Result<()>>;
313 fn save_as(
314 &self,
315 project: Model<Project>,
316 path: ProjectPath,
317 cx: &mut WindowContext,
318 ) -> Task<Result<()>>;
319 fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
320 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyView>;
321 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
322 fn on_release(
323 &self,
324 cx: &mut AppContext,
325 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
326 ) -> gpui::Subscription;
327 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
328 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
329 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
330 fn serialized_item_kind(&self) -> Option<&'static str>;
331 fn show_toolbar(&self, cx: &AppContext) -> bool;
332 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>>;
333 fn downgrade_item(&self) -> Box<dyn WeakItemHandle>;
334 fn workspace_settings<'a>(&self, cx: &'a AppContext) -> &'a WorkspaceSettings;
335}
336
337pub trait WeakItemHandle: Send + Sync {
338 fn id(&self) -> EntityId;
339 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
340}
341
342impl dyn ItemHandle {
343 pub fn downcast<V: 'static>(&self) -> Option<View<V>> {
344 self.to_any().downcast().ok()
345 }
346
347 pub fn act_as<V: 'static>(&self, cx: &AppContext) -> Option<View<V>> {
348 self.act_as_type(TypeId::of::<V>(), cx)
349 .and_then(|t| t.downcast().ok())
350 }
351}
352
353impl<T: Item> ItemHandle for View<T> {
354 fn subscribe_to_item_events(
355 &self,
356 cx: &mut WindowContext,
357 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
358 ) -> gpui::Subscription {
359 cx.subscribe(self, move |_, event, cx| {
360 T::to_item_events(event, |item_event| handler(item_event, cx));
361 })
362 }
363
364 fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
365 self.focus_handle(cx)
366 }
367
368 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
369 self.read(cx).tab_tooltip_text(cx)
370 }
371
372 fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str> {
373 self.read(cx).telemetry_event_text()
374 }
375
376 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
377 self.read(cx).tab_description(detail, cx)
378 }
379
380 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
381 self.read(cx).tab_content(params, cx)
382 }
383
384 fn dragged_tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
385 self.read(cx).tab_content(
386 TabContentParams {
387 selected: true,
388 ..params
389 },
390 cx,
391 )
392 }
393
394 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
395 let this = self.read(cx);
396 let mut result = None;
397 if this.is_singleton(cx) {
398 this.for_each_project_item(cx, &mut |_, item| {
399 result = item.project_path(cx);
400 });
401 }
402 result
403 }
404
405 fn workspace_settings<'a>(&self, cx: &'a AppContext) -> &'a WorkspaceSettings {
406 if let Some(project_path) = self.project_path(cx) {
407 WorkspaceSettings::get(
408 Some(SettingsLocation {
409 worktree_id: project_path.worktree_id.into(),
410 path: &project_path.path,
411 }),
412 cx,
413 )
414 } else {
415 WorkspaceSettings::get_global(cx)
416 }
417 }
418
419 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
420 let mut result = SmallVec::new();
421 self.read(cx).for_each_project_item(cx, &mut |_, item| {
422 if let Some(id) = item.entry_id(cx) {
423 result.push(id);
424 }
425 });
426 result
427 }
428
429 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]> {
430 let mut result = SmallVec::new();
431 self.read(cx).for_each_project_item(cx, &mut |id, _| {
432 result.push(id);
433 });
434 result
435 }
436
437 fn for_each_project_item(
438 &self,
439 cx: &AppContext,
440 f: &mut dyn FnMut(EntityId, &dyn project::Item),
441 ) {
442 self.read(cx).for_each_project_item(cx, f)
443 }
444
445 fn is_singleton(&self, cx: &AppContext) -> bool {
446 self.read(cx).is_singleton(cx)
447 }
448
449 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
450 Box::new(self.clone())
451 }
452
453 fn clone_on_split(
454 &self,
455 workspace_id: Option<WorkspaceId>,
456 cx: &mut WindowContext,
457 ) -> Option<Box<dyn ItemHandle>> {
458 self.update(cx, |item, cx| item.clone_on_split(workspace_id, cx))
459 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
460 }
461
462 fn added_to_pane(
463 &self,
464 workspace: &mut Workspace,
465 pane: View<Pane>,
466 cx: &mut ViewContext<Workspace>,
467 ) {
468 let weak_item = self.downgrade();
469 let history = pane.read(cx).nav_history_for_item(self);
470 self.update(cx, |this, cx| {
471 this.set_nav_history(history, cx);
472 this.added_to_workspace(workspace, cx);
473 });
474
475 if let Some(followed_item) = self.to_followable_item_handle(cx) {
476 if let Some(message) = followed_item.to_state_proto(cx) {
477 workspace.update_followers(
478 followed_item.is_project_item(cx),
479 proto::update_followers::Variant::CreateView(proto::View {
480 id: followed_item
481 .remote_id(&workspace.client(), cx)
482 .map(|id| id.to_proto()),
483 variant: Some(message),
484 leader_id: workspace.leader_for_pane(&pane),
485 }),
486 cx,
487 );
488 }
489 }
490
491 if workspace
492 .panes_by_item
493 .insert(self.item_id(), pane.downgrade())
494 .is_none()
495 {
496 let mut pending_autosave = DelayedDebouncedEditAction::new();
497 let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
498 let pending_update = Rc::new(RefCell::new(None));
499
500 let mut send_follower_updates = None;
501 if let Some(item) = self.to_followable_item_handle(cx) {
502 let is_project_item = item.is_project_item(cx);
503 let item = item.downgrade();
504
505 send_follower_updates = Some(cx.spawn({
506 let pending_update = pending_update.clone();
507 |workspace, mut cx| async move {
508 while let Some(mut leader_id) = pending_update_rx.next().await {
509 while let Ok(Some(id)) = pending_update_rx.try_next() {
510 leader_id = id;
511 }
512
513 workspace.update(&mut cx, |workspace, cx| {
514 let Some(item) = item.upgrade() else { return };
515 workspace.update_followers(
516 is_project_item,
517 proto::update_followers::Variant::UpdateView(
518 proto::UpdateView {
519 id: item
520 .remote_id(workspace.client(), cx)
521 .map(|id| id.to_proto()),
522 variant: pending_update.borrow_mut().take(),
523 leader_id,
524 },
525 ),
526 cx,
527 );
528 })?;
529 cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
530 }
531 anyhow::Ok(())
532 }
533 }));
534 }
535
536 let mut event_subscription = Some(cx.subscribe(
537 self,
538 move |workspace, item: View<T>, event, cx| {
539 let pane = if let Some(pane) = workspace
540 .panes_by_item
541 .get(&item.item_id())
542 .and_then(|pane| pane.upgrade())
543 {
544 pane
545 } else {
546 return;
547 };
548
549 if let Some(item) = item.to_followable_item_handle(cx) {
550 let leader_id = workspace.leader_for_pane(&pane);
551 let follow_event = item.to_follow_event(event);
552 if leader_id.is_some()
553 && matches!(follow_event, Some(FollowEvent::Unfollow))
554 {
555 workspace.unfollow(&pane, cx);
556 }
557
558 if item.focus_handle(cx).contains_focused(cx) {
559 item.add_event_to_update_proto(
560 event,
561 &mut pending_update.borrow_mut(),
562 cx,
563 );
564 pending_update_tx.unbounded_send(leader_id).ok();
565 }
566 }
567
568 T::to_item_events(event, |event| match event {
569 ItemEvent::CloseItem => {
570 pane.update(cx, |pane, cx| {
571 pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
572 })
573 .detach_and_log_err(cx);
574 return;
575 }
576
577 ItemEvent::UpdateTab => {
578 pane.update(cx, |_, cx| {
579 cx.emit(pane::Event::ChangeItemTitle);
580 cx.notify();
581 });
582 }
583
584 ItemEvent::Edit => {
585 let autosave = item.workspace_settings(cx).autosave;
586
587 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
588 let delay = Duration::from_millis(milliseconds);
589 let item = item.clone();
590 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
591 Pane::autosave_item(&item, workspace.project().clone(), cx)
592 });
593 }
594 pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
595 }
596
597 _ => {}
598 });
599 },
600 ));
601
602 cx.on_blur(&self.focus_handle(cx), move |workspace, cx| {
603 if let Some(item) = weak_item.upgrade() {
604 if item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange {
605 Pane::autosave_item(&item, workspace.project.clone(), cx)
606 .detach_and_log_err(cx);
607 }
608 }
609 })
610 .detach();
611
612 let item_id = self.item_id();
613 cx.observe_release(self, move |workspace, _, _| {
614 workspace.panes_by_item.remove(&item_id);
615 event_subscription.take();
616 send_follower_updates.take();
617 })
618 .detach();
619 }
620
621 cx.defer(|workspace, cx| {
622 workspace.serialize_workspace(cx);
623 });
624 }
625
626 fn deactivated(&self, cx: &mut WindowContext) {
627 self.update(cx, |this, cx| this.deactivated(cx));
628 }
629
630 fn workspace_deactivated(&self, cx: &mut WindowContext) {
631 self.update(cx, |this, cx| this.workspace_deactivated(cx));
632 }
633
634 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
635 self.update(cx, |this, cx| this.navigate(data, cx))
636 }
637
638 fn item_id(&self) -> EntityId {
639 self.entity_id()
640 }
641
642 fn to_any(&self) -> AnyView {
643 self.clone().into()
644 }
645
646 fn is_dirty(&self, cx: &AppContext) -> bool {
647 self.read(cx).is_dirty(cx)
648 }
649
650 fn has_conflict(&self, cx: &AppContext) -> bool {
651 self.read(cx).has_conflict(cx)
652 }
653
654 fn can_save(&self, cx: &AppContext) -> bool {
655 self.read(cx).can_save(cx)
656 }
657
658 fn save(
659 &self,
660 format: bool,
661 project: Model<Project>,
662 cx: &mut WindowContext,
663 ) -> Task<Result<()>> {
664 self.update(cx, |item, cx| item.save(format, project, cx))
665 }
666
667 fn save_as(
668 &self,
669 project: Model<Project>,
670 path: ProjectPath,
671 cx: &mut WindowContext,
672 ) -> Task<anyhow::Result<()>> {
673 self.update(cx, |item, cx| item.save_as(project, path, cx))
674 }
675
676 fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
677 self.update(cx, |item, cx| item.reload(project, cx))
678 }
679
680 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
681 self.read(cx).act_as_type(type_id, self, cx)
682 }
683
684 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
685 let builders = cx.try_global::<FollowableItemBuilders>()?;
686 let item = self.to_any();
687 Some(builders.get(&item.entity_type())?.1(&item))
688 }
689
690 fn on_release(
691 &self,
692 cx: &mut AppContext,
693 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
694 ) -> gpui::Subscription {
695 cx.observe_release(self, move |_, cx| callback(cx))
696 }
697
698 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
699 self.read(cx).as_searchable(self)
700 }
701
702 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
703 self.read(cx).breadcrumb_location()
704 }
705
706 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
707 self.read(cx).breadcrumbs(theme, cx)
708 }
709
710 fn serialized_item_kind(&self) -> Option<&'static str> {
711 T::serialized_item_kind()
712 }
713
714 fn show_toolbar(&self, cx: &AppContext) -> bool {
715 self.read(cx).show_toolbar()
716 }
717
718 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
719 self.read(cx).pixel_position_of_cursor(cx)
720 }
721
722 fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
723 Box::new(self.downgrade())
724 }
725}
726
727impl From<Box<dyn ItemHandle>> for AnyView {
728 fn from(val: Box<dyn ItemHandle>) -> Self {
729 val.to_any()
730 }
731}
732
733impl From<&Box<dyn ItemHandle>> for AnyView {
734 fn from(val: &Box<dyn ItemHandle>) -> Self {
735 val.to_any()
736 }
737}
738
739impl Clone for Box<dyn ItemHandle> {
740 fn clone(&self) -> Box<dyn ItemHandle> {
741 self.boxed_clone()
742 }
743}
744
745impl<T: Item> WeakItemHandle for WeakView<T> {
746 fn id(&self) -> EntityId {
747 self.entity_id()
748 }
749
750 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
751 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
752 }
753}
754
755pub trait ProjectItem: Item {
756 type Item: project::Item;
757
758 fn for_project_item(
759 project: Model<Project>,
760 item: Model<Self::Item>,
761 cx: &mut ViewContext<Self>,
762 ) -> Self
763 where
764 Self: Sized;
765}
766
767#[derive(Debug)]
768pub enum FollowEvent {
769 Unfollow,
770}
771
772pub trait FollowableItem: Item {
773 fn remote_id(&self) -> Option<ViewId>;
774 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
775 fn from_state_proto(
776 pane: View<Pane>,
777 project: View<Workspace>,
778 id: ViewId,
779 state: &mut Option<proto::view::Variant>,
780 cx: &mut WindowContext,
781 ) -> Option<Task<Result<View<Self>>>>;
782 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
783 fn add_event_to_update_proto(
784 &self,
785 event: &Self::Event,
786 update: &mut Option<proto::update_view::Variant>,
787 cx: &WindowContext,
788 ) -> bool;
789 fn apply_update_proto(
790 &mut self,
791 project: &Model<Project>,
792 message: proto::update_view::Variant,
793 cx: &mut ViewContext<Self>,
794 ) -> Task<Result<()>>;
795 fn is_project_item(&self, cx: &WindowContext) -> bool;
796 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
797}
798
799pub trait FollowableItemHandle: ItemHandle {
800 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
801 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
802 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
803 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
804 fn add_event_to_update_proto(
805 &self,
806 event: &dyn Any,
807 update: &mut Option<proto::update_view::Variant>,
808 cx: &WindowContext,
809 ) -> bool;
810 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
811 fn apply_update_proto(
812 &self,
813 project: &Model<Project>,
814 message: proto::update_view::Variant,
815 cx: &mut WindowContext,
816 ) -> Task<Result<()>>;
817 fn is_project_item(&self, cx: &WindowContext) -> bool;
818}
819
820impl<T: FollowableItem> FollowableItemHandle for View<T> {
821 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
822 self.read(cx).remote_id().or_else(|| {
823 client.peer_id().map(|creator| ViewId {
824 creator,
825 id: self.item_id().as_u64(),
826 })
827 })
828 }
829
830 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
831 Box::new(self.downgrade())
832 }
833
834 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
835 self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
836 }
837
838 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
839 self.read(cx).to_state_proto(cx)
840 }
841
842 fn add_event_to_update_proto(
843 &self,
844 event: &dyn Any,
845 update: &mut Option<proto::update_view::Variant>,
846 cx: &WindowContext,
847 ) -> bool {
848 if let Some(event) = event.downcast_ref() {
849 self.read(cx).add_event_to_update_proto(event, update, cx)
850 } else {
851 false
852 }
853 }
854
855 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
856 T::to_follow_event(event.downcast_ref()?)
857 }
858
859 fn apply_update_proto(
860 &self,
861 project: &Model<Project>,
862 message: proto::update_view::Variant,
863 cx: &mut WindowContext,
864 ) -> Task<Result<()>> {
865 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
866 }
867
868 fn is_project_item(&self, cx: &WindowContext) -> bool {
869 self.read(cx).is_project_item(cx)
870 }
871}
872
873pub trait WeakFollowableItemHandle: Send + Sync {
874 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
875}
876
877impl<T: FollowableItem> WeakFollowableItemHandle for WeakView<T> {
878 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
879 Some(Box::new(self.upgrade()?))
880 }
881}
882
883#[cfg(any(test, feature = "test-support"))]
884pub mod test {
885 use super::{Item, ItemEvent, TabContentParams};
886 use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
887 use gpui::{
888 AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
889 InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
890 VisualContext, WeakView,
891 };
892 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
893 use std::{any::Any, cell::Cell, path::Path};
894
895 pub struct TestProjectItem {
896 pub entry_id: Option<ProjectEntryId>,
897 pub project_path: Option<ProjectPath>,
898 }
899
900 pub struct TestItem {
901 pub workspace_id: Option<WorkspaceId>,
902 pub state: String,
903 pub label: String,
904 pub save_count: usize,
905 pub save_as_count: usize,
906 pub reload_count: usize,
907 pub is_dirty: bool,
908 pub is_singleton: bool,
909 pub has_conflict: bool,
910 pub project_items: Vec<Model<TestProjectItem>>,
911 pub nav_history: Option<ItemNavHistory>,
912 pub tab_descriptions: Option<Vec<&'static str>>,
913 pub tab_detail: Cell<Option<usize>>,
914 focus_handle: gpui::FocusHandle,
915 }
916
917 impl project::Item for TestProjectItem {
918 fn try_open(
919 _project: &Model<Project>,
920 _path: &ProjectPath,
921 _cx: &mut AppContext,
922 ) -> Option<Task<gpui::Result<Model<Self>>>> {
923 None
924 }
925
926 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
927 self.entry_id
928 }
929
930 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
931 self.project_path.clone()
932 }
933 }
934
935 pub enum TestItemEvent {
936 Edit,
937 }
938
939 impl TestProjectItem {
940 pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
941 let entry_id = Some(ProjectEntryId::from_proto(id));
942 let project_path = Some(ProjectPath {
943 worktree_id: WorktreeId::from_usize(0),
944 path: Path::new(path).into(),
945 });
946 cx.new_model(|_| Self {
947 entry_id,
948 project_path,
949 })
950 }
951
952 pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
953 cx.new_model(|_| Self {
954 project_path: None,
955 entry_id: None,
956 })
957 }
958 }
959
960 impl TestItem {
961 pub fn new(cx: &mut ViewContext<Self>) -> Self {
962 Self {
963 state: String::new(),
964 label: String::new(),
965 save_count: 0,
966 save_as_count: 0,
967 reload_count: 0,
968 is_dirty: false,
969 has_conflict: false,
970 project_items: Vec::new(),
971 is_singleton: true,
972 nav_history: None,
973 tab_descriptions: None,
974 tab_detail: Default::default(),
975 workspace_id: Default::default(),
976 focus_handle: cx.focus_handle(),
977 }
978 }
979
980 pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
981 let mut this = Self::new(cx);
982 this.workspace_id = Some(id);
983 this
984 }
985
986 pub fn with_label(mut self, state: &str) -> Self {
987 self.label = state.to_string();
988 self
989 }
990
991 pub fn with_singleton(mut self, singleton: bool) -> Self {
992 self.is_singleton = singleton;
993 self
994 }
995
996 pub fn with_dirty(mut self, dirty: bool) -> Self {
997 self.is_dirty = dirty;
998 self
999 }
1000
1001 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
1002 self.has_conflict = has_conflict;
1003 self
1004 }
1005
1006 pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
1007 self.project_items.clear();
1008 self.project_items.extend(items.iter().cloned());
1009 self
1010 }
1011
1012 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
1013 self.push_to_nav_history(cx);
1014 self.state = state;
1015 }
1016
1017 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
1018 if let Some(history) = &mut self.nav_history {
1019 history.push(Some(Box::new(self.state.clone())), cx);
1020 }
1021 }
1022 }
1023
1024 impl Render for TestItem {
1025 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1026 gpui::div().track_focus(&self.focus_handle)
1027 }
1028 }
1029
1030 impl EventEmitter<ItemEvent> for TestItem {}
1031
1032 impl FocusableView for TestItem {
1033 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
1034 self.focus_handle.clone()
1035 }
1036 }
1037
1038 impl Item for TestItem {
1039 type Event = ItemEvent;
1040
1041 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1042 f(*event)
1043 }
1044
1045 fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
1046 self.tab_descriptions.as_ref().and_then(|descriptions| {
1047 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1048 Some(description.into())
1049 })
1050 }
1051
1052 fn telemetry_event_text(&self) -> Option<&'static str> {
1053 None
1054 }
1055
1056 fn tab_content(
1057 &self,
1058 params: TabContentParams,
1059 _cx: &ui::prelude::WindowContext,
1060 ) -> AnyElement {
1061 self.tab_detail.set(params.detail);
1062 gpui::div().into_any_element()
1063 }
1064
1065 fn for_each_project_item(
1066 &self,
1067 cx: &AppContext,
1068 f: &mut dyn FnMut(EntityId, &dyn project::Item),
1069 ) {
1070 self.project_items
1071 .iter()
1072 .for_each(|item| f(item.entity_id(), item.read(cx)))
1073 }
1074
1075 fn is_singleton(&self, _: &AppContext) -> bool {
1076 self.is_singleton
1077 }
1078
1079 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
1080 self.nav_history = Some(history);
1081 }
1082
1083 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
1084 let state = *state.downcast::<String>().unwrap_or_default();
1085 if state != self.state {
1086 self.state = state;
1087 true
1088 } else {
1089 false
1090 }
1091 }
1092
1093 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
1094 self.push_to_nav_history(cx);
1095 }
1096
1097 fn clone_on_split(
1098 &self,
1099 _workspace_id: Option<WorkspaceId>,
1100 cx: &mut ViewContext<Self>,
1101 ) -> Option<View<Self>>
1102 where
1103 Self: Sized,
1104 {
1105 Some(cx.new_view(|cx| Self {
1106 state: self.state.clone(),
1107 label: self.label.clone(),
1108 save_count: self.save_count,
1109 save_as_count: self.save_as_count,
1110 reload_count: self.reload_count,
1111 is_dirty: self.is_dirty,
1112 is_singleton: self.is_singleton,
1113 has_conflict: self.has_conflict,
1114 project_items: self.project_items.clone(),
1115 nav_history: None,
1116 tab_descriptions: None,
1117 tab_detail: Default::default(),
1118 workspace_id: self.workspace_id,
1119 focus_handle: cx.focus_handle(),
1120 }))
1121 }
1122
1123 fn is_dirty(&self, _: &AppContext) -> bool {
1124 self.is_dirty
1125 }
1126
1127 fn has_conflict(&self, _: &AppContext) -> bool {
1128 self.has_conflict
1129 }
1130
1131 fn can_save(&self, cx: &AppContext) -> bool {
1132 !self.project_items.is_empty()
1133 && self
1134 .project_items
1135 .iter()
1136 .all(|item| item.read(cx).entry_id.is_some())
1137 }
1138
1139 fn save(
1140 &mut self,
1141 _: bool,
1142 _: Model<Project>,
1143 _: &mut ViewContext<Self>,
1144 ) -> Task<anyhow::Result<()>> {
1145 self.save_count += 1;
1146 self.is_dirty = false;
1147 Task::ready(Ok(()))
1148 }
1149
1150 fn save_as(
1151 &mut self,
1152 _: Model<Project>,
1153 _: ProjectPath,
1154 _: &mut ViewContext<Self>,
1155 ) -> Task<anyhow::Result<()>> {
1156 self.save_as_count += 1;
1157 self.is_dirty = false;
1158 Task::ready(Ok(()))
1159 }
1160
1161 fn reload(
1162 &mut self,
1163 _: Model<Project>,
1164 _: &mut ViewContext<Self>,
1165 ) -> Task<anyhow::Result<()>> {
1166 self.reload_count += 1;
1167 self.is_dirty = false;
1168 Task::ready(Ok(()))
1169 }
1170
1171 fn serialized_item_kind() -> Option<&'static str> {
1172 Some("TestItem")
1173 }
1174
1175 fn deserialize(
1176 _project: Model<Project>,
1177 _workspace: WeakView<Workspace>,
1178 workspace_id: WorkspaceId,
1179 _item_id: ItemId,
1180 cx: &mut ViewContext<Pane>,
1181 ) -> Task<anyhow::Result<View<Self>>> {
1182 let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1183 Task::Ready(Some(anyhow::Ok(view)))
1184 }
1185 }
1186}