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 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: 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 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: 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: 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}
334
335pub trait WeakItemHandle: Send + Sync {
336 fn id(&self) -> EntityId;
337 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
338}
339
340impl dyn ItemHandle {
341 pub fn downcast<V: 'static>(&self) -> Option<View<V>> {
342 self.to_any().downcast().ok()
343 }
344
345 pub fn act_as<V: 'static>(&self, cx: &AppContext) -> Option<View<V>> {
346 self.act_as_type(TypeId::of::<V>(), cx)
347 .and_then(|t| t.downcast().ok())
348 }
349}
350
351impl<T: Item> ItemHandle for View<T> {
352 fn subscribe_to_item_events(
353 &self,
354 cx: &mut WindowContext,
355 handler: Box<dyn Fn(ItemEvent, &mut WindowContext)>,
356 ) -> gpui::Subscription {
357 cx.subscribe(self, move |_, event, cx| {
358 T::to_item_events(event, |item_event| handler(item_event, cx));
359 })
360 }
361
362 fn focus_handle(&self, cx: &WindowContext) -> FocusHandle {
363 self.focus_handle(cx)
364 }
365
366 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
367 self.read(cx).tab_tooltip_text(cx)
368 }
369
370 fn telemetry_event_text(&self, cx: &WindowContext) -> Option<&'static str> {
371 self.read(cx).telemetry_event_text()
372 }
373
374 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
375 self.read(cx).tab_description(detail, cx)
376 }
377
378 fn tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
379 self.read(cx).tab_content(params, cx)
380 }
381
382 fn dragged_tab_content(&self, params: TabContentParams, cx: &WindowContext) -> AnyElement {
383 self.read(cx).tab_content(
384 TabContentParams {
385 selected: true,
386 ..params
387 },
388 cx,
389 )
390 }
391
392 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
393 let this = self.read(cx);
394 let mut result = None;
395 if this.is_singleton(cx) {
396 this.for_each_project_item(cx, &mut |_, item| {
397 result = item.project_path(cx);
398 });
399 }
400 result
401 }
402
403 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
404 let mut result = SmallVec::new();
405 self.read(cx).for_each_project_item(cx, &mut |_, item| {
406 if let Some(id) = item.entry_id(cx) {
407 result.push(id);
408 }
409 });
410 result
411 }
412
413 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[EntityId; 3]> {
414 let mut result = SmallVec::new();
415 self.read(cx).for_each_project_item(cx, &mut |id, _| {
416 result.push(id);
417 });
418 result
419 }
420
421 fn for_each_project_item(
422 &self,
423 cx: &AppContext,
424 f: &mut dyn FnMut(EntityId, &dyn project::Item),
425 ) {
426 self.read(cx).for_each_project_item(cx, f)
427 }
428
429 fn is_singleton(&self, cx: &AppContext) -> bool {
430 self.read(cx).is_singleton(cx)
431 }
432
433 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
434 Box::new(self.clone())
435 }
436
437 fn clone_on_split(
438 &self,
439 workspace_id: WorkspaceId,
440 cx: &mut WindowContext,
441 ) -> Option<Box<dyn ItemHandle>> {
442 self.update(cx, |item, cx| item.clone_on_split(workspace_id, cx))
443 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
444 }
445
446 fn added_to_pane(
447 &self,
448 workspace: &mut Workspace,
449 pane: View<Pane>,
450 cx: &mut ViewContext<Workspace>,
451 ) {
452 let weak_item = self.downgrade();
453 let history = pane.read(cx).nav_history_for_item(self);
454 self.update(cx, |this, cx| {
455 this.set_nav_history(history, cx);
456 this.added_to_workspace(workspace, cx);
457 });
458
459 if let Some(followed_item) = self.to_followable_item_handle(cx) {
460 if let Some(message) = followed_item.to_state_proto(cx) {
461 workspace.update_followers(
462 followed_item.is_project_item(cx),
463 proto::update_followers::Variant::CreateView(proto::View {
464 id: followed_item
465 .remote_id(&workspace.client(), cx)
466 .map(|id| id.to_proto()),
467 variant: Some(message),
468 leader_id: workspace.leader_for_pane(&pane),
469 }),
470 cx,
471 );
472 }
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 log::error!("unexpected item event after pane was dropped");
531 return;
532 };
533
534 if let Some(item) = item.to_followable_item_handle(cx) {
535 let leader_id = workspace.leader_for_pane(&pane);
536 let follow_event = item.to_follow_event(event);
537 if leader_id.is_some()
538 && matches!(follow_event, Some(FollowEvent::Unfollow))
539 {
540 workspace.unfollow(&pane, cx);
541 }
542
543 if item.focus_handle(cx).contains_focused(cx) {
544 item.add_event_to_update_proto(
545 event,
546 &mut pending_update.borrow_mut(),
547 cx,
548 );
549 pending_update_tx.unbounded_send(leader_id).ok();
550 }
551 }
552
553 T::to_item_events(event, |event| match event {
554 ItemEvent::CloseItem => {
555 pane.update(cx, |pane, cx| {
556 pane.close_item_by_id(item.item_id(), crate::SaveIntent::Close, cx)
557 })
558 .detach_and_log_err(cx);
559 return;
560 }
561
562 ItemEvent::UpdateTab => {
563 pane.update(cx, |_, cx| {
564 cx.emit(pane::Event::ChangeItemTitle);
565 cx.notify();
566 });
567 }
568
569 ItemEvent::Edit => {
570 let autosave = WorkspaceSettings::get_global(cx).autosave;
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 WorkspaceSettings::get_global(cx).autosave == AutosaveSetting::OnFocusChange {
588 if let Some(item) = weak_item.upgrade() {
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 let builders = cx.try_global::<FollowableItemBuilders>()?;
670 let item = self.to_any();
671 Some(builders.get(&item.entity_type())?.1(&item))
672 }
673
674 fn on_release(
675 &self,
676 cx: &mut AppContext,
677 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
678 ) -> gpui::Subscription {
679 cx.observe_release(self, move |_, cx| callback(cx))
680 }
681
682 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
683 self.read(cx).as_searchable(self)
684 }
685
686 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
687 self.read(cx).breadcrumb_location()
688 }
689
690 fn breadcrumbs(&self, theme: &Theme, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
691 self.read(cx).breadcrumbs(theme, cx)
692 }
693
694 fn serialized_item_kind(&self) -> Option<&'static str> {
695 T::serialized_item_kind()
696 }
697
698 fn show_toolbar(&self, cx: &AppContext) -> bool {
699 self.read(cx).show_toolbar()
700 }
701
702 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
703 self.read(cx).pixel_position_of_cursor(cx)
704 }
705}
706
707impl From<Box<dyn ItemHandle>> for AnyView {
708 fn from(val: Box<dyn ItemHandle>) -> Self {
709 val.to_any()
710 }
711}
712
713impl From<&Box<dyn ItemHandle>> for AnyView {
714 fn from(val: &Box<dyn ItemHandle>) -> Self {
715 val.to_any()
716 }
717}
718
719impl Clone for Box<dyn ItemHandle> {
720 fn clone(&self) -> Box<dyn ItemHandle> {
721 self.boxed_clone()
722 }
723}
724
725impl<T: Item> WeakItemHandle for WeakView<T> {
726 fn id(&self) -> EntityId {
727 self.entity_id()
728 }
729
730 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
731 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
732 }
733}
734
735pub trait ProjectItem: Item {
736 type Item: project::Item;
737
738 fn for_project_item(
739 project: Model<Project>,
740 item: Model<Self::Item>,
741 cx: &mut ViewContext<Self>,
742 ) -> Self
743 where
744 Self: Sized;
745}
746
747#[derive(Debug)]
748pub enum FollowEvent {
749 Unfollow,
750}
751
752pub trait FollowableItem: Item {
753 fn remote_id(&self) -> Option<ViewId>;
754 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
755 fn from_state_proto(
756 pane: View<Pane>,
757 project: View<Workspace>,
758 id: ViewId,
759 state: &mut Option<proto::view::Variant>,
760 cx: &mut WindowContext,
761 ) -> Option<Task<Result<View<Self>>>>;
762 fn to_follow_event(event: &Self::Event) -> Option<FollowEvent>;
763 fn add_event_to_update_proto(
764 &self,
765 event: &Self::Event,
766 update: &mut Option<proto::update_view::Variant>,
767 cx: &WindowContext,
768 ) -> bool;
769 fn apply_update_proto(
770 &mut self,
771 project: &Model<Project>,
772 message: proto::update_view::Variant,
773 cx: &mut ViewContext<Self>,
774 ) -> Task<Result<()>>;
775 fn is_project_item(&self, cx: &WindowContext) -> bool;
776 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
777}
778
779pub trait FollowableItemHandle: ItemHandle {
780 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId>;
781 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle>;
782 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
783 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant>;
784 fn add_event_to_update_proto(
785 &self,
786 event: &dyn Any,
787 update: &mut Option<proto::update_view::Variant>,
788 cx: &WindowContext,
789 ) -> bool;
790 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent>;
791 fn apply_update_proto(
792 &self,
793 project: &Model<Project>,
794 message: proto::update_view::Variant,
795 cx: &mut WindowContext,
796 ) -> Task<Result<()>>;
797 fn is_project_item(&self, cx: &WindowContext) -> bool;
798}
799
800impl<T: FollowableItem> FollowableItemHandle for View<T> {
801 fn remote_id(&self, client: &Arc<Client>, cx: &WindowContext) -> Option<ViewId> {
802 self.read(cx).remote_id().or_else(|| {
803 client.peer_id().map(|creator| ViewId {
804 creator,
805 id: self.item_id().as_u64(),
806 })
807 })
808 }
809
810 fn downgrade(&self) -> Box<dyn WeakFollowableItemHandle> {
811 Box::new(self.downgrade())
812 }
813
814 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
815 self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
816 }
817
818 fn to_state_proto(&self, cx: &WindowContext) -> Option<proto::view::Variant> {
819 self.read(cx).to_state_proto(cx)
820 }
821
822 fn add_event_to_update_proto(
823 &self,
824 event: &dyn Any,
825 update: &mut Option<proto::update_view::Variant>,
826 cx: &WindowContext,
827 ) -> bool {
828 if let Some(event) = event.downcast_ref() {
829 self.read(cx).add_event_to_update_proto(event, update, cx)
830 } else {
831 false
832 }
833 }
834
835 fn to_follow_event(&self, event: &dyn Any) -> Option<FollowEvent> {
836 T::to_follow_event(event.downcast_ref()?)
837 }
838
839 fn apply_update_proto(
840 &self,
841 project: &Model<Project>,
842 message: proto::update_view::Variant,
843 cx: &mut WindowContext,
844 ) -> Task<Result<()>> {
845 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
846 }
847
848 fn is_project_item(&self, cx: &WindowContext) -> bool {
849 self.read(cx).is_project_item(cx)
850 }
851}
852
853pub trait WeakFollowableItemHandle: Send + Sync {
854 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>>;
855}
856
857impl<T: FollowableItem> WeakFollowableItemHandle for WeakView<T> {
858 fn upgrade(&self) -> Option<Box<dyn FollowableItemHandle>> {
859 Some(Box::new(self.upgrade()?))
860 }
861}
862
863#[cfg(any(test, feature = "test-support"))]
864pub mod test {
865 use super::{Item, ItemEvent, TabContentParams};
866 use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
867 use gpui::{
868 AnyElement, AppContext, Context as _, EntityId, EventEmitter, FocusableView,
869 InteractiveElement, IntoElement, Model, Render, SharedString, Task, View, ViewContext,
870 VisualContext, WeakView,
871 };
872 use project::{Project, ProjectEntryId, ProjectPath, WorktreeId};
873 use std::{any::Any, cell::Cell, path::Path};
874
875 pub struct TestProjectItem {
876 pub entry_id: Option<ProjectEntryId>,
877 pub project_path: Option<ProjectPath>,
878 }
879
880 pub struct TestItem {
881 pub workspace_id: WorkspaceId,
882 pub state: String,
883 pub label: String,
884 pub save_count: usize,
885 pub save_as_count: usize,
886 pub reload_count: usize,
887 pub is_dirty: bool,
888 pub is_singleton: bool,
889 pub has_conflict: bool,
890 pub project_items: Vec<Model<TestProjectItem>>,
891 pub nav_history: Option<ItemNavHistory>,
892 pub tab_descriptions: Option<Vec<&'static str>>,
893 pub tab_detail: Cell<Option<usize>>,
894 focus_handle: gpui::FocusHandle,
895 }
896
897 impl project::Item for TestProjectItem {
898 fn try_open(
899 _project: &Model<Project>,
900 _path: &ProjectPath,
901 _cx: &mut AppContext,
902 ) -> Option<Task<gpui::Result<Model<Self>>>> {
903 None
904 }
905
906 fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
907 self.entry_id
908 }
909
910 fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
911 self.project_path.clone()
912 }
913 }
914
915 pub enum TestItemEvent {
916 Edit,
917 }
918
919 impl TestProjectItem {
920 pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
921 let entry_id = Some(ProjectEntryId::from_proto(id));
922 let project_path = Some(ProjectPath {
923 worktree_id: WorktreeId::from_usize(0),
924 path: Path::new(path).into(),
925 });
926 cx.new_model(|_| Self {
927 entry_id,
928 project_path,
929 })
930 }
931
932 pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
933 cx.new_model(|_| Self {
934 project_path: None,
935 entry_id: None,
936 })
937 }
938 }
939
940 impl TestItem {
941 pub fn new(cx: &mut ViewContext<Self>) -> Self {
942 Self {
943 state: String::new(),
944 label: String::new(),
945 save_count: 0,
946 save_as_count: 0,
947 reload_count: 0,
948 is_dirty: false,
949 has_conflict: false,
950 project_items: Vec::new(),
951 is_singleton: true,
952 nav_history: None,
953 tab_descriptions: None,
954 tab_detail: Default::default(),
955 workspace_id: Default::default(),
956 focus_handle: cx.focus_handle(),
957 }
958 }
959
960 pub fn new_deserialized(id: WorkspaceId, cx: &mut ViewContext<Self>) -> Self {
961 let mut this = Self::new(cx);
962 this.workspace_id = id;
963 this
964 }
965
966 pub fn with_label(mut self, state: &str) -> Self {
967 self.label = state.to_string();
968 self
969 }
970
971 pub fn with_singleton(mut self, singleton: bool) -> Self {
972 self.is_singleton = singleton;
973 self
974 }
975
976 pub fn with_dirty(mut self, dirty: bool) -> Self {
977 self.is_dirty = dirty;
978 self
979 }
980
981 pub fn with_conflict(mut self, has_conflict: bool) -> Self {
982 self.has_conflict = has_conflict;
983 self
984 }
985
986 pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
987 self.project_items.clear();
988 self.project_items.extend(items.iter().cloned());
989 self
990 }
991
992 pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
993 self.push_to_nav_history(cx);
994 self.state = state;
995 }
996
997 fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
998 if let Some(history) = &mut self.nav_history {
999 history.push(Some(Box::new(self.state.clone())), cx);
1000 }
1001 }
1002 }
1003
1004 impl Render for TestItem {
1005 fn render(&mut self, _: &mut ViewContext<Self>) -> impl IntoElement {
1006 gpui::div().track_focus(&self.focus_handle)
1007 }
1008 }
1009
1010 impl EventEmitter<ItemEvent> for TestItem {}
1011
1012 impl FocusableView for TestItem {
1013 fn focus_handle(&self, _: &AppContext) -> gpui::FocusHandle {
1014 self.focus_handle.clone()
1015 }
1016 }
1017
1018 impl Item for TestItem {
1019 type Event = ItemEvent;
1020
1021 fn to_item_events(event: &Self::Event, mut f: impl FnMut(ItemEvent)) {
1022 f(*event)
1023 }
1024
1025 fn tab_description(&self, detail: usize, _: &AppContext) -> Option<SharedString> {
1026 self.tab_descriptions.as_ref().and_then(|descriptions| {
1027 let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
1028 Some(description.into())
1029 })
1030 }
1031
1032 fn telemetry_event_text(&self) -> Option<&'static str> {
1033 None
1034 }
1035
1036 fn tab_content(
1037 &self,
1038 params: TabContentParams,
1039 _cx: &ui::prelude::WindowContext,
1040 ) -> AnyElement {
1041 self.tab_detail.set(params.detail);
1042 gpui::div().into_any_element()
1043 }
1044
1045 fn for_each_project_item(
1046 &self,
1047 cx: &AppContext,
1048 f: &mut dyn FnMut(EntityId, &dyn project::Item),
1049 ) {
1050 self.project_items
1051 .iter()
1052 .for_each(|item| f(item.entity_id(), item.read(cx)))
1053 }
1054
1055 fn is_singleton(&self, _: &AppContext) -> bool {
1056 self.is_singleton
1057 }
1058
1059 fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
1060 self.nav_history = Some(history);
1061 }
1062
1063 fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
1064 let state = *state.downcast::<String>().unwrap_or_default();
1065 if state != self.state {
1066 self.state = state;
1067 true
1068 } else {
1069 false
1070 }
1071 }
1072
1073 fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
1074 self.push_to_nav_history(cx);
1075 }
1076
1077 fn clone_on_split(
1078 &self,
1079 _workspace_id: WorkspaceId,
1080 cx: &mut ViewContext<Self>,
1081 ) -> Option<View<Self>>
1082 where
1083 Self: Sized,
1084 {
1085 Some(cx.new_view(|cx| Self {
1086 state: self.state.clone(),
1087 label: self.label.clone(),
1088 save_count: self.save_count,
1089 save_as_count: self.save_as_count,
1090 reload_count: self.reload_count,
1091 is_dirty: self.is_dirty,
1092 is_singleton: self.is_singleton,
1093 has_conflict: self.has_conflict,
1094 project_items: self.project_items.clone(),
1095 nav_history: None,
1096 tab_descriptions: None,
1097 tab_detail: Default::default(),
1098 workspace_id: self.workspace_id,
1099 focus_handle: cx.focus_handle(),
1100 }))
1101 }
1102
1103 fn is_dirty(&self, _: &AppContext) -> bool {
1104 self.is_dirty
1105 }
1106
1107 fn has_conflict(&self, _: &AppContext) -> bool {
1108 self.has_conflict
1109 }
1110
1111 fn can_save(&self, cx: &AppContext) -> bool {
1112 !self.project_items.is_empty()
1113 && self
1114 .project_items
1115 .iter()
1116 .all(|item| item.read(cx).entry_id.is_some())
1117 }
1118
1119 fn save(
1120 &mut self,
1121 _: bool,
1122 _: Model<Project>,
1123 _: &mut ViewContext<Self>,
1124 ) -> Task<anyhow::Result<()>> {
1125 self.save_count += 1;
1126 self.is_dirty = false;
1127 Task::ready(Ok(()))
1128 }
1129
1130 fn save_as(
1131 &mut self,
1132 _: Model<Project>,
1133 _: ProjectPath,
1134 _: &mut ViewContext<Self>,
1135 ) -> Task<anyhow::Result<()>> {
1136 self.save_as_count += 1;
1137 self.is_dirty = false;
1138 Task::ready(Ok(()))
1139 }
1140
1141 fn reload(
1142 &mut self,
1143 _: Model<Project>,
1144 _: &mut ViewContext<Self>,
1145 ) -> Task<anyhow::Result<()>> {
1146 self.reload_count += 1;
1147 self.is_dirty = false;
1148 Task::ready(Ok(()))
1149 }
1150
1151 fn serialized_item_kind() -> Option<&'static str> {
1152 Some("TestItem")
1153 }
1154
1155 fn deserialize(
1156 _project: Model<Project>,
1157 _workspace: WeakView<Workspace>,
1158 workspace_id: WorkspaceId,
1159 _item_id: ItemId,
1160 cx: &mut ViewContext<Pane>,
1161 ) -> Task<anyhow::Result<View<Self>>> {
1162 let view = cx.new_view(|cx| Self::new_deserialized(workspace_id, cx));
1163 Task::Ready(Some(anyhow::Ok(view)))
1164 }
1165 }
1166}