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