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