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