1use crate::{
2 pane::{self, Pane},
3 persistence::model::ItemId,
4 searchable::SearchableItemHandle,
5 workspace_settings::{AutosaveSetting, WorkspaceSettings},
6 DelayedDebouncedEditAction, FollowableViewRegistry, 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 workspace
476 .panes_by_item
477 .insert(self.item_id(), pane.downgrade())
478 .is_none()
479 {
480 let mut pending_autosave = DelayedDebouncedEditAction::new();
481 let (pending_update_tx, mut pending_update_rx) = mpsc::unbounded();
482 let pending_update = Rc::new(RefCell::new(None));
483
484 let mut send_follower_updates = None;
485 if let Some(item) = self.to_followable_item_handle(cx) {
486 let is_project_item = item.is_project_item(cx);
487 let item = item.downgrade();
488
489 send_follower_updates = Some(cx.spawn({
490 let pending_update = pending_update.clone();
491 |workspace, mut cx| async move {
492 while let Some(mut leader_id) = pending_update_rx.next().await {
493 while let Ok(Some(id)) = pending_update_rx.try_next() {
494 leader_id = id;
495 }
496
497 workspace.update(&mut cx, |workspace, cx| {
498 let Some(item) = item.upgrade() else { return };
499 workspace.update_followers(
500 is_project_item,
501 proto::update_followers::Variant::UpdateView(
502 proto::UpdateView {
503 id: item
504 .remote_id(workspace.client(), cx)
505 .map(|id| id.to_proto()),
506 variant: pending_update.borrow_mut().take(),
507 leader_id,
508 },
509 ),
510 cx,
511 );
512 })?;
513 cx.background_executor().timer(LEADER_UPDATE_THROTTLE).await;
514 }
515 anyhow::Ok(())
516 }
517 }));
518 }
519
520 let mut event_subscription = Some(cx.subscribe(
521 self,
522 move |workspace, item: View<T>, event, cx| {
523 let pane = if let Some(pane) = workspace
524 .panes_by_item
525 .get(&item.item_id())
526 .and_then(|pane| pane.upgrade())
527 {
528 pane
529 } else {
530 return;
531 };
532
533 if let Some(item) = item.to_followable_item_handle(cx) {
534 let leader_id = workspace.leader_for_pane(&pane);
535
536 if let Some(leader_id) = leader_id {
537 if let Some(FollowEvent::Unfollow) = item.to_follow_event(event) {
538 workspace.unfollow(leader_id, cx);
539 }
540 }
541
542 if item.focus_handle(cx).contains_focused(cx) {
543 item.add_event_to_update_proto(
544 event,
545 &mut pending_update.borrow_mut(),
546 cx,
547 );
548 pending_update_tx.unbounded_send(leader_id).ok();
549 }
550 }
551
552 T::to_item_events(event, |event| match event {
553 ItemEvent::CloseItem => {
554 pane.update(cx, |pane, cx| {
555 pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
556 })
557 .detach_and_log_err(cx);
558 return;
559 }
560
561 ItemEvent::UpdateTab => {
562 pane.update(cx, |_, cx| {
563 cx.emit(pane::Event::ChangeItemTitle);
564 cx.notify();
565 });
566 }
567
568 ItemEvent::Edit => {
569 let autosave = item.workspace_settings(cx).autosave;
570
571 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
572 let delay = Duration::from_millis(milliseconds);
573 let item = item.clone();
574 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
575 Pane::autosave_item(&item, workspace.project().clone(), cx)
576 });
577 }
578 pane.update(cx, |pane, cx| pane.handle_item_edit(item.item_id(), cx));
579 }
580
581 _ => {}
582 });
583 },
584 ));
585
586 cx.on_blur(&self.focus_handle(cx), move |workspace, cx| {
587 if let Some(item) = weak_item.upgrade() {
588 if item.workspace_settings(cx).autosave == AutosaveSetting::OnFocusChange {
589 Pane::autosave_item(&item, workspace.project.clone(), cx)
590 .detach_and_log_err(cx);
591 }
592 }
593 })
594 .detach();
595
596 let item_id = self.item_id();
597 cx.observe_release(self, move |workspace, _, _| {
598 workspace.panes_by_item.remove(&item_id);
599 event_subscription.take();
600 send_follower_updates.take();
601 })
602 .detach();
603 }
604
605 cx.defer(|workspace, cx| {
606 workspace.serialize_workspace(cx);
607 });
608 }
609
610 fn deactivated(&self, cx: &mut WindowContext) {
611 self.update(cx, |this, cx| this.deactivated(cx));
612 }
613
614 fn workspace_deactivated(&self, cx: &mut WindowContext) {
615 self.update(cx, |this, cx| this.workspace_deactivated(cx));
616 }
617
618 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
619 self.update(cx, |this, cx| this.navigate(data, cx))
620 }
621
622 fn item_id(&self) -> EntityId {
623 self.entity_id()
624 }
625
626 fn to_any(&self) -> AnyView {
627 self.clone().into()
628 }
629
630 fn is_dirty(&self, cx: &AppContext) -> bool {
631 self.read(cx).is_dirty(cx)
632 }
633
634 fn has_conflict(&self, cx: &AppContext) -> bool {
635 self.read(cx).has_conflict(cx)
636 }
637
638 fn can_save(&self, cx: &AppContext) -> bool {
639 self.read(cx).can_save(cx)
640 }
641
642 fn save(
643 &self,
644 format: bool,
645 project: Model<Project>,
646 cx: &mut WindowContext,
647 ) -> Task<Result<()>> {
648 self.update(cx, |item, cx| item.save(format, project, cx))
649 }
650
651 fn save_as(
652 &self,
653 project: Model<Project>,
654 path: ProjectPath,
655 cx: &mut WindowContext,
656 ) -> Task<anyhow::Result<()>> {
657 self.update(cx, |item, cx| item.save_as(project, path, cx))
658 }
659
660 fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
661 self.update(cx, |item, cx| item.reload(project, cx))
662 }
663
664 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
665 self.read(cx).act_as_type(type_id, self, cx)
666 }
667
668 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
669 FollowableViewRegistry::to_followable_view(self.clone(), cx)
670 }
671
672 fn on_release(
673 &self,
674 cx: &mut AppContext,
675 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
676 ) -> gpui::Subscription {
677 cx.observe_release(self, move |_, cx| callback(cx))
678 }
679
680 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
681 self.read(cx).as_searchable(self)
682 }
683
684 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
685 self.read(cx).breadcrumb_location()
686 }
687
688 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
689 self.read(cx).breadcrumbs(theme, cx)
690 }
691
692 fn serialized_item_kind(&self) -> Option<&'static str> {
693 T::serialized_item_kind()
694 }
695
696 fn show_toolbar(&self, cx: &AppContext) -> bool {
697 self.read(cx).show_toolbar()
698 }
699
700 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
701 self.read(cx).pixel_position_of_cursor(cx)
702 }
703
704 fn downgrade_item(&self) -> Box<dyn WeakItemHandle> {
705 Box::new(self.downgrade())
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 From<&Box<dyn ItemHandle>> for AnyView {
716 fn from(val: &Box<dyn ItemHandle>) -> Self {
717 val.to_any()
718 }
719}
720
721impl Clone for Box<dyn ItemHandle> {
722 fn clone(&self) -> Box<dyn ItemHandle> {
723 self.boxed_clone()
724 }
725}
726
727impl<T: Item> WeakItemHandle for WeakView<T> {
728 fn id(&self) -> EntityId {
729 self.entity_id()
730 }
731
732 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
733 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
734 }
735}
736
737pub trait ProjectItem: Item {
738 type Item: project::Item;
739
740 fn for_project_item(
741 project: Model<Project>,
742 item: Model<Self::Item>,
743 cx: &mut ViewContext<Self>,
744 ) -> Self
745 where
746 Self: Sized;
747}
748
749#[derive(Debug)]
750pub enum FollowEvent {
751 Unfollow,
752}
753
754pub enum Dedup {
755 KeepExisting,
756 ReplaceExisting,
757}
758
759pub trait FollowableItem: Item {
760 fn remote_id(&self) -> Option<ViewId>;
761 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
762 fn from_state_proto(
763 project: View<Workspace>,
764 id: ViewId,
765 state: &mut Option<proto::view::Variant>,
766 cx: &mut WindowContext,
767 ) -> Option<Task<Result<View<Self>>>>;
768 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
769 fn add_event_to_update_proto(
770 &self,
771 event: &Self::Event,
772 update: &mut Option<proto::update_view::Variant>,
773 cx: &WindowContext,
774 ) -> bool;
775 fn apply_update_proto(
776 &mut self,
777 project: &Model<Project>,
778 message: proto::update_view::Variant,
779 cx: &mut ViewContext<Self>,
780 ) -> Task<Result<()>>;
781 fn is_project_item(&self, cx: &WindowContext) -> bool;
782 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
783 fn dedup(&self, existing: &Self, cx: &WindowContext) -> Option<Dedup>;
784}
785
786pub trait FollowableItemHandle: ItemHandle {
787 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
788 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
789 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
790 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
791 fn add_event_to_update_proto(
792 &self,
793 event: &dyn Any,
794 update: &mut Option<proto::update_view::Variant>,
795 cx: &WindowContext,
796 ) -> bool;
797 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
798 fn apply_update_proto(
799 &self,
800 project: &Model<Project>,
801 message: proto::update_view::Variant,
802 cx: &mut WindowContext,
803 ) -> Task<Result<()>>;
804 fn is_project_item(&self, cx: &WindowContext) -> bool;
805 fn dedup(&self, existing: &dyn FollowableItemHandle, cx: &WindowContext) -> Option<Dedup>;
806}
807
808impl<T: FollowableItem> FollowableItemHandle for View<T> {
809 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
810 self.read(cx).remote_id().or_else(|| {
811 client.peer_id().map(|creator| ViewId {
812 creator,
813 id: self.item_id().as_u64(),
814 })
815 })
816 }
817
818 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
819 Box::new(self.downgrade())
820 }
821
822 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
823 self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
824 }
825
826 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
827 self.read(cx).to_state_proto(cx)
828 }
829
830 fn add_event_to_update_proto(
831 &self,
832 event: &dyn Any,
833 update: &mut Option<proto::update_view::Variant>,
834 cx: &WindowContext,
835 ) -> bool {
836 if let Some(event) = event.downcast_ref() {
837 self.read(cx).add_event_to_update_proto(event, update, cx)
838 } else {
839 false
840 }
841 }
842
843 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
844 T::to_follow_event(event.downcast_ref()?)
845 }
846
847 fn apply_update_proto(
848 &self,
849 project: &Model<Project>,
850 message: proto::update_view::Variant,
851 cx: &mut WindowContext,
852 ) -> Task<Result<()>> {
853 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
854 }
855
856 fn is_project_item(&self, cx: &WindowContext) -> bool {
857 self.read(cx).is_project_item(cx)
858 }
859
860 fn dedup(&self, existing: &dyn FollowableItemHandle, cx: &WindowContext) -> Option<Dedup> {
861 let existing = existing.to_any().downcast::<T>().ok()?;
862 self.read(cx).dedup(existing.read(cx), cx)
863 }
864}
865
866pub trait WeakFollowableItemHandle: Send + Sync {
867 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
868}
869
870impl<T: FollowableItem> WeakFollowableItemHandle for WeakView<T> {
871 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
872 Some(Box::new(self.upgrade()?))
873 }
874}
875
876#[cfg(any(test, feature = "test-support"))]
877pub mod test {
878 use super::{Item, ItemEvent, TabContentParams};
879 use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
880 use gpui::{
881 AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
882 InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
883 VisualContext, WeakView,
884 };
885 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
886 use std::{any::Any, cell::Cell, path::Path};
887
888 pub struct TestProjectItem {
889 pub entry_id: Option<ProjectEntryId>,
890 pub project_path: Option<ProjectPath>,
891 }
892
893 pub struct TestItem {
894 pub workspace_id: Option<WorkspaceId>,
895 pub state: String,
896 pub label: String,
897 pub save_count: usize,
898 pub save_as_count: usize,
899 pub reload_count: usize,
900 pub is_dirty: bool,
901 pub is_singleton: bool,
902 pub has_conflict: bool,
903 pub project_items: Vec<Model<TestProjectItem>>,
904 pub nav_history: Option<ItemNavHistory>,
905 pub tab_descriptions: Option<Vec<&'static str>>,
906 pub tab_detail: Cell<Option<usize>>,
907 focus_handle: gpui::FocusHandle,
908 }
909
910 impl project::Item for TestProjectItem {
911 fn try_open(
912 _project: &Model<Project>,
913 _path: &ProjectPath,
914 _cx: &mut AppContext,
915 ) -> Option<Task<gpui::Result<Model<Self>>>> {
916 None
917 }
918
919 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
920 self.entry_id
921 }
922
923 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
924 self.project_path.clone()
925 }
926 }
927
928 pub enum TestItemEvent {
929 Edit,
930 }
931
932 impl TestProjectItem {
933 pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
934 let entry_id = Some(ProjectEntryId::from_proto(id));
935 let project_path = Some(ProjectPath {
936 worktree_id: WorktreeId::from_usize(0),
937 path: Path::new(path).into(),
938 });
939 cx.new_model(|_| Self {
940 entry_id,
941 project_path,
942 })
943 }
944
945 pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
946 cx.new_model(|_| Self {
947 project_path: None,
948 entry_id: None,
949 })
950 }
951 }
952
953 impl TestItem {
954 pub fn new(cx: &mut ViewContext<Self>) -> Self {
955 Self {
956 state: String::new(),
957 label: String::new(),
958 save_count: 0,
959 save_as_count: 0,
960 reload_count: 0,
961 is_dirty: false,
962 has_conflict: false,
963 project_items: Vec::new(),
964 is_singleton: true,
965 nav_history: None,
966 tab_descriptions: None,
967 tab_detail: Default::default(),
968 workspace_id: Default::default(),
969 focus_handle: cx.focus_handle(),
970 }
971 }
972
973 pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
974 let mut this = Self::new(cx);
975 this.workspace_id = Some(id);
976 this
977 }
978
979 pub fn with_label(mut self, state: &str) -> Self {
980 self.label = state.to_string();
981 self
982 }
983
984 pub fn with_singleton(mut self, singleton: bool) -> Self {
985 self.is_singleton = singleton;
986 self
987 }
988
989 pub fn with_dirty(mut self, dirty: bool) -> Self {
990 self.is_dirty = dirty;
991 self
992 }
993
994 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
995 self.has_conflict = has_conflict;
996 self
997 }
998
999 pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
1000 self.project_items.clear();
1001 self.project_items.extend(items.iter().cloned());
1002 self
1003 }
1004
1005 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
1006 self.push_to_nav_history(cx);
1007 self.state = state;
1008 }
1009
1010 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
1011 if let Some(history) = &mut self.nav_history {
1012 history.push(Some(Box::new(self.state.clone())), cx);
1013 }
1014 }
1015 }
1016
1017 impl Render for TestItem {
1018 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1019 gpui::div().track_focus(&self.focus_handle)
1020 }
1021 }
1022
1023 impl EventEmitter<ItemEvent> for TestItem {}
1024
1025 impl FocusableView for TestItem {
1026 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
1027 self.focus_handle.clone()
1028 }
1029 }
1030
1031 impl Item for TestItem {
1032 type Event = ItemEvent;
1033
1034 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1035 f(*event)
1036 }
1037
1038 fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
1039 self.tab_descriptions.as_ref().and_then(|descriptions| {
1040 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1041 Some(description.into())
1042 })
1043 }
1044
1045 fn telemetry_event_text(&self) -> Option<&'static str> {
1046 None
1047 }
1048
1049 fn tab_content(
1050 &self,
1051 params: TabContentParams,
1052 _cx: &ui::prelude::WindowContext,
1053 ) -> AnyElement {
1054 self.tab_detail.set(params.detail);
1055 gpui::div().into_any_element()
1056 }
1057
1058 fn for_each_project_item(
1059 &self,
1060 cx: &AppContext,
1061 f: &mut dyn FnMut(EntityId, &dyn project::Item),
1062 ) {
1063 self.project_items
1064 .iter()
1065 .for_each(|item| f(item.entity_id(), item.read(cx)))
1066 }
1067
1068 fn is_singleton(&self, _: &AppContext) -> bool {
1069 self.is_singleton
1070 }
1071
1072 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
1073 self.nav_history = Some(history);
1074 }
1075
1076 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
1077 let state = *state.downcast::<String>().unwrap_or_default();
1078 if state != self.state {
1079 self.state = state;
1080 true
1081 } else {
1082 false
1083 }
1084 }
1085
1086 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
1087 self.push_to_nav_history(cx);
1088 }
1089
1090 fn clone_on_split(
1091 &self,
1092 _workspace_id: Option<WorkspaceId>,
1093 cx: &mut ViewContext<Self>,
1094 ) -> Option<View<Self>>
1095 where
1096 Self: Sized,
1097 {
1098 Some(cx.new_view(|cx| Self {
1099 state: self.state.clone(),
1100 label: self.label.clone(),
1101 save_count: self.save_count,
1102 save_as_count: self.save_as_count,
1103 reload_count: self.reload_count,
1104 is_dirty: self.is_dirty,
1105 is_singleton: self.is_singleton,
1106 has_conflict: self.has_conflict,
1107 project_items: self.project_items.clone(),
1108 nav_history: None,
1109 tab_descriptions: None,
1110 tab_detail: Default::default(),
1111 workspace_id: self.workspace_id,
1112 focus_handle: cx.focus_handle(),
1113 }))
1114 }
1115
1116 fn is_dirty(&self, _: &AppContext) -> bool {
1117 self.is_dirty
1118 }
1119
1120 fn has_conflict(&self, _: &AppContext) -> bool {
1121 self.has_conflict
1122 }
1123
1124 fn can_save(&self, cx: &AppContext) -> bool {
1125 !self.project_items.is_empty()
1126 && self
1127 .project_items
1128 .iter()
1129 .all(|item| item.read(cx).entry_id.is_some())
1130 }
1131
1132 fn save(
1133 &mut self,
1134 _: bool,
1135 _: Model<Project>,
1136 _: &mut ViewContext<Self>,
1137 ) -> Task<anyhow::Result<()>> {
1138 self.save_count += 1;
1139 self.is_dirty = false;
1140 Task::ready(Ok(()))
1141 }
1142
1143 fn save_as(
1144 &mut self,
1145 _: Model<Project>,
1146 _: ProjectPath,
1147 _: &mut ViewContext<Self>,
1148 ) -> Task<anyhow::Result<()>> {
1149 self.save_as_count += 1;
1150 self.is_dirty = false;
1151 Task::ready(Ok(()))
1152 }
1153
1154 fn reload(
1155 &mut self,
1156 _: Model<Project>,
1157 _: &mut ViewContext<Self>,
1158 ) -> Task<anyhow::Result<()>> {
1159 self.reload_count += 1;
1160 self.is_dirty = false;
1161 Task::ready(Ok(()))
1162 }
1163
1164 fn serialized_item_kind() -> Option<&'static str> {
1165 Some("TestItem")
1166 }
1167
1168 fn deserialize(
1169 _project: Model<Project>,
1170 _workspace: WeakView<Workspace>,
1171 workspace_id: WorkspaceId,
1172 _item_id: ItemId,
1173 cx: &mut ViewContext<Pane>,
1174 ) -> Task<anyhow::Result<View<Self>>> {
1175 let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1176 Task::Ready(Some(anyhow::Ok(view)))
1177 }
1178 }
1179}