1use crate::{
2 pane::{self, Pane},
3 persistence::model::ItemId,
4 searchable::SearchableItemHandle,
5 workspace_settings::{AutosaveSetting, WorkspaceSettings},
6 DelayedDebouncedEditAction, FollowableItemBuilders, ItemNavHistory, ToolbarItemLocation,
7 ViewId, Workspace, WorkspaceId,
8};
9use anyhow::Result;
10use client2::{
11 proto::{self, PeerId},
12 Client,
13};
14use gpui::{
15 AnyElement, AnyView, AppContext, Entity, EntityId, EventEmitter, HighlightStyle, Model, Pixels,
16 Point, Render, SharedString, Task, View, ViewContext, WeakView, WindowContext,
17};
18use parking_lot::Mutex;
19use project2::{Project, ProjectEntryId, ProjectPath};
20use schemars::JsonSchema;
21use serde::{Deserialize, Serialize};
22use settings2::Settings;
23use smallvec::SmallVec;
24use std::{
25 any::{Any, TypeId},
26 ops::Range,
27 path::PathBuf,
28 sync::{
29 atomic::{AtomicBool, Ordering},
30 Arc,
31 },
32 time::Duration,
33};
34use theme2::ThemeVariant;
35
36#[derive(Deserialize)]
37pub struct ItemSettings {
38 pub git_status: bool,
39 pub close_position: ClosePosition,
40}
41
42#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
43#[serde(rename_all = "lowercase")]
44pub enum ClosePosition {
45 Left,
46 #[default]
47 Right,
48}
49
50impl ClosePosition {
51 pub fn right(&self) -> bool {
52 match self {
53 ClosePosition::Left => false,
54 ClosePosition::Right => true,
55 }
56 }
57}
58
59#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
60pub struct ItemSettingsContent {
61 git_status: Option<bool>,
62 close_position: Option<ClosePosition>,
63}
64
65impl Settings for ItemSettings {
66 const KEY: Option<&'static str> = Some("tabs");
67
68 type FileContent = ItemSettingsContent;
69
70 fn load(
71 default_value: &Self::FileContent,
72 user_values: &[&Self::FileContent],
73 _: &mut AppContext,
74 ) -> Result<Self> {
75 Self::load_via_json_merge(default_value, user_values)
76 }
77}
78
79#[derive(Eq, PartialEq, Hash, Debug)]
80pub enum ItemEvent {
81 CloseItem,
82 UpdateTab,
83 UpdateBreadcrumbs,
84 Edit,
85}
86
87// TODO: Combine this with existing HighlightedText struct?
88pub struct BreadcrumbText {
89 pub text: String,
90 pub highlights: Option<Vec<(Range<usize>, HighlightStyle)>>,
91}
92
93pub trait Item: Render + EventEmitter + Send {
94 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
95 fn workspace_deactivated(&mut self, _: &mut ViewContext<Self>) {}
96 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
97 false
98 }
99 fn tab_tooltip_text(&self, _: &AppContext) -> Option<SharedString> {
100 None
101 }
102 fn tab_description(&self, _: usize, _: &AppContext) -> Option<SharedString> {
103 None
104 }
105 fn tab_content<V: 'static>(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<V>;
106
107 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project2::Item)) {
108 } // (model id, Item)
109 fn is_singleton(&self, _cx: &AppContext) -> bool {
110 false
111 }
112 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>) {}
113 fn clone_on_split(
114 &self,
115 _workspace_id: WorkspaceId,
116 _: &mut ViewContext<Self>,
117 ) -> Option<View<Self>>
118 where
119 Self: Sized,
120 {
121 None
122 }
123 fn is_dirty(&self, _: &AppContext) -> bool {
124 false
125 }
126 fn has_conflict(&self, _: &AppContext) -> bool {
127 false
128 }
129 fn can_save(&self, _cx: &AppContext) -> bool {
130 false
131 }
132 fn save(&mut self, _project: Model<Project>, _cx: &mut ViewContext<Self>) -> Task<Result<()>> {
133 unimplemented!("save() must be implemented if can_save() returns true")
134 }
135 fn save_as(
136 &mut self,
137 _project: Model<Project>,
138 _abs_path: PathBuf,
139 _cx: &mut ViewContext<Self>,
140 ) -> Task<Result<()>> {
141 unimplemented!("save_as() must be implemented if can_save() returns true")
142 }
143 fn reload(
144 &mut self,
145 _project: Model<Project>,
146 _cx: &mut ViewContext<Self>,
147 ) -> Task<Result<()>> {
148 unimplemented!("reload() must be implemented if can_save() returns true")
149 }
150 fn to_item_events(_event: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
151 SmallVec::new()
152 }
153 fn should_close_item_on_event(_: &Self::Event) -> bool {
154 false
155 }
156 fn should_update_tab_on_event(_: &Self::Event) -> bool {
157 false
158 }
159
160 fn act_as_type<'a>(
161 &'a self,
162 type_id: TypeId,
163 self_handle: &'a View<Self>,
164 _: &'a AppContext,
165 ) -> Option<AnyView> {
166 if TypeId::of::<Self>() == type_id {
167 Some(self_handle.clone().into())
168 } else {
169 None
170 }
171 }
172
173 fn as_searchable(&self, _: &View<Self>) -> Option<Box<dyn SearchableItemHandle>> {
174 None
175 }
176
177 fn breadcrumb_location(&self) -> ToolbarItemLocation {
178 ToolbarItemLocation::Hidden
179 }
180
181 fn breadcrumbs(&self, _theme: &ThemeVariant, _cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
182 None
183 }
184
185 fn added_to_workspace(&mut self, _workspace: &mut Workspace, _cx: &mut ViewContext<Self>) {}
186
187 fn serialized_item_kind() -> Option<&'static str> {
188 None
189 }
190
191 fn deserialize(
192 _project: Model<Project>,
193 _workspace: WeakView<Workspace>,
194 _workspace_id: WorkspaceId,
195 _item_id: ItemId,
196 _cx: &mut ViewContext<Pane>,
197 ) -> Task<Result<View<Self>>> {
198 unimplemented!(
199 "deserialize() must be implemented if serialized_item_kind() returns Some(_)"
200 )
201 }
202 fn show_toolbar(&self) -> bool {
203 true
204 }
205 fn pixel_position_of_cursor(&self, _: &AppContext) -> Option<Point<Pixels>> {
206 None
207 }
208}
209
210pub trait ItemHandle: 'static + Send {
211 fn subscribe_to_item_events(
212 &self,
213 cx: &mut WindowContext,
214 handler: Box<dyn Fn(ItemEvent, &mut WindowContext) + Send>,
215 ) -> gpui::Subscription;
216 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString>;
217 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString>;
218 fn tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Pane>;
219 fn dragged_tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Workspace>;
220 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
221 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]>;
222 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]>;
223 fn for_each_project_item(&self, _: &AppContext, _: &mut dyn FnMut(usize, &dyn project2::Item));
224 fn is_singleton(&self, cx: &AppContext) -> bool;
225 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
226 fn clone_on_split(
227 &self,
228 workspace_id: WorkspaceId,
229 cx: &mut WindowContext,
230 ) -> Option<Box<dyn ItemHandle>>;
231 fn added_to_pane(
232 &self,
233 workspace: &mut Workspace,
234 pane: View<Pane>,
235 cx: &mut ViewContext<Workspace>,
236 );
237 fn deactivated(&self, cx: &mut WindowContext);
238 fn workspace_deactivated(&self, cx: &mut WindowContext);
239 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool;
240 fn id(&self) -> EntityId;
241 fn to_any(&self) -> AnyView;
242 fn is_dirty(&self, cx: &AppContext) -> bool;
243 fn has_conflict(&self, cx: &AppContext) -> bool;
244 fn can_save(&self, cx: &AppContext) -> bool;
245 fn save(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
246 fn save_as(
247 &self,
248 project: Model<Project>,
249 abs_path: PathBuf,
250 cx: &mut WindowContext,
251 ) -> Task<Result<()>>;
252 fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>>;
253 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyView>;
254 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
255 fn on_release(
256 &mut self,
257 cx: &mut AppContext,
258 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
259 ) -> gpui::Subscription;
260 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>>;
261 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation;
262 fn breadcrumbs(&self, theme: &ThemeVariant, cx: &AppContext) -> Option<Vec<BreadcrumbText>>;
263 fn serialized_item_kind(&self) -> Option<&'static str>;
264 fn show_toolbar(&self, cx: &AppContext) -> bool;
265 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>>;
266}
267
268pub trait WeakItemHandle: Send + Sync {
269 fn id(&self) -> EntityId;
270 fn upgrade(&self) -> Option<Box<dyn ItemHandle>>;
271}
272
273impl dyn ItemHandle {
274 pub fn downcast<V: 'static>(&self) -> Option<View<V>> {
275 self.to_any().downcast().ok()
276 }
277
278 pub fn act_as<V: 'static>(&self, cx: &AppContext) -> Option<View<V>> {
279 self.act_as_type(TypeId::of::<V>(), cx)
280 .and_then(|t| t.downcast().ok())
281 }
282}
283
284impl<T: Item> ItemHandle for View<T> {
285 fn subscribe_to_item_events(
286 &self,
287 cx: &mut WindowContext,
288 handler: Box<dyn Fn(ItemEvent, &mut WindowContext) + Send>,
289 ) -> gpui::Subscription {
290 cx.subscribe(self, move |_, event, cx| {
291 for item_event in T::to_item_events(event) {
292 handler(item_event, cx)
293 }
294 })
295 }
296
297 fn tab_tooltip_text(&self, cx: &AppContext) -> Option<SharedString> {
298 self.read(cx).tab_tooltip_text(cx)
299 }
300
301 fn tab_description(&self, detail: usize, cx: &AppContext) -> Option<SharedString> {
302 self.read(cx).tab_description(detail, cx)
303 }
304
305 fn tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Pane> {
306 self.read(cx).tab_content(detail, cx)
307 }
308
309 fn dragged_tab_content(&self, detail: Option<usize>, cx: &AppContext) -> AnyElement<Workspace> {
310 self.read(cx).tab_content(detail, cx)
311 }
312
313 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
314 let this = self.read(cx);
315 let mut result = None;
316 if this.is_singleton(cx) {
317 this.for_each_project_item(cx, &mut |_, item| {
318 result = item.project_path(cx);
319 });
320 }
321 result
322 }
323
324 fn project_entry_ids(&self, cx: &AppContext) -> SmallVec<[ProjectEntryId; 3]> {
325 let mut result = SmallVec::new();
326 self.read(cx).for_each_project_item(cx, &mut |_, item| {
327 if let Some(id) = item.entry_id(cx) {
328 result.push(id);
329 }
330 });
331 result
332 }
333
334 fn project_item_model_ids(&self, cx: &AppContext) -> SmallVec<[usize; 3]> {
335 let mut result = SmallVec::new();
336 self.read(cx).for_each_project_item(cx, &mut |id, _| {
337 result.push(id);
338 });
339 result
340 }
341
342 fn for_each_project_item(
343 &self,
344 cx: &AppContext,
345 f: &mut dyn FnMut(usize, &dyn project2::Item),
346 ) {
347 self.read(cx).for_each_project_item(cx, f)
348 }
349
350 fn is_singleton(&self, cx: &AppContext) -> bool {
351 self.read(cx).is_singleton(cx)
352 }
353
354 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
355 Box::new(self.clone())
356 }
357
358 fn clone_on_split(
359 &self,
360 workspace_id: WorkspaceId,
361 cx: &mut WindowContext,
362 ) -> Option<Box<dyn ItemHandle>> {
363 self.update(cx, |item, cx| item.clone_on_split(workspace_id, cx))
364 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
365 }
366
367 fn added_to_pane(
368 &self,
369 workspace: &mut Workspace,
370 pane: View<Pane>,
371 cx: &mut ViewContext<Workspace>,
372 ) {
373 let history = pane.read(cx).nav_history_for_item(self);
374 self.update(cx, |this, cx| {
375 this.set_nav_history(history, cx);
376 this.added_to_workspace(workspace, cx);
377 });
378
379 if let Some(followed_item) = self.to_followable_item_handle(cx) {
380 if let Some(message) = followed_item.to_state_proto(cx) {
381 workspace.update_followers(
382 followed_item.is_project_item(cx),
383 proto::update_followers::Variant::CreateView(proto::View {
384 id: followed_item
385 .remote_id(&workspace.app_state.client, cx)
386 .map(|id| id.to_proto()),
387 variant: Some(message),
388 leader_id: workspace.leader_for_pane(&pane),
389 }),
390 cx,
391 );
392 }
393 }
394
395 if workspace
396 .panes_by_item
397 .insert(self.id(), pane.downgrade())
398 .is_none()
399 {
400 let mut pending_autosave = DelayedDebouncedEditAction::new();
401 let pending_update = Arc::new(Mutex::new(None));
402 let pending_update_scheduled = Arc::new(AtomicBool::new(false));
403
404 let event_subscription = Some(cx.subscribe(self, move |workspace, item, event, cx| {
405 let pane = if let Some(pane) = workspace
406 .panes_by_item
407 .get(&item.id())
408 .and_then(|pane| pane.upgrade())
409 {
410 pane
411 } else {
412 log::error!("unexpected item event after pane was dropped");
413 return;
414 };
415
416 if let Some(item) = item.to_followable_item_handle(cx) {
417 let _is_project_item = item.is_project_item(cx);
418 let leader_id = workspace.leader_for_pane(&pane);
419
420 if leader_id.is_some() && item.should_unfollow_on_event(event, cx) {
421 workspace.unfollow(&pane, cx);
422 }
423
424 if item.add_event_to_update_proto(event, &mut *pending_update.lock(), cx)
425 && !pending_update_scheduled.load(Ordering::SeqCst)
426 {
427 pending_update_scheduled.store(true, Ordering::SeqCst);
428 todo!("replace with on_next_frame?");
429 // cx.after_window_update({
430 // let pending_update = pending_update.clone();
431 // let pending_update_scheduled = pending_update_scheduled.clone();
432 // move |this, cx| {
433 // pending_update_scheduled.store(false, Ordering::SeqCst);
434 // this.update_followers(
435 // is_project_item,
436 // proto::update_followers::Variant::UpdateView(
437 // proto::UpdateView {
438 // id: item
439 // .remote_id(&this.app_state.client, cx)
440 // .map(|id| id.to_proto()),
441 // variant: pending_update.borrow_mut().take(),
442 // leader_id,
443 // },
444 // ),
445 // cx,
446 // );
447 // }
448 // });
449 }
450 }
451
452 for item_event in T::to_item_events(event).into_iter() {
453 match item_event {
454 ItemEvent::CloseItem => {
455 pane.update(cx, |pane, cx| {
456 pane.close_item_by_id(item.id(), crate::SaveIntent::Close, cx)
457 })
458 .detach_and_log_err(cx);
459 return;
460 }
461
462 ItemEvent::UpdateTab => {
463 pane.update(cx, |_, cx| {
464 cx.emit(pane::Event::ChangeItemTitle);
465 cx.notify();
466 });
467 }
468
469 ItemEvent::Edit => {
470 let autosave = WorkspaceSettings::get_global(cx).autosave;
471 if let AutosaveSetting::AfterDelay { milliseconds } = autosave {
472 let delay = Duration::from_millis(milliseconds);
473 let item = item.clone();
474 pending_autosave.fire_new(delay, cx, move |workspace, cx| {
475 Pane::autosave_item(&item, workspace.project().clone(), cx)
476 });
477 }
478 }
479
480 _ => {}
481 }
482 }
483 }));
484
485 todo!("observe focus");
486 // cx.observe_focus(self, move |workspace, item, focused, cx| {
487 // if !focused
488 // && WorkspaceSettings::get_global(cx).autosave == AutosaveSetting::OnFocusChange
489 // {
490 // Pane::autosave_item(&item, workspace.project.clone(), cx)
491 // .detach_and_log_err(cx);
492 // }
493 // })
494 // .detach();
495
496 // let item_id = self.id();
497 // cx.observe_release(self, move |workspace, _, _| {
498 // workspace.panes_by_item.remove(&item_id);
499 // event_subscription.take();
500 // })
501 // .detach();
502 }
503
504 cx.defer(|workspace, cx| {
505 workspace.serialize_workspace(cx);
506 });
507 }
508
509 fn deactivated(&self, cx: &mut WindowContext) {
510 self.update(cx, |this, cx| this.deactivated(cx));
511 }
512
513 fn workspace_deactivated(&self, cx: &mut WindowContext) {
514 self.update(cx, |this, cx| this.workspace_deactivated(cx));
515 }
516
517 fn navigate(&self, data: Box<dyn Any>, cx: &mut WindowContext) -> bool {
518 self.update(cx, |this, cx| this.navigate(data, cx))
519 }
520
521 fn id(&self) -> EntityId {
522 self.entity_id()
523 }
524
525 fn to_any(&self) -> AnyView {
526 self.clone().into()
527 }
528
529 fn is_dirty(&self, cx: &AppContext) -> bool {
530 self.read(cx).is_dirty(cx)
531 }
532
533 fn has_conflict(&self, cx: &AppContext) -> bool {
534 self.read(cx).has_conflict(cx)
535 }
536
537 fn can_save(&self, cx: &AppContext) -> bool {
538 self.read(cx).can_save(cx)
539 }
540
541 fn save(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
542 self.update(cx, |item, cx| item.save(project, cx))
543 }
544
545 fn save_as(
546 &self,
547 project: Model<Project>,
548 abs_path: PathBuf,
549 cx: &mut WindowContext,
550 ) -> Task<anyhow::Result<()>> {
551 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
552 }
553
554 fn reload(&self, project: Model<Project>, cx: &mut WindowContext) -> Task<Result<()>> {
555 self.update(cx, |item, cx| item.reload(project, cx))
556 }
557
558 fn act_as_type<'a>(&'a self, type_id: TypeId, cx: &'a AppContext) -> Option<AnyView> {
559 self.read(cx).act_as_type(type_id, self, cx)
560 }
561
562 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
563 if cx.has_global::<FollowableItemBuilders>() {
564 let builders = cx.global::<FollowableItemBuilders>();
565 let item = self.to_any();
566 Some(builders.get(&item.entity_type())?.1(&item))
567 } else {
568 None
569 }
570 }
571
572 fn on_release(
573 &mut self,
574 cx: &mut AppContext,
575 callback: Box<dyn FnOnce(&mut AppContext) + Send>,
576 ) -> gpui::Subscription {
577 cx.observe_release(self, move |_, cx| callback(cx))
578 }
579
580 fn to_searchable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn SearchableItemHandle>> {
581 self.read(cx).as_searchable(self)
582 }
583
584 fn breadcrumb_location(&self, cx: &AppContext) -> ToolbarItemLocation {
585 self.read(cx).breadcrumb_location()
586 }
587
588 fn breadcrumbs(&self, theme: &ThemeVariant, cx: &AppContext) -> Option<Vec<BreadcrumbText>> {
589 self.read(cx).breadcrumbs(theme, cx)
590 }
591
592 fn serialized_item_kind(&self) -> Option<&'static str> {
593 T::serialized_item_kind()
594 }
595
596 fn show_toolbar(&self, cx: &AppContext) -> bool {
597 self.read(cx).show_toolbar()
598 }
599
600 fn pixel_position_of_cursor(&self, cx: &AppContext) -> Option<Point<Pixels>> {
601 self.read(cx).pixel_position_of_cursor(cx)
602 }
603}
604
605impl From<Box<dyn ItemHandle>> for AnyView {
606 fn from(val: Box<dyn ItemHandle>) -> Self {
607 val.to_any()
608 }
609}
610
611impl From<&Box<dyn ItemHandle>> for AnyView {
612 fn from(val: &Box<dyn ItemHandle>) -> Self {
613 val.to_any()
614 }
615}
616
617impl Clone for Box<dyn ItemHandle> {
618 fn clone(&self) -> Box<dyn ItemHandle> {
619 self.boxed_clone()
620 }
621}
622
623impl<T: Item> WeakItemHandle for WeakView<T> {
624 fn id(&self) -> EntityId {
625 self.entity_id()
626 }
627
628 fn upgrade(&self) -> Option<Box<dyn ItemHandle>> {
629 self.upgrade().map(|v| Box::new(v) as Box<dyn ItemHandle>)
630 }
631}
632
633pub trait ProjectItem: Item {
634 type Item: project2::Item;
635
636 fn for_project_item(
637 project: Model<Project>,
638 item: Model<Self::Item>,
639 cx: &mut ViewContext<Self>,
640 ) -> Self
641 where
642 Self: Sized;
643}
644
645pub trait FollowableItem: Item {
646 fn remote_id(&self) -> Option<ViewId>;
647 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
648 fn from_state_proto(
649 pane: View<Pane>,
650 project: View<Workspace>,
651 id: ViewId,
652 state: &mut Option<proto::view::Variant>,
653 cx: &mut AppContext,
654 ) -> Option<Task<Result<View<Self>>>>;
655 fn add_event_to_update_proto(
656 &self,
657 event: &Self::Event,
658 update: &mut Option<proto::update_view::Variant>,
659 cx: &AppContext,
660 ) -> bool;
661 fn apply_update_proto(
662 &mut self,
663 project: &Model<Project>,
664 message: proto::update_view::Variant,
665 cx: &mut ViewContext<Self>,
666 ) -> Task<Result<()>>;
667 fn is_project_item(&self, cx: &AppContext) -> bool;
668
669 fn set_leader_peer_id(&mut self, leader_peer_id: Option<PeerId>, cx: &mut ViewContext<Self>);
670 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
671}
672
673pub trait FollowableItemHandle: ItemHandle {
674 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId>;
675 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext);
676 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant>;
677 fn add_event_to_update_proto(
678 &self,
679 event: &dyn Any,
680 update: &mut Option<proto::update_view::Variant>,
681 cx: &AppContext,
682 ) -> bool;
683 fn apply_update_proto(
684 &self,
685 project: &Model<Project>,
686 message: proto::update_view::Variant,
687 cx: &mut WindowContext,
688 ) -> Task<Result<()>>;
689 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
690 fn is_project_item(&self, cx: &AppContext) -> bool;
691}
692
693impl<T: FollowableItem> FollowableItemHandle for View<T> {
694 fn remote_id(&self, client: &Arc<Client>, cx: &AppContext) -> Option<ViewId> {
695 self.read(cx).remote_id().or_else(|| {
696 client.peer_id().map(|creator| ViewId {
697 creator,
698 id: self.id().as_u64(),
699 })
700 })
701 }
702
703 fn set_leader_peer_id(&self, leader_peer_id: Option<PeerId>, cx: &mut WindowContext) {
704 self.update(cx, |this, cx| this.set_leader_peer_id(leader_peer_id, cx))
705 }
706
707 fn to_state_proto(&self, cx: &AppContext) -> Option<proto::view::Variant> {
708 self.read(cx).to_state_proto(cx)
709 }
710
711 fn add_event_to_update_proto(
712 &self,
713 event: &dyn Any,
714 update: &mut Option<proto::update_view::Variant>,
715 cx: &AppContext,
716 ) -> bool {
717 if let Some(event) = event.downcast_ref() {
718 self.read(cx).add_event_to_update_proto(event, update, cx)
719 } else {
720 false
721 }
722 }
723
724 fn apply_update_proto(
725 &self,
726 project: &Model<Project>,
727 message: proto::update_view::Variant,
728 cx: &mut WindowContext,
729 ) -> Task<Result<()>> {
730 self.update(cx, |this, cx| this.apply_update_proto(project, message, cx))
731 }
732
733 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
734 if let Some(event) = event.downcast_ref() {
735 T::should_unfollow_on_event(event, cx)
736 } else {
737 false
738 }
739 }
740
741 fn is_project_item(&self, cx: &AppContext) -> bool {
742 self.read(cx).is_project_item(cx)
743 }
744}
745
746// #[cfg(any(test, feature = "test-support"))]
747// pub mod test {
748// use super::{Item, ItemEvent};
749// use crate::{ItemId, ItemNavHistory, Pane, Workspace, WorkspaceId};
750// use gpui::{
751// elements::Empty, AnyElement, AppContext, Element, Entity, Model, Task, View,
752// ViewContext, View, WeakViewHandle,
753// };
754// use project2::{Project, ProjectEntryId, ProjectPath, WorktreeId};
755// use smallvec::SmallVec;
756// use std::{any::Any, borrow::Cow, cell::Cell, path::Path};
757
758// pub struct TestProjectItem {
759// pub entry_id: Option<ProjectEntryId>,
760// pub project_path: Option<ProjectPath>,
761// }
762
763// pub struct TestItem {
764// pub workspace_id: WorkspaceId,
765// pub state: String,
766// pub label: String,
767// pub save_count: usize,
768// pub save_as_count: usize,
769// pub reload_count: usize,
770// pub is_dirty: bool,
771// pub is_singleton: bool,
772// pub has_conflict: bool,
773// pub project_items: Vec<Model<TestProjectItem>>,
774// pub nav_history: Option<ItemNavHistory>,
775// pub tab_descriptions: Option<Vec<&'static str>>,
776// pub tab_detail: Cell<Option<usize>>,
777// }
778
779// impl Entity for TestProjectItem {
780// type Event = ();
781// }
782
783// impl project2::Item for TestProjectItem {
784// fn entry_id(&self, _: &AppContext) -> Option<ProjectEntryId> {
785// self.entry_id
786// }
787
788// fn project_path(&self, _: &AppContext) -> Option<ProjectPath> {
789// self.project_path.clone()
790// }
791// }
792
793// pub enum TestItemEvent {
794// Edit,
795// }
796
797// impl Clone for TestItem {
798// fn clone(&self) -> Self {
799// Self {
800// state: self.state.clone(),
801// label: self.label.clone(),
802// save_count: self.save_count,
803// save_as_count: self.save_as_count,
804// reload_count: self.reload_count,
805// is_dirty: self.is_dirty,
806// is_singleton: self.is_singleton,
807// has_conflict: self.has_conflict,
808// project_items: self.project_items.clone(),
809// nav_history: None,
810// tab_descriptions: None,
811// tab_detail: Default::default(),
812// workspace_id: self.workspace_id,
813// }
814// }
815// }
816
817// impl TestProjectItem {
818// pub fn new(id: u64, path: &str, cx: &mut AppContext) -> Model<Self> {
819// let entry_id = Some(ProjectEntryId::from_proto(id));
820// let project_path = Some(ProjectPath {
821// worktree_id: WorktreeId::from_usize(0),
822// path: Path::new(path).into(),
823// });
824// cx.add_model(|_| Self {
825// entry_id,
826// project_path,
827// })
828// }
829
830// pub fn new_untitled(cx: &mut AppContext) -> Model<Self> {
831// cx.add_model(|_| Self {
832// project_path: None,
833// entry_id: None,
834// })
835// }
836// }
837
838// impl TestItem {
839// pub fn new() -> Self {
840// Self {
841// state: String::new(),
842// label: String::new(),
843// save_count: 0,
844// save_as_count: 0,
845// reload_count: 0,
846// is_dirty: false,
847// has_conflict: false,
848// project_items: Vec::new(),
849// is_singleton: true,
850// nav_history: None,
851// tab_descriptions: None,
852// tab_detail: Default::default(),
853// workspace_id: 0,
854// }
855// }
856
857// pub fn new_deserialized(id: WorkspaceId) -> Self {
858// let mut this = Self::new();
859// this.workspace_id = id;
860// this
861// }
862
863// pub fn with_label(mut self, state: &str) -> Self {
864// self.label = state.to_string();
865// self
866// }
867
868// pub fn with_singleton(mut self, singleton: bool) -> Self {
869// self.is_singleton = singleton;
870// self
871// }
872
873// pub fn with_dirty(mut self, dirty: bool) -> Self {
874// self.is_dirty = dirty;
875// self
876// }
877
878// pub fn with_conflict(mut self, has_conflict: bool) -> Self {
879// self.has_conflict = has_conflict;
880// self
881// }
882
883// pub fn with_project_items(mut self, items: &[Model<TestProjectItem>]) -> Self {
884// self.project_items.clear();
885// self.project_items.extend(items.iter().cloned());
886// self
887// }
888
889// pub fn set_state(&mut self, state: String, cx: &mut ViewContext<Self>) {
890// self.push_to_nav_history(cx);
891// self.state = state;
892// }
893
894// fn push_to_nav_history(&mut self, cx: &mut ViewContext<Self>) {
895// if let Some(history) = &mut self.nav_history {
896// history.push(Some(Box::new(self.state.clone())), cx);
897// }
898// }
899// }
900
901// impl Entity for TestItem {
902// type Event = TestItemEvent;
903// }
904
905// impl View for TestItem {
906// fn ui_name() -> &'static str {
907// "TestItem"
908// }
909
910// fn render(&mut self, _: &mut ViewContext<Self>) -> AnyElement<Self> {
911// Empty::new().into_any()
912// }
913// }
914
915// impl Item for TestItem {
916// fn tab_description(&self, detail: usize, _: &AppContext) -> Option<Cow<str>> {
917// self.tab_descriptions.as_ref().and_then(|descriptions| {
918// let description = *descriptions.get(detail).or_else(|| descriptions.last())?;
919// Some(description.into())
920// })
921// }
922
923// fn tab_content<V: 'static>(
924// &self,
925// detail: Option<usize>,
926// _: &theme2::Tab,
927// _: &AppContext,
928// ) -> AnyElement<V> {
929// self.tab_detail.set(detail);
930// Empty::new().into_any()
931// }
932
933// fn for_each_project_item(
934// &self,
935// cx: &AppContext,
936// f: &mut dyn FnMut(usize, &dyn project2::Item),
937// ) {
938// self.project_items
939// .iter()
940// .for_each(|item| f(item.id(), item.read(cx)))
941// }
942
943// fn is_singleton(&self, _: &AppContext) -> bool {
944// self.is_singleton
945// }
946
947// fn set_nav_history(&mut self, history: ItemNavHistory, _: &mut ViewContext<Self>) {
948// self.nav_history = Some(history);
949// }
950
951// fn navigate(&mut self, state: Box<dyn Any>, _: &mut ViewContext<Self>) -> bool {
952// let state = *state.downcast::<String>().unwrap_or_default();
953// if state != self.state {
954// self.state = state;
955// true
956// } else {
957// false
958// }
959// }
960
961// fn deactivated(&mut self, cx: &mut ViewContext<Self>) {
962// self.push_to_nav_history(cx);
963// }
964
965// fn clone_on_split(
966// &self,
967// _workspace_id: WorkspaceId,
968// _: &mut ViewContext<Self>,
969// ) -> Option<Self>
970// where
971// Self: Sized,
972// {
973// Some(self.clone())
974// }
975
976// fn is_dirty(&self, _: &AppContext) -> bool {
977// self.is_dirty
978// }
979
980// fn has_conflict(&self, _: &AppContext) -> bool {
981// self.has_conflict
982// }
983
984// fn can_save(&self, cx: &AppContext) -> bool {
985// !self.project_items.is_empty()
986// && self
987// .project_items
988// .iter()
989// .all(|item| item.read(cx).entry_id.is_some())
990// }
991
992// fn save(
993// &mut self,
994// _: Model<Project>,
995// _: &mut ViewContext<Self>,
996// ) -> Task<anyhow::Result<()>> {
997// self.save_count += 1;
998// self.is_dirty = false;
999// Task::ready(Ok(()))
1000// }
1001
1002// fn save_as(
1003// &mut self,
1004// _: Model<Project>,
1005// _: std::path::PathBuf,
1006// _: &mut ViewContext<Self>,
1007// ) -> Task<anyhow::Result<()>> {
1008// self.save_as_count += 1;
1009// self.is_dirty = false;
1010// Task::ready(Ok(()))
1011// }
1012
1013// fn reload(
1014// &mut self,
1015// _: Model<Project>,
1016// _: &mut ViewContext<Self>,
1017// ) -> Task<anyhow::Result<()>> {
1018// self.reload_count += 1;
1019// self.is_dirty = false;
1020// Task::ready(Ok(()))
1021// }
1022
1023// fn to_item_events(_: &Self::Event) -> SmallVec<[ItemEvent; 2]> {
1024// [ItemEvent::UpdateTab, ItemEvent::Edit].into()
1025// }
1026
1027// fn serialized_item_kind() -> Option<&'static str> {
1028// Some("TestItem")
1029// }
1030
1031// fn deserialize(
1032// _project: Model<Project>,
1033// _workspace: WeakViewHandle<Workspace>,
1034// workspace_id: WorkspaceId,
1035// _item_id: ItemId,
1036// cx: &mut ViewContext<Pane>,
1037// ) -> Task<anyhow::Result<View<Self>>> {
1038// let view = cx.add_view(|_cx| Self::new_deserialized(workspace_id));
1039// Task::Ready(Some(anyhow::Ok(view)))
1040// }
1041// }
1042// }