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