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