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