1pub mod lsp_status;
2pub mod menu;
3pub mod pane;
4pub mod pane_group;
5pub mod settings;
6pub mod sidebar;
7mod status_bar;
8
9use anyhow::{anyhow, Context, Result};
10use client::{
11 proto, Authenticate, ChannelList, Client, PeerId, Subscription, TypedEnvelope, User, UserStore,
12};
13use clock::ReplicaId;
14use collections::{hash_map, HashMap, HashSet};
15use gpui::{
16 action,
17 color::Color,
18 elements::*,
19 geometry::{vector::vec2f, PathBuilder},
20 json::{self, to_string_pretty, ToJson},
21 keymap::Binding,
22 platform::{CursorStyle, WindowOptions},
23 AnyModelHandle, AnyViewHandle, AppContext, AsyncAppContext, Border, ClipboardItem, Entity,
24 ImageData, ModelHandle, MutableAppContext, PathPromptOptions, PromptLevel, RenderContext, Task,
25 View, ViewContext, ViewHandle, WeakViewHandle,
26};
27use language::LanguageRegistry;
28use log::error;
29pub use pane::*;
30pub use pane_group::*;
31use postage::prelude::Stream;
32use project::{fs, Fs, Project, ProjectEntryId, ProjectPath, Worktree};
33pub use settings::Settings;
34use sidebar::{Side, Sidebar, SidebarItemId, ToggleSidebarItem, ToggleSidebarItemFocus};
35use status_bar::StatusBar;
36pub use status_bar::StatusItemView;
37use std::{
38 any::{Any, TypeId},
39 cell::RefCell,
40 fmt,
41 future::Future,
42 path::{Path, PathBuf},
43 rc::Rc,
44 sync::Arc,
45};
46use theme::{Theme, ThemeRegistry};
47use util::ResultExt;
48
49type ProjectItemBuilders = HashMap<
50 TypeId,
51 fn(usize, ModelHandle<Project>, AnyModelHandle, &mut MutableAppContext) -> Box<dyn ItemHandle>,
52>;
53
54type FollowableItemBuilder = fn(
55 ViewHandle<Pane>,
56 ModelHandle<Project>,
57 &mut Option<proto::view::Variant>,
58 &mut MutableAppContext,
59) -> Option<Task<Result<Box<dyn FollowableItemHandle>>>>;
60type FollowableItemBuilders = HashMap<
61 TypeId,
62 (
63 FollowableItemBuilder,
64 fn(AnyViewHandle) -> Box<dyn FollowableItemHandle>,
65 ),
66>;
67
68action!(Open, Arc<AppState>);
69action!(OpenNew, Arc<AppState>);
70action!(OpenPaths, OpenParams);
71action!(ToggleShare);
72action!(ToggleFollow, PeerId);
73action!(Unfollow);
74action!(JoinProject, JoinProjectParams);
75action!(Save);
76action!(DebugElements);
77
78pub fn init(client: &Arc<Client>, cx: &mut MutableAppContext) {
79 pane::init(cx);
80 menu::init(cx);
81
82 cx.add_global_action(open);
83 cx.add_global_action(move |action: &OpenPaths, cx: &mut MutableAppContext| {
84 open_paths(&action.0.paths, &action.0.app_state, cx).detach();
85 });
86 cx.add_global_action(move |action: &OpenNew, cx: &mut MutableAppContext| {
87 open_new(&action.0, cx)
88 });
89 cx.add_global_action(move |action: &JoinProject, cx: &mut MutableAppContext| {
90 join_project(action.0.project_id, &action.0.app_state, cx).detach();
91 });
92
93 cx.add_action(Workspace::toggle_share);
94 cx.add_async_action(Workspace::toggle_follow);
95 cx.add_action(
96 |workspace: &mut Workspace, _: &Unfollow, cx: &mut ViewContext<Workspace>| {
97 let pane = workspace.active_pane().clone();
98 workspace.unfollow(&pane, cx);
99 },
100 );
101 cx.add_action(
102 |workspace: &mut Workspace, _: &Save, cx: &mut ViewContext<Workspace>| {
103 workspace.save_active_item(cx).detach_and_log_err(cx);
104 },
105 );
106 cx.add_action(Workspace::debug_elements);
107 cx.add_action(Workspace::toggle_sidebar_item);
108 cx.add_action(Workspace::toggle_sidebar_item_focus);
109 cx.add_bindings(vec![
110 Binding::new("cmd-alt-shift-U", Unfollow, None),
111 Binding::new("cmd-s", Save, None),
112 Binding::new("cmd-alt-i", DebugElements, None),
113 Binding::new(
114 "cmd-shift-!",
115 ToggleSidebarItem(SidebarItemId {
116 side: Side::Left,
117 item_index: 0,
118 }),
119 None,
120 ),
121 Binding::new(
122 "cmd-1",
123 ToggleSidebarItemFocus(SidebarItemId {
124 side: Side::Left,
125 item_index: 0,
126 }),
127 None,
128 ),
129 ]);
130
131 client.add_view_request_handler(Workspace::handle_follow);
132 client.add_view_message_handler(Workspace::handle_unfollow);
133 client.add_view_message_handler(Workspace::handle_update_followers);
134}
135
136pub fn register_project_item<I: ProjectItem>(cx: &mut MutableAppContext) {
137 cx.update_default_global(|builders: &mut ProjectItemBuilders, _| {
138 builders.insert(TypeId::of::<I::Item>(), |window_id, project, model, cx| {
139 let item = model.downcast::<I::Item>().unwrap();
140 Box::new(cx.add_view(window_id, |cx| I::for_project_item(project, item, cx)))
141 });
142 });
143}
144
145pub fn register_followable_item<I: FollowableItem>(cx: &mut MutableAppContext) {
146 cx.update_default_global(|builders: &mut FollowableItemBuilders, _| {
147 builders.insert(
148 TypeId::of::<I>(),
149 (
150 |pane, project, state, cx| {
151 I::for_state_message(pane, project, state, cx).map(|task| {
152 cx.foreground()
153 .spawn(async move { Ok(Box::new(task.await?) as Box<_>) })
154 })
155 },
156 |this| Box::new(this.downcast::<I>().unwrap()),
157 ),
158 );
159 });
160}
161
162pub struct AppState {
163 pub languages: Arc<LanguageRegistry>,
164 pub themes: Arc<ThemeRegistry>,
165 pub client: Arc<client::Client>,
166 pub user_store: ModelHandle<client::UserStore>,
167 pub fs: Arc<dyn fs::Fs>,
168 pub channel_list: ModelHandle<client::ChannelList>,
169 pub build_window_options: &'static dyn Fn() -> WindowOptions<'static>,
170 pub build_workspace: &'static dyn Fn(
171 ModelHandle<Project>,
172 &Arc<AppState>,
173 &mut ViewContext<Workspace>,
174 ) -> Workspace,
175}
176
177#[derive(Clone)]
178pub struct OpenParams {
179 pub paths: Vec<PathBuf>,
180 pub app_state: Arc<AppState>,
181}
182
183#[derive(Clone)]
184pub struct JoinProjectParams {
185 pub project_id: u64,
186 pub app_state: Arc<AppState>,
187}
188
189pub trait Item: View {
190 fn deactivated(&mut self, _: &mut ViewContext<Self>) {}
191 fn navigate(&mut self, _: Box<dyn Any>, _: &mut ViewContext<Self>) {}
192 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
193 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
194 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
195 fn set_nav_history(&mut self, _: ItemNavHistory, _: &mut ViewContext<Self>);
196 fn clone_on_split(&self, _: &mut ViewContext<Self>) -> Option<Self>
197 where
198 Self: Sized,
199 {
200 None
201 }
202 fn is_dirty(&self, _: &AppContext) -> bool {
203 false
204 }
205 fn has_conflict(&self, _: &AppContext) -> bool {
206 false
207 }
208 fn can_save(&self, cx: &AppContext) -> bool;
209 fn save(
210 &mut self,
211 project: ModelHandle<Project>,
212 cx: &mut ViewContext<Self>,
213 ) -> Task<Result<()>>;
214 fn can_save_as(&self, cx: &AppContext) -> bool;
215 fn save_as(
216 &mut self,
217 project: ModelHandle<Project>,
218 abs_path: PathBuf,
219 cx: &mut ViewContext<Self>,
220 ) -> Task<Result<()>>;
221 fn should_activate_item_on_event(_: &Self::Event) -> bool {
222 false
223 }
224 fn should_close_item_on_event(_: &Self::Event) -> bool {
225 false
226 }
227 fn should_update_tab_on_event(_: &Self::Event) -> bool {
228 false
229 }
230 fn act_as_type(
231 &self,
232 type_id: TypeId,
233 self_handle: &ViewHandle<Self>,
234 _: &AppContext,
235 ) -> Option<AnyViewHandle> {
236 if TypeId::of::<Self>() == type_id {
237 Some(self_handle.into())
238 } else {
239 None
240 }
241 }
242}
243
244pub trait ProjectItem: Item {
245 type Item: project::Item;
246
247 fn for_project_item(
248 project: ModelHandle<Project>,
249 item: ModelHandle<Self::Item>,
250 cx: &mut ViewContext<Self>,
251 ) -> Self;
252}
253
254pub trait FollowableItem: Item {
255 fn for_state_message(
256 pane: ViewHandle<Pane>,
257 project: ModelHandle<Project>,
258 state: &mut Option<proto::view::Variant>,
259 cx: &mut MutableAppContext,
260 ) -> Option<Task<Result<ViewHandle<Self>>>>;
261 fn set_leader_replica_id(&mut self, leader_replica_id: Option<u16>, cx: &mut ViewContext<Self>);
262 fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant>;
263 fn to_update_message(
264 &self,
265 event: &Self::Event,
266 cx: &AppContext,
267 ) -> Option<proto::update_view::Variant>;
268 fn apply_update_message(
269 &mut self,
270 message: proto::update_view::Variant,
271 cx: &mut ViewContext<Self>,
272 ) -> Result<()>;
273 fn should_unfollow_on_event(event: &Self::Event, cx: &AppContext) -> bool;
274}
275
276pub trait FollowableItemHandle: ItemHandle {
277 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext);
278 fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant>;
279 fn to_update_message(
280 &self,
281 event: &dyn Any,
282 cx: &AppContext,
283 ) -> Option<proto::update_view::Variant>;
284 fn apply_update_message(
285 &self,
286 message: proto::update_view::Variant,
287 cx: &mut MutableAppContext,
288 ) -> Result<()>;
289 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool;
290}
291
292impl<T: FollowableItem> FollowableItemHandle for ViewHandle<T> {
293 fn set_leader_replica_id(&self, leader_replica_id: Option<u16>, cx: &mut MutableAppContext) {
294 self.update(cx, |this, cx| {
295 this.set_leader_replica_id(leader_replica_id, cx)
296 })
297 }
298
299 fn to_state_message(&self, cx: &AppContext) -> Option<proto::view::Variant> {
300 self.read(cx).to_state_message(cx)
301 }
302
303 fn to_update_message(
304 &self,
305 event: &dyn Any,
306 cx: &AppContext,
307 ) -> Option<proto::update_view::Variant> {
308 self.read(cx).to_update_message(event.downcast_ref()?, cx)
309 }
310
311 fn apply_update_message(
312 &self,
313 message: proto::update_view::Variant,
314 cx: &mut MutableAppContext,
315 ) -> Result<()> {
316 self.update(cx, |this, cx| this.apply_update_message(message, cx))
317 }
318
319 fn should_unfollow_on_event(&self, event: &dyn Any, cx: &AppContext) -> bool {
320 if let Some(event) = event.downcast_ref() {
321 T::should_unfollow_on_event(event, cx)
322 } else {
323 false
324 }
325 }
326}
327
328pub trait ItemHandle: 'static + fmt::Debug {
329 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox;
330 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
331 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
332 fn boxed_clone(&self) -> Box<dyn ItemHandle>;
333 fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext);
334 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>>;
335 fn added_to_pane(
336 &self,
337 workspace: &mut Workspace,
338 pane: ViewHandle<Pane>,
339 cx: &mut ViewContext<Workspace>,
340 );
341 fn deactivated(&self, cx: &mut MutableAppContext);
342 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext);
343 fn id(&self) -> usize;
344 fn to_any(&self) -> AnyViewHandle;
345 fn is_dirty(&self, cx: &AppContext) -> bool;
346 fn has_conflict(&self, cx: &AppContext) -> bool;
347 fn can_save(&self, cx: &AppContext) -> bool;
348 fn can_save_as(&self, cx: &AppContext) -> bool;
349 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>>;
350 fn save_as(
351 &self,
352 project: ModelHandle<Project>,
353 abs_path: PathBuf,
354 cx: &mut MutableAppContext,
355 ) -> Task<Result<()>>;
356 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle>;
357 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>>;
358}
359
360pub trait WeakItemHandle {
361 fn id(&self) -> usize;
362 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>>;
363}
364
365impl dyn ItemHandle {
366 pub fn downcast<T: View>(&self) -> Option<ViewHandle<T>> {
367 self.to_any().downcast()
368 }
369
370 pub fn act_as<T: View>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
371 self.act_as_type(TypeId::of::<T>(), cx)
372 .and_then(|t| t.downcast())
373 }
374}
375
376impl<T: Item> ItemHandle for ViewHandle<T> {
377 fn tab_content(&self, style: &theme::Tab, cx: &AppContext) -> ElementBox {
378 self.read(cx).tab_content(style, cx)
379 }
380
381 fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
382 self.read(cx).project_path(cx)
383 }
384
385 fn project_entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
386 self.read(cx).project_entry_id(cx)
387 }
388
389 fn boxed_clone(&self) -> Box<dyn ItemHandle> {
390 Box::new(self.clone())
391 }
392
393 fn clone_on_split(&self, cx: &mut MutableAppContext) -> Option<Box<dyn ItemHandle>> {
394 self.update(cx, |item, cx| {
395 cx.add_option_view(|cx| item.clone_on_split(cx))
396 })
397 .map(|handle| Box::new(handle) as Box<dyn ItemHandle>)
398 }
399
400 fn set_nav_history(&self, nav_history: Rc<RefCell<NavHistory>>, cx: &mut MutableAppContext) {
401 self.update(cx, |item, cx| {
402 item.set_nav_history(ItemNavHistory::new(nav_history, &cx.handle()), cx);
403 })
404 }
405
406 fn added_to_pane(
407 &self,
408 workspace: &mut Workspace,
409 pane: ViewHandle<Pane>,
410 cx: &mut ViewContext<Workspace>,
411 ) {
412 if let Some(followed_item) = self.to_followable_item_handle(cx) {
413 if let Some(message) = followed_item.to_state_message(cx) {
414 workspace.update_followers(
415 proto::update_followers::Variant::CreateView(proto::View {
416 id: followed_item.id() as u64,
417 variant: Some(message),
418 leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
419 }),
420 cx,
421 );
422 }
423 }
424
425 let pane = pane.downgrade();
426 cx.subscribe(self, move |workspace, item, event, cx| {
427 let pane = if let Some(pane) = pane.upgrade(cx) {
428 pane
429 } else {
430 log::error!("unexpected item event after pane was dropped");
431 return;
432 };
433
434 if let Some(item) = item.to_followable_item_handle(cx) {
435 if item.should_unfollow_on_event(event, cx) {
436 workspace.unfollow(&pane, cx);
437 }
438 }
439
440 if T::should_close_item_on_event(event) {
441 pane.update(cx, |pane, cx| pane.close_item(item.id(), cx));
442 return;
443 }
444
445 if T::should_activate_item_on_event(event) {
446 pane.update(cx, |pane, cx| {
447 if let Some(ix) = pane.index_for_item(&item) {
448 pane.activate_item(ix, cx);
449 pane.activate(cx);
450 }
451 });
452 }
453
454 if T::should_update_tab_on_event(event) {
455 pane.update(cx, |_, cx| cx.notify());
456 }
457
458 if let Some(message) = item
459 .to_followable_item_handle(cx)
460 .and_then(|i| i.to_update_message(event, cx))
461 {
462 workspace.update_followers(
463 proto::update_followers::Variant::UpdateView(proto::UpdateView {
464 id: item.id() as u64,
465 variant: Some(message),
466 leader_id: workspace.leader_for_pane(&pane).map(|id| id.0),
467 }),
468 cx,
469 );
470 }
471 })
472 .detach();
473 }
474
475 fn deactivated(&self, cx: &mut MutableAppContext) {
476 self.update(cx, |this, cx| this.deactivated(cx));
477 }
478
479 fn navigate(&self, data: Box<dyn Any>, cx: &mut MutableAppContext) {
480 self.update(cx, |this, cx| this.navigate(data, cx));
481 }
482
483 fn save(&self, project: ModelHandle<Project>, cx: &mut MutableAppContext) -> Task<Result<()>> {
484 self.update(cx, |item, cx| item.save(project, cx))
485 }
486
487 fn save_as(
488 &self,
489 project: ModelHandle<Project>,
490 abs_path: PathBuf,
491 cx: &mut MutableAppContext,
492 ) -> Task<anyhow::Result<()>> {
493 self.update(cx, |item, cx| item.save_as(project, abs_path, cx))
494 }
495
496 fn is_dirty(&self, cx: &AppContext) -> bool {
497 self.read(cx).is_dirty(cx)
498 }
499
500 fn has_conflict(&self, cx: &AppContext) -> bool {
501 self.read(cx).has_conflict(cx)
502 }
503
504 fn id(&self) -> usize {
505 self.id()
506 }
507
508 fn to_any(&self) -> AnyViewHandle {
509 self.into()
510 }
511
512 fn can_save(&self, cx: &AppContext) -> bool {
513 self.read(cx).can_save(cx)
514 }
515
516 fn can_save_as(&self, cx: &AppContext) -> bool {
517 self.read(cx).can_save_as(cx)
518 }
519
520 fn act_as_type(&self, type_id: TypeId, cx: &AppContext) -> Option<AnyViewHandle> {
521 self.read(cx).act_as_type(type_id, self, cx)
522 }
523
524 fn to_followable_item_handle(&self, cx: &AppContext) -> Option<Box<dyn FollowableItemHandle>> {
525 if cx.has_global::<FollowableItemBuilders>() {
526 let builders = cx.global::<FollowableItemBuilders>();
527 let item = self.to_any();
528 Some(builders.get(&item.view_type())?.1(item))
529 } else {
530 None
531 }
532 }
533}
534
535impl Into<AnyViewHandle> for Box<dyn ItemHandle> {
536 fn into(self) -> AnyViewHandle {
537 self.to_any()
538 }
539}
540
541impl Clone for Box<dyn ItemHandle> {
542 fn clone(&self) -> Box<dyn ItemHandle> {
543 self.boxed_clone()
544 }
545}
546
547impl<T: Item> WeakItemHandle for WeakViewHandle<T> {
548 fn id(&self) -> usize {
549 self.id()
550 }
551
552 fn upgrade(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
553 self.upgrade(cx).map(|v| Box::new(v) as Box<dyn ItemHandle>)
554 }
555}
556
557#[derive(Clone)]
558pub struct WorkspaceParams {
559 pub project: ModelHandle<Project>,
560 pub client: Arc<Client>,
561 pub fs: Arc<dyn Fs>,
562 pub languages: Arc<LanguageRegistry>,
563 pub user_store: ModelHandle<UserStore>,
564 pub channel_list: ModelHandle<ChannelList>,
565}
566
567impl WorkspaceParams {
568 #[cfg(any(test, feature = "test-support"))]
569 pub fn test(cx: &mut MutableAppContext) -> Self {
570 let settings = Settings::test(cx);
571 cx.set_global(settings);
572
573 let fs = project::FakeFs::new(cx.background().clone());
574 let languages = Arc::new(LanguageRegistry::test());
575 let http_client = client::test::FakeHttpClient::new(|_| async move {
576 Ok(client::http::ServerResponse::new(404))
577 });
578 let client = Client::new(http_client.clone());
579 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
580 let project = Project::local(
581 client.clone(),
582 user_store.clone(),
583 languages.clone(),
584 fs.clone(),
585 cx,
586 );
587 Self {
588 project,
589 channel_list: cx
590 .add_model(|cx| ChannelList::new(user_store.clone(), client.clone(), cx)),
591 client,
592 fs,
593 languages,
594 user_store,
595 }
596 }
597
598 #[cfg(any(test, feature = "test-support"))]
599 pub fn local(app_state: &Arc<AppState>, cx: &mut MutableAppContext) -> Self {
600 Self {
601 project: Project::local(
602 app_state.client.clone(),
603 app_state.user_store.clone(),
604 app_state.languages.clone(),
605 app_state.fs.clone(),
606 cx,
607 ),
608 client: app_state.client.clone(),
609 fs: app_state.fs.clone(),
610 languages: app_state.languages.clone(),
611 user_store: app_state.user_store.clone(),
612 channel_list: app_state.channel_list.clone(),
613 }
614 }
615}
616
617pub struct Workspace {
618 weak_self: WeakViewHandle<Self>,
619 client: Arc<Client>,
620 user_store: ModelHandle<client::UserStore>,
621 remote_entity_subscription: Option<Subscription>,
622 fs: Arc<dyn Fs>,
623 modal: Option<AnyViewHandle>,
624 center: PaneGroup,
625 left_sidebar: Sidebar,
626 right_sidebar: Sidebar,
627 panes: Vec<ViewHandle<Pane>>,
628 active_pane: ViewHandle<Pane>,
629 status_bar: ViewHandle<StatusBar>,
630 project: ModelHandle<Project>,
631 leader_state: LeaderState,
632 follower_states_by_leader: FollowerStatesByLeader,
633 _observe_current_user: Task<()>,
634}
635
636#[derive(Default)]
637struct LeaderState {
638 followers: HashSet<PeerId>,
639}
640
641type FollowerStatesByLeader = HashMap<PeerId, HashMap<ViewHandle<Pane>, FollowerState>>;
642
643#[derive(Default)]
644struct FollowerState {
645 active_view_id: Option<u64>,
646 items_by_leader_view_id: HashMap<u64, FollowerItem>,
647}
648
649#[derive(Debug)]
650enum FollowerItem {
651 Loading(Vec<proto::update_view::Variant>),
652 Loaded(Box<dyn FollowableItemHandle>),
653}
654
655impl Workspace {
656 pub fn new(params: &WorkspaceParams, cx: &mut ViewContext<Self>) -> Self {
657 cx.observe(¶ms.project, |_, project, cx| {
658 if project.read(cx).is_read_only() {
659 cx.blur();
660 }
661 cx.notify()
662 })
663 .detach();
664
665 cx.subscribe(¶ms.project, move |this, project, event, cx| {
666 if let project::Event::RemoteIdChanged(remote_id) = event {
667 this.project_remote_id_changed(*remote_id, cx);
668 }
669 if project.read(cx).is_read_only() {
670 cx.blur();
671 }
672 cx.notify()
673 })
674 .detach();
675
676 let pane = cx.add_view(|_| Pane::new());
677 let pane_id = pane.id();
678 cx.observe(&pane, move |me, _, cx| {
679 let active_entry = me.active_project_path(cx);
680 me.project
681 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
682 })
683 .detach();
684 cx.subscribe(&pane, move |me, _, event, cx| {
685 me.handle_pane_event(pane_id, event, cx)
686 })
687 .detach();
688 cx.focus(&pane);
689
690 let status_bar = cx.add_view(|cx| StatusBar::new(&pane, cx));
691 let mut current_user = params.user_store.read(cx).watch_current_user().clone();
692 let mut connection_status = params.client.status().clone();
693 let _observe_current_user = cx.spawn_weak(|this, mut cx| async move {
694 current_user.recv().await;
695 connection_status.recv().await;
696 let mut stream =
697 Stream::map(current_user, drop).merge(Stream::map(connection_status, drop));
698
699 while stream.recv().await.is_some() {
700 cx.update(|cx| {
701 if let Some(this) = this.upgrade(cx) {
702 this.update(cx, |_, cx| cx.notify());
703 }
704 })
705 }
706 });
707
708 let weak_self = cx.weak_handle();
709
710 cx.emit_global(WorkspaceCreated(weak_self.clone()));
711
712 let mut this = Workspace {
713 modal: None,
714 weak_self,
715 center: PaneGroup::new(pane.clone()),
716 panes: vec![pane.clone()],
717 active_pane: pane.clone(),
718 status_bar,
719 client: params.client.clone(),
720 remote_entity_subscription: None,
721 user_store: params.user_store.clone(),
722 fs: params.fs.clone(),
723 left_sidebar: Sidebar::new(Side::Left),
724 right_sidebar: Sidebar::new(Side::Right),
725 project: params.project.clone(),
726 leader_state: Default::default(),
727 follower_states_by_leader: Default::default(),
728 _observe_current_user,
729 };
730 this.project_remote_id_changed(this.project.read(cx).remote_id(), cx);
731 this
732 }
733
734 pub fn weak_handle(&self) -> WeakViewHandle<Self> {
735 self.weak_self.clone()
736 }
737
738 pub fn left_sidebar_mut(&mut self) -> &mut Sidebar {
739 &mut self.left_sidebar
740 }
741
742 pub fn right_sidebar_mut(&mut self) -> &mut Sidebar {
743 &mut self.right_sidebar
744 }
745
746 pub fn status_bar(&self) -> &ViewHandle<StatusBar> {
747 &self.status_bar
748 }
749
750 pub fn project(&self) -> &ModelHandle<Project> {
751 &self.project
752 }
753
754 pub fn worktrees<'a>(
755 &self,
756 cx: &'a AppContext,
757 ) -> impl 'a + Iterator<Item = ModelHandle<Worktree>> {
758 self.project.read(cx).worktrees(cx)
759 }
760
761 pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
762 paths.iter().all(|path| self.contains_path(&path, cx))
763 }
764
765 pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
766 for worktree in self.worktrees(cx) {
767 let worktree = worktree.read(cx).as_local();
768 if worktree.map_or(false, |w| w.contains_abs_path(path)) {
769 return true;
770 }
771 }
772 false
773 }
774
775 pub fn worktree_scans_complete(&self, cx: &AppContext) -> impl Future<Output = ()> + 'static {
776 let futures = self
777 .worktrees(cx)
778 .filter_map(|worktree| worktree.read(cx).as_local())
779 .map(|worktree| worktree.scan_complete())
780 .collect::<Vec<_>>();
781 async move {
782 for future in futures {
783 future.await;
784 }
785 }
786 }
787
788 pub fn open_paths(
789 &mut self,
790 abs_paths: &[PathBuf],
791 cx: &mut ViewContext<Self>,
792 ) -> Task<Vec<Option<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>>>> {
793 let entries = abs_paths
794 .iter()
795 .cloned()
796 .map(|path| self.project_path_for_path(&path, cx))
797 .collect::<Vec<_>>();
798
799 let fs = self.fs.clone();
800 let tasks = abs_paths
801 .iter()
802 .cloned()
803 .zip(entries.into_iter())
804 .map(|(abs_path, project_path)| {
805 cx.spawn(|this, mut cx| {
806 let fs = fs.clone();
807 async move {
808 let project_path = project_path.await.ok()?;
809 if fs.is_file(&abs_path).await {
810 Some(
811 this.update(&mut cx, |this, cx| this.open_path(project_path, cx))
812 .await,
813 )
814 } else {
815 None
816 }
817 }
818 })
819 })
820 .collect::<Vec<_>>();
821
822 cx.foreground().spawn(async move {
823 let mut items = Vec::new();
824 for task in tasks {
825 items.push(task.await);
826 }
827 items
828 })
829 }
830
831 fn project_path_for_path(
832 &self,
833 abs_path: &Path,
834 cx: &mut ViewContext<Self>,
835 ) -> Task<Result<ProjectPath>> {
836 let entry = self.project().update(cx, |project, cx| {
837 project.find_or_create_local_worktree(abs_path, true, cx)
838 });
839 cx.spawn(|_, cx| async move {
840 let (worktree, path) = entry.await?;
841 Ok(ProjectPath {
842 worktree_id: worktree.read_with(&cx, |t, _| t.id()),
843 path: path.into(),
844 })
845 })
846 }
847
848 // Returns the model that was toggled closed if it was open
849 pub fn toggle_modal<V, F>(
850 &mut self,
851 cx: &mut ViewContext<Self>,
852 add_view: F,
853 ) -> Option<ViewHandle<V>>
854 where
855 V: 'static + View,
856 F: FnOnce(&mut ViewContext<Self>, &mut Self) -> ViewHandle<V>,
857 {
858 cx.notify();
859 // Whatever modal was visible is getting clobbered. If its the same type as V, then return
860 // it. Otherwise, create a new modal and set it as active.
861 let already_open_modal = self.modal.take().and_then(|modal| modal.downcast::<V>());
862 if let Some(already_open_modal) = already_open_modal {
863 cx.focus_self();
864 Some(already_open_modal)
865 } else {
866 let modal = add_view(cx, self);
867 cx.focus(&modal);
868 self.modal = Some(modal.into());
869 None
870 }
871 }
872
873 pub fn modal(&self) -> Option<&AnyViewHandle> {
874 self.modal.as_ref()
875 }
876
877 pub fn dismiss_modal(&mut self, cx: &mut ViewContext<Self>) {
878 if self.modal.take().is_some() {
879 cx.focus(&self.active_pane);
880 cx.notify();
881 }
882 }
883
884 pub fn items<'a>(
885 &'a self,
886 cx: &'a AppContext,
887 ) -> impl 'a + Iterator<Item = &Box<dyn ItemHandle>> {
888 self.panes.iter().flat_map(|pane| pane.read(cx).items())
889 }
890
891 pub fn item_of_type<T: Item>(&self, cx: &AppContext) -> Option<ViewHandle<T>> {
892 self.items_of_type(cx).max_by_key(|item| item.id())
893 }
894
895 pub fn items_of_type<'a, T: Item>(
896 &'a self,
897 cx: &'a AppContext,
898 ) -> impl 'a + Iterator<Item = ViewHandle<T>> {
899 self.panes
900 .iter()
901 .flat_map(|pane| pane.read(cx).items_of_type())
902 }
903
904 pub fn active_item(&self, cx: &AppContext) -> Option<Box<dyn ItemHandle>> {
905 self.active_pane().read(cx).active_item()
906 }
907
908 fn active_project_path(&self, cx: &ViewContext<Self>) -> Option<ProjectPath> {
909 self.active_item(cx).and_then(|item| item.project_path(cx))
910 }
911
912 pub fn save_active_item(&mut self, cx: &mut ViewContext<Self>) -> Task<Result<()>> {
913 let project = self.project.clone();
914 if let Some(item) = self.active_item(cx) {
915 if item.can_save(cx) {
916 if item.has_conflict(cx.as_ref()) {
917 const CONFLICT_MESSAGE: &'static str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
918
919 let mut answer = cx.prompt(
920 PromptLevel::Warning,
921 CONFLICT_MESSAGE,
922 &["Overwrite", "Cancel"],
923 );
924 cx.spawn(|_, mut cx| async move {
925 let answer = answer.recv().await;
926 if answer == Some(0) {
927 cx.update(|cx| item.save(project, cx)).await?;
928 }
929 Ok(())
930 })
931 } else {
932 item.save(project, cx)
933 }
934 } else if item.can_save_as(cx) {
935 let worktree = self.worktrees(cx).next();
936 let start_abs_path = worktree
937 .and_then(|w| w.read(cx).as_local())
938 .map_or(Path::new(""), |w| w.abs_path())
939 .to_path_buf();
940 let mut abs_path = cx.prompt_for_new_path(&start_abs_path);
941 cx.spawn(|_, mut cx| async move {
942 if let Some(abs_path) = abs_path.recv().await.flatten() {
943 cx.update(|cx| item.save_as(project, abs_path, cx)).await?;
944 }
945 Ok(())
946 })
947 } else {
948 Task::ready(Ok(()))
949 }
950 } else {
951 Task::ready(Ok(()))
952 }
953 }
954
955 pub fn toggle_sidebar_item(&mut self, action: &ToggleSidebarItem, cx: &mut ViewContext<Self>) {
956 let sidebar = match action.0.side {
957 Side::Left => &mut self.left_sidebar,
958 Side::Right => &mut self.right_sidebar,
959 };
960 sidebar.toggle_item(action.0.item_index);
961 if let Some(active_item) = sidebar.active_item() {
962 cx.focus(active_item);
963 } else {
964 cx.focus_self();
965 }
966 cx.notify();
967 }
968
969 pub fn toggle_sidebar_item_focus(
970 &mut self,
971 action: &ToggleSidebarItemFocus,
972 cx: &mut ViewContext<Self>,
973 ) {
974 let sidebar = match action.0.side {
975 Side::Left => &mut self.left_sidebar,
976 Side::Right => &mut self.right_sidebar,
977 };
978 sidebar.activate_item(action.0.item_index);
979 if let Some(active_item) = sidebar.active_item() {
980 if active_item.is_focused(cx) {
981 cx.focus_self();
982 } else {
983 cx.focus(active_item);
984 }
985 }
986 cx.notify();
987 }
988
989 pub fn debug_elements(&mut self, _: &DebugElements, cx: &mut ViewContext<Self>) {
990 match to_string_pretty(&cx.debug_elements()) {
991 Ok(json) => {
992 let kib = json.len() as f32 / 1024.;
993 cx.as_mut().write_to_clipboard(ClipboardItem::new(json));
994 log::info!(
995 "copied {:.1} KiB of element debug JSON to the clipboard",
996 kib
997 );
998 }
999 Err(error) => {
1000 log::error!("error debugging elements: {}", error);
1001 }
1002 };
1003 }
1004
1005 fn add_pane(&mut self, cx: &mut ViewContext<Self>) -> ViewHandle<Pane> {
1006 let pane = cx.add_view(|_| Pane::new());
1007 let pane_id = pane.id();
1008 cx.observe(&pane, move |me, _, cx| {
1009 let active_entry = me.active_project_path(cx);
1010 me.project
1011 .update(cx, |project, cx| project.set_active_path(active_entry, cx));
1012 })
1013 .detach();
1014 cx.subscribe(&pane, move |me, _, event, cx| {
1015 me.handle_pane_event(pane_id, event, cx)
1016 })
1017 .detach();
1018 self.panes.push(pane.clone());
1019 self.activate_pane(pane.clone(), cx);
1020 pane
1021 }
1022
1023 pub fn add_item(&mut self, item: Box<dyn ItemHandle>, cx: &mut ViewContext<Self>) {
1024 let pane = self.active_pane().clone();
1025 Pane::add_item(self, pane, item, cx);
1026 }
1027
1028 pub fn open_path(
1029 &mut self,
1030 path: impl Into<ProjectPath>,
1031 cx: &mut ViewContext<Self>,
1032 ) -> Task<Result<Box<dyn ItemHandle>, Arc<anyhow::Error>>> {
1033 let pane = self.active_pane().downgrade();
1034 let task = self.load_path(path.into(), cx);
1035 cx.spawn(|this, mut cx| async move {
1036 let (project_entry_id, build_item) = task.await?;
1037 let pane = pane
1038 .upgrade(&cx)
1039 .ok_or_else(|| anyhow!("pane was closed"))?;
1040 this.update(&mut cx, |this, cx| {
1041 Ok(Pane::open_item(
1042 this,
1043 pane,
1044 project_entry_id,
1045 cx,
1046 build_item,
1047 ))
1048 })
1049 })
1050 }
1051
1052 pub(crate) fn load_path(
1053 &mut self,
1054 path: ProjectPath,
1055 cx: &mut ViewContext<Self>,
1056 ) -> Task<
1057 Result<(
1058 ProjectEntryId,
1059 impl 'static + FnOnce(&mut MutableAppContext) -> Box<dyn ItemHandle>,
1060 )>,
1061 > {
1062 let project = self.project().clone();
1063 let project_item = project.update(cx, |project, cx| project.open_path(path, cx));
1064 let window_id = cx.window_id();
1065 cx.as_mut().spawn(|mut cx| async move {
1066 let (project_entry_id, project_item) = project_item.await?;
1067 let build_item = cx.update(|cx| {
1068 cx.default_global::<ProjectItemBuilders>()
1069 .get(&project_item.model_type())
1070 .ok_or_else(|| anyhow!("no item builder for project item"))
1071 .cloned()
1072 })?;
1073 let build_item =
1074 move |cx: &mut MutableAppContext| build_item(window_id, project, project_item, cx);
1075 Ok((project_entry_id, build_item))
1076 })
1077 }
1078
1079 pub fn open_project_item<T>(
1080 &mut self,
1081 project_item: ModelHandle<T::Item>,
1082 cx: &mut ViewContext<Self>,
1083 ) -> ViewHandle<T>
1084 where
1085 T: ProjectItem,
1086 {
1087 use project::Item as _;
1088
1089 if let Some(item) = project_item
1090 .read(cx)
1091 .entry_id(cx)
1092 .and_then(|entry_id| self.active_pane().read(cx).item_for_entry(entry_id, cx))
1093 .and_then(|item| item.downcast())
1094 {
1095 self.activate_item(&item, cx);
1096 return item;
1097 }
1098
1099 let item = cx.add_view(|cx| T::for_project_item(self.project().clone(), project_item, cx));
1100 self.add_item(Box::new(item.clone()), cx);
1101 item
1102 }
1103
1104 pub fn activate_item(&mut self, item: &dyn ItemHandle, cx: &mut ViewContext<Self>) -> bool {
1105 let result = self.panes.iter().find_map(|pane| {
1106 if let Some(ix) = pane.read(cx).index_for_item(item) {
1107 Some((pane.clone(), ix))
1108 } else {
1109 None
1110 }
1111 });
1112 if let Some((pane, ix)) = result {
1113 self.activate_pane(pane.clone(), cx);
1114 pane.update(cx, |pane, cx| pane.activate_item(ix, cx));
1115 true
1116 } else {
1117 false
1118 }
1119 }
1120
1121 pub fn activate_next_pane(&mut self, cx: &mut ViewContext<Self>) {
1122 let ix = self
1123 .panes
1124 .iter()
1125 .position(|pane| pane == &self.active_pane)
1126 .unwrap();
1127 let next_ix = (ix + 1) % self.panes.len();
1128 self.activate_pane(self.panes[next_ix].clone(), cx);
1129 }
1130
1131 fn activate_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1132 if self.active_pane != pane {
1133 self.active_pane = pane.clone();
1134 self.status_bar.update(cx, |status_bar, cx| {
1135 status_bar.set_active_pane(&self.active_pane, cx);
1136 });
1137 cx.focus(&self.active_pane);
1138 cx.notify();
1139 }
1140
1141 self.update_followers(
1142 proto::update_followers::Variant::UpdateActiveView(proto::UpdateActiveView {
1143 id: self.active_item(cx).map(|item| item.id() as u64),
1144 leader_id: self.leader_for_pane(&pane).map(|id| id.0),
1145 }),
1146 cx,
1147 );
1148 }
1149
1150 fn handle_pane_event(
1151 &mut self,
1152 pane_id: usize,
1153 event: &pane::Event,
1154 cx: &mut ViewContext<Self>,
1155 ) {
1156 if let Some(pane) = self.pane(pane_id) {
1157 match event {
1158 pane::Event::Split(direction) => {
1159 self.split_pane(pane, *direction, cx);
1160 }
1161 pane::Event::Remove => {
1162 self.remove_pane(pane, cx);
1163 }
1164 pane::Event::Activate => {
1165 self.activate_pane(pane, cx);
1166 }
1167 }
1168 } else {
1169 error!("pane {} not found", pane_id);
1170 }
1171 }
1172
1173 pub fn split_pane(
1174 &mut self,
1175 pane: ViewHandle<Pane>,
1176 direction: SplitDirection,
1177 cx: &mut ViewContext<Self>,
1178 ) -> ViewHandle<Pane> {
1179 let new_pane = self.add_pane(cx);
1180 self.activate_pane(new_pane.clone(), cx);
1181 if let Some(item) = pane.read(cx).active_item() {
1182 if let Some(clone) = item.clone_on_split(cx.as_mut()) {
1183 Pane::add_item(self, new_pane.clone(), clone, cx);
1184 }
1185 }
1186 self.center.split(&pane, &new_pane, direction).unwrap();
1187 cx.notify();
1188 new_pane
1189 }
1190
1191 fn remove_pane(&mut self, pane: ViewHandle<Pane>, cx: &mut ViewContext<Self>) {
1192 if self.center.remove(&pane).unwrap() {
1193 self.panes.retain(|p| p != &pane);
1194 self.activate_pane(self.panes.last().unwrap().clone(), cx);
1195 self.unfollow(&pane, cx);
1196 cx.notify();
1197 }
1198 }
1199
1200 pub fn panes(&self) -> &[ViewHandle<Pane>] {
1201 &self.panes
1202 }
1203
1204 fn pane(&self, pane_id: usize) -> Option<ViewHandle<Pane>> {
1205 self.panes.iter().find(|pane| pane.id() == pane_id).cloned()
1206 }
1207
1208 pub fn active_pane(&self) -> &ViewHandle<Pane> {
1209 &self.active_pane
1210 }
1211
1212 fn toggle_share(&mut self, _: &ToggleShare, cx: &mut ViewContext<Self>) {
1213 self.project.update(cx, |project, cx| {
1214 if project.is_local() {
1215 if project.is_shared() {
1216 project.unshare(cx).detach();
1217 } else {
1218 project.share(cx).detach();
1219 }
1220 }
1221 });
1222 }
1223
1224 fn project_remote_id_changed(&mut self, remote_id: Option<u64>, cx: &mut ViewContext<Self>) {
1225 if let Some(remote_id) = remote_id {
1226 self.remote_entity_subscription =
1227 Some(self.client.add_view_for_remote_entity(remote_id, cx));
1228 } else {
1229 self.remote_entity_subscription.take();
1230 }
1231 }
1232
1233 pub fn toggle_follow(
1234 &mut self,
1235 ToggleFollow(leader_id): &ToggleFollow,
1236 cx: &mut ViewContext<Self>,
1237 ) -> Option<Task<Result<()>>> {
1238 let leader_id = *leader_id;
1239 let pane = self.active_pane().clone();
1240
1241 if let Some(prev_leader_id) = self.unfollow(&pane, cx) {
1242 if leader_id == prev_leader_id {
1243 cx.notify();
1244 return None;
1245 }
1246 }
1247
1248 self.follower_states_by_leader
1249 .entry(leader_id)
1250 .or_default()
1251 .insert(pane.clone(), Default::default());
1252
1253 let project_id = self.project.read(cx).remote_id()?;
1254 let request = self.client.request(proto::Follow {
1255 project_id,
1256 leader_id: leader_id.0,
1257 });
1258 Some(cx.spawn_weak(|this, mut cx| async move {
1259 let response = request.await?;
1260 if let Some(this) = this.upgrade(&cx) {
1261 this.update(&mut cx, |this, _| {
1262 let state = this
1263 .follower_states_by_leader
1264 .get_mut(&leader_id)
1265 .and_then(|states_by_pane| states_by_pane.get_mut(&pane))
1266 .ok_or_else(|| anyhow!("following interrupted"))?;
1267 state.active_view_id = response.active_view_id;
1268 Ok::<_, anyhow::Error>(())
1269 })?;
1270 Self::add_views_from_leader(this, leader_id, vec![pane], response.views, &mut cx)
1271 .await?;
1272 }
1273 Ok(())
1274 }))
1275 }
1276
1277 pub fn unfollow(
1278 &mut self,
1279 pane: &ViewHandle<Pane>,
1280 cx: &mut ViewContext<Self>,
1281 ) -> Option<PeerId> {
1282 for (leader_id, states_by_pane) in &mut self.follower_states_by_leader {
1283 let leader_id = *leader_id;
1284 if let Some(state) = states_by_pane.remove(&pane) {
1285 for (_, item) in state.items_by_leader_view_id {
1286 if let FollowerItem::Loaded(item) = item {
1287 item.set_leader_replica_id(None, cx);
1288 }
1289 }
1290
1291 if states_by_pane.is_empty() {
1292 self.follower_states_by_leader.remove(&leader_id);
1293 if let Some(project_id) = self.project.read(cx).remote_id() {
1294 self.client
1295 .send(proto::Unfollow {
1296 project_id,
1297 leader_id: leader_id.0,
1298 })
1299 .log_err();
1300 }
1301 }
1302
1303 cx.notify();
1304 return Some(leader_id);
1305 }
1306 }
1307 None
1308 }
1309
1310 fn render_connection_status(&self, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1311 let theme = &cx.global::<Settings>().theme;
1312 match &*self.client.status().borrow() {
1313 client::Status::ConnectionError
1314 | client::Status::ConnectionLost
1315 | client::Status::Reauthenticating
1316 | client::Status::Reconnecting { .. }
1317 | client::Status::ReconnectionError { .. } => Some(
1318 Container::new(
1319 Align::new(
1320 ConstrainedBox::new(
1321 Svg::new("icons/offline-14.svg")
1322 .with_color(theme.workspace.titlebar.offline_icon.color)
1323 .boxed(),
1324 )
1325 .with_width(theme.workspace.titlebar.offline_icon.width)
1326 .boxed(),
1327 )
1328 .boxed(),
1329 )
1330 .with_style(theme.workspace.titlebar.offline_icon.container)
1331 .boxed(),
1332 ),
1333 client::Status::UpgradeRequired => Some(
1334 Label::new(
1335 "Please update Zed to collaborate".to_string(),
1336 theme.workspace.titlebar.outdated_warning.text.clone(),
1337 )
1338 .contained()
1339 .with_style(theme.workspace.titlebar.outdated_warning.container)
1340 .aligned()
1341 .boxed(),
1342 ),
1343 _ => None,
1344 }
1345 }
1346
1347 fn render_titlebar(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> ElementBox {
1348 ConstrainedBox::new(
1349 Container::new(
1350 Stack::new()
1351 .with_child(
1352 Align::new(
1353 Label::new("zed".into(), theme.workspace.titlebar.title.clone())
1354 .boxed(),
1355 )
1356 .boxed(),
1357 )
1358 .with_child(
1359 Align::new(
1360 Flex::row()
1361 .with_children(self.render_share_icon(theme, cx))
1362 .with_children(self.render_collaborators(theme, cx))
1363 .with_child(self.render_current_user(
1364 self.user_store.read(cx).current_user().as_ref(),
1365 self.project.read(cx).replica_id(),
1366 theme,
1367 cx,
1368 ))
1369 .with_children(self.render_connection_status(cx))
1370 .boxed(),
1371 )
1372 .right()
1373 .boxed(),
1374 )
1375 .boxed(),
1376 )
1377 .with_style(theme.workspace.titlebar.container)
1378 .boxed(),
1379 )
1380 .with_height(theme.workspace.titlebar.height)
1381 .named("titlebar")
1382 }
1383
1384 fn render_collaborators(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Vec<ElementBox> {
1385 let mut collaborators = self
1386 .project
1387 .read(cx)
1388 .collaborators()
1389 .values()
1390 .cloned()
1391 .collect::<Vec<_>>();
1392 collaborators.sort_unstable_by_key(|collaborator| collaborator.replica_id);
1393 collaborators
1394 .into_iter()
1395 .filter_map(|collaborator| {
1396 Some(self.render_avatar(
1397 collaborator.user.avatar.clone()?,
1398 collaborator.replica_id,
1399 Some(collaborator.peer_id),
1400 theme,
1401 cx,
1402 ))
1403 })
1404 .collect()
1405 }
1406
1407 fn render_current_user(
1408 &self,
1409 user: Option<&Arc<User>>,
1410 replica_id: ReplicaId,
1411 theme: &Theme,
1412 cx: &mut RenderContext<Self>,
1413 ) -> ElementBox {
1414 if let Some(avatar) = user.and_then(|user| user.avatar.clone()) {
1415 self.render_avatar(avatar, replica_id, None, theme, cx)
1416 } else {
1417 MouseEventHandler::new::<Authenticate, _, _>(0, cx, |state, _| {
1418 let style = if state.hovered {
1419 &theme.workspace.titlebar.hovered_sign_in_prompt
1420 } else {
1421 &theme.workspace.titlebar.sign_in_prompt
1422 };
1423 Label::new("Sign in".to_string(), style.text.clone())
1424 .contained()
1425 .with_style(style.container)
1426 .boxed()
1427 })
1428 .on_click(|cx| cx.dispatch_action(Authenticate))
1429 .with_cursor_style(CursorStyle::PointingHand)
1430 .aligned()
1431 .boxed()
1432 }
1433 }
1434
1435 fn render_avatar(
1436 &self,
1437 avatar: Arc<ImageData>,
1438 replica_id: ReplicaId,
1439 peer_id: Option<PeerId>,
1440 theme: &Theme,
1441 cx: &mut RenderContext<Self>,
1442 ) -> ElementBox {
1443 let replica_color = theme.editor.replica_selection_style(replica_id).cursor;
1444 let is_followed = peer_id.map_or(false, |peer_id| {
1445 self.follower_states_by_leader.contains_key(&peer_id)
1446 });
1447 let mut avatar_style = theme.workspace.titlebar.avatar;
1448 if is_followed {
1449 avatar_style.border = Border::all(1.0, replica_color);
1450 }
1451 let content = Stack::new()
1452 .with_child(
1453 Image::new(avatar)
1454 .with_style(avatar_style)
1455 .constrained()
1456 .with_width(theme.workspace.titlebar.avatar_width)
1457 .aligned()
1458 .boxed(),
1459 )
1460 .with_child(
1461 AvatarRibbon::new(replica_color)
1462 .constrained()
1463 .with_width(theme.workspace.titlebar.avatar_ribbon.width)
1464 .with_height(theme.workspace.titlebar.avatar_ribbon.height)
1465 .aligned()
1466 .bottom()
1467 .boxed(),
1468 )
1469 .constrained()
1470 .with_width(theme.workspace.right_sidebar.width)
1471 .boxed();
1472
1473 if let Some(peer_id) = peer_id {
1474 MouseEventHandler::new::<ToggleFollow, _, _>(replica_id.into(), cx, move |_, _| content)
1475 .with_cursor_style(CursorStyle::PointingHand)
1476 .on_click(move |cx| cx.dispatch_action(ToggleFollow(peer_id)))
1477 .boxed()
1478 } else {
1479 content
1480 }
1481 }
1482
1483 fn render_share_icon(&self, theme: &Theme, cx: &mut RenderContext<Self>) -> Option<ElementBox> {
1484 if self.project().read(cx).is_local() && self.client.user_id().is_some() {
1485 let color = if self.project().read(cx).is_shared() {
1486 theme.workspace.titlebar.share_icon_active_color
1487 } else {
1488 theme.workspace.titlebar.share_icon_color
1489 };
1490 Some(
1491 MouseEventHandler::new::<ToggleShare, _, _>(0, cx, |_, _| {
1492 Align::new(
1493 Svg::new("icons/broadcast-24.svg")
1494 .with_color(color)
1495 .constrained()
1496 .with_width(24.)
1497 .boxed(),
1498 )
1499 .boxed()
1500 })
1501 .with_cursor_style(CursorStyle::PointingHand)
1502 .on_click(|cx| cx.dispatch_action(ToggleShare))
1503 .boxed(),
1504 )
1505 } else {
1506 None
1507 }
1508 }
1509
1510 fn render_disconnected_overlay(&self, cx: &AppContext) -> Option<ElementBox> {
1511 if self.project.read(cx).is_read_only() {
1512 let theme = &cx.global::<Settings>().theme;
1513 Some(
1514 EventHandler::new(
1515 Label::new(
1516 "Your connection to the remote project has been lost.".to_string(),
1517 theme.workspace.disconnected_overlay.text.clone(),
1518 )
1519 .aligned()
1520 .contained()
1521 .with_style(theme.workspace.disconnected_overlay.container)
1522 .boxed(),
1523 )
1524 .capture(|_, _, _| true)
1525 .boxed(),
1526 )
1527 } else {
1528 None
1529 }
1530 }
1531
1532 // RPC handlers
1533
1534 async fn handle_follow(
1535 this: ViewHandle<Self>,
1536 envelope: TypedEnvelope<proto::Follow>,
1537 _: Arc<Client>,
1538 mut cx: AsyncAppContext,
1539 ) -> Result<proto::FollowResponse> {
1540 this.update(&mut cx, |this, cx| {
1541 this.leader_state
1542 .followers
1543 .insert(envelope.original_sender_id()?);
1544
1545 let active_view_id = this
1546 .active_item(cx)
1547 .and_then(|i| i.to_followable_item_handle(cx))
1548 .map(|i| i.id() as u64);
1549 Ok(proto::FollowResponse {
1550 active_view_id,
1551 views: this
1552 .panes()
1553 .iter()
1554 .flat_map(|pane| {
1555 let leader_id = this.leader_for_pane(pane).map(|id| id.0);
1556 pane.read(cx).items().filter_map({
1557 let cx = &cx;
1558 move |item| {
1559 let id = item.id() as u64;
1560 let item = item.to_followable_item_handle(cx)?;
1561 let variant = item.to_state_message(cx)?;
1562 Some(proto::View {
1563 id,
1564 leader_id,
1565 variant: Some(variant),
1566 })
1567 }
1568 })
1569 })
1570 .collect(),
1571 })
1572 })
1573 }
1574
1575 async fn handle_unfollow(
1576 this: ViewHandle<Self>,
1577 envelope: TypedEnvelope<proto::Unfollow>,
1578 _: Arc<Client>,
1579 mut cx: AsyncAppContext,
1580 ) -> Result<()> {
1581 this.update(&mut cx, |this, _| {
1582 this.leader_state
1583 .followers
1584 .remove(&envelope.original_sender_id()?);
1585 Ok(())
1586 })
1587 }
1588
1589 async fn handle_update_followers(
1590 this: ViewHandle<Self>,
1591 envelope: TypedEnvelope<proto::UpdateFollowers>,
1592 _: Arc<Client>,
1593 mut cx: AsyncAppContext,
1594 ) -> Result<()> {
1595 let leader_id = envelope.original_sender_id()?;
1596 match envelope
1597 .payload
1598 .variant
1599 .ok_or_else(|| anyhow!("invalid update"))?
1600 {
1601 proto::update_followers::Variant::UpdateActiveView(update_active_view) => {
1602 this.update(&mut cx, |this, cx| {
1603 this.update_leader_state(leader_id, cx, |state, _| {
1604 state.active_view_id = update_active_view.id;
1605 });
1606 Ok::<_, anyhow::Error>(())
1607 })
1608 }
1609 proto::update_followers::Variant::UpdateView(update_view) => {
1610 this.update(&mut cx, |this, cx| {
1611 let variant = update_view
1612 .variant
1613 .ok_or_else(|| anyhow!("missing update view variant"))?;
1614 this.update_leader_state(leader_id, cx, |state, cx| {
1615 let variant = variant.clone();
1616 match state
1617 .items_by_leader_view_id
1618 .entry(update_view.id)
1619 .or_insert(FollowerItem::Loading(Vec::new()))
1620 {
1621 FollowerItem::Loaded(item) => {
1622 item.apply_update_message(variant, cx).log_err();
1623 }
1624 FollowerItem::Loading(updates) => updates.push(variant),
1625 }
1626 });
1627 Ok(())
1628 })
1629 }
1630 proto::update_followers::Variant::CreateView(view) => {
1631 let panes = this.read_with(&cx, |this, _| {
1632 this.follower_states_by_leader
1633 .get(&leader_id)
1634 .into_iter()
1635 .flat_map(|states_by_pane| states_by_pane.keys())
1636 .cloned()
1637 .collect()
1638 });
1639 Self::add_views_from_leader(this.clone(), leader_id, panes, vec![view], &mut cx)
1640 .await?;
1641 Ok(())
1642 }
1643 }
1644 .log_err();
1645
1646 Ok(())
1647 }
1648
1649 async fn add_views_from_leader(
1650 this: ViewHandle<Self>,
1651 leader_id: PeerId,
1652 panes: Vec<ViewHandle<Pane>>,
1653 views: Vec<proto::View>,
1654 cx: &mut AsyncAppContext,
1655 ) -> Result<()> {
1656 let project = this.read_with(cx, |this, _| this.project.clone());
1657 let replica_id = project
1658 .read_with(cx, |project, _| {
1659 project
1660 .collaborators()
1661 .get(&leader_id)
1662 .map(|c| c.replica_id)
1663 })
1664 .ok_or_else(|| anyhow!("no such collaborator {}", leader_id))?;
1665
1666 let item_builders = cx.update(|cx| {
1667 cx.default_global::<FollowableItemBuilders>()
1668 .values()
1669 .map(|b| b.0)
1670 .collect::<Vec<_>>()
1671 .clone()
1672 });
1673
1674 let mut item_tasks_by_pane = HashMap::default();
1675 for pane in panes {
1676 let mut item_tasks = Vec::new();
1677 let mut leader_view_ids = Vec::new();
1678 for view in &views {
1679 let mut variant = view.variant.clone();
1680 if variant.is_none() {
1681 Err(anyhow!("missing variant"))?;
1682 }
1683 for build_item in &item_builders {
1684 let task =
1685 cx.update(|cx| build_item(pane.clone(), project.clone(), &mut variant, cx));
1686 if let Some(task) = task {
1687 item_tasks.push(task);
1688 leader_view_ids.push(view.id);
1689 break;
1690 } else {
1691 assert!(variant.is_some());
1692 }
1693 }
1694 }
1695
1696 item_tasks_by_pane.insert(pane, (item_tasks, leader_view_ids));
1697 }
1698
1699 for (pane, (item_tasks, leader_view_ids)) in item_tasks_by_pane {
1700 let items = futures::future::try_join_all(item_tasks).await?;
1701 this.update(cx, |this, cx| {
1702 let state = this
1703 .follower_states_by_leader
1704 .get_mut(&leader_id)?
1705 .get_mut(&pane)?;
1706
1707 for (id, item) in leader_view_ids.into_iter().zip(items) {
1708 item.set_leader_replica_id(Some(replica_id), cx);
1709 match state.items_by_leader_view_id.entry(id) {
1710 hash_map::Entry::Occupied(e) => {
1711 let e = e.into_mut();
1712 if let FollowerItem::Loading(updates) = e {
1713 for update in updates.drain(..) {
1714 item.apply_update_message(update, cx)
1715 .context("failed to apply view update")
1716 .log_err();
1717 }
1718 }
1719 *e = FollowerItem::Loaded(item);
1720 }
1721 hash_map::Entry::Vacant(e) => {
1722 e.insert(FollowerItem::Loaded(item));
1723 }
1724 }
1725 }
1726
1727 Some(())
1728 });
1729 }
1730 this.update(cx, |this, cx| this.leader_updated(leader_id, cx));
1731
1732 Ok(())
1733 }
1734
1735 fn update_followers(
1736 &self,
1737 update: proto::update_followers::Variant,
1738 cx: &AppContext,
1739 ) -> Option<()> {
1740 let project_id = self.project.read(cx).remote_id()?;
1741 if !self.leader_state.followers.is_empty() {
1742 self.client
1743 .send(proto::UpdateFollowers {
1744 project_id,
1745 follower_ids: self.leader_state.followers.iter().map(|f| f.0).collect(),
1746 variant: Some(update),
1747 })
1748 .log_err();
1749 }
1750 None
1751 }
1752
1753 pub fn leader_for_pane(&self, pane: &ViewHandle<Pane>) -> Option<PeerId> {
1754 self.follower_states_by_leader
1755 .iter()
1756 .find_map(|(leader_id, state)| {
1757 if state.contains_key(pane) {
1758 Some(*leader_id)
1759 } else {
1760 None
1761 }
1762 })
1763 }
1764
1765 fn update_leader_state(
1766 &mut self,
1767 leader_id: PeerId,
1768 cx: &mut ViewContext<Self>,
1769 mut update_fn: impl FnMut(&mut FollowerState, &mut ViewContext<Self>),
1770 ) {
1771 for (_, state) in self
1772 .follower_states_by_leader
1773 .get_mut(&leader_id)
1774 .into_iter()
1775 .flatten()
1776 {
1777 update_fn(state, cx);
1778 }
1779 self.leader_updated(leader_id, cx);
1780 }
1781
1782 fn leader_updated(&mut self, leader_id: PeerId, cx: &mut ViewContext<Self>) -> Option<()> {
1783 let mut items_to_add = Vec::new();
1784 for (pane, state) in self.follower_states_by_leader.get(&leader_id)? {
1785 if let Some(active_item) = state
1786 .active_view_id
1787 .and_then(|id| state.items_by_leader_view_id.get(&id))
1788 {
1789 if let FollowerItem::Loaded(item) = active_item {
1790 items_to_add.push((pane.clone(), item.boxed_clone()));
1791 }
1792 }
1793 }
1794
1795 for (pane, item) in items_to_add {
1796 Pane::add_item(self, pane.clone(), item.boxed_clone(), cx);
1797 cx.notify();
1798 }
1799 None
1800 }
1801}
1802
1803impl Entity for Workspace {
1804 type Event = ();
1805}
1806
1807impl View for Workspace {
1808 fn ui_name() -> &'static str {
1809 "Workspace"
1810 }
1811
1812 fn render(&mut self, cx: &mut RenderContext<Self>) -> ElementBox {
1813 let theme = cx.global::<Settings>().theme.clone();
1814 Stack::new()
1815 .with_child(
1816 Flex::column()
1817 .with_child(self.render_titlebar(&theme, cx))
1818 .with_child(
1819 Stack::new()
1820 .with_child({
1821 let mut content = Flex::row();
1822 content.add_child(self.left_sidebar.render(&theme, cx));
1823 if let Some(element) =
1824 self.left_sidebar.render_active_item(&theme, cx)
1825 {
1826 content.add_child(Flexible::new(0.8, false, element).boxed());
1827 }
1828 content.add_child(
1829 Flex::column()
1830 .with_child(
1831 Flexible::new(
1832 1.,
1833 true,
1834 self.center.render(
1835 &theme,
1836 &self.follower_states_by_leader,
1837 self.project.read(cx).collaborators(),
1838 ),
1839 )
1840 .boxed(),
1841 )
1842 .with_child(ChildView::new(&self.status_bar).boxed())
1843 .flexible(1., true)
1844 .boxed(),
1845 );
1846 if let Some(element) =
1847 self.right_sidebar.render_active_item(&theme, cx)
1848 {
1849 content.add_child(Flexible::new(0.8, false, element).boxed());
1850 }
1851 content.add_child(self.right_sidebar.render(&theme, cx));
1852 content.boxed()
1853 })
1854 .with_children(self.modal.as_ref().map(|m| ChildView::new(m).boxed()))
1855 .flexible(1.0, true)
1856 .boxed(),
1857 )
1858 .contained()
1859 .with_background_color(theme.workspace.background)
1860 .boxed(),
1861 )
1862 .with_children(self.render_disconnected_overlay(cx))
1863 .named("workspace")
1864 }
1865
1866 fn on_focus(&mut self, cx: &mut ViewContext<Self>) {
1867 cx.focus(&self.active_pane);
1868 }
1869}
1870
1871pub trait WorkspaceHandle {
1872 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath>;
1873}
1874
1875impl WorkspaceHandle for ViewHandle<Workspace> {
1876 fn file_project_paths(&self, cx: &AppContext) -> Vec<ProjectPath> {
1877 self.read(cx)
1878 .worktrees(cx)
1879 .flat_map(|worktree| {
1880 let worktree_id = worktree.read(cx).id();
1881 worktree.read(cx).files(true, 0).map(move |f| ProjectPath {
1882 worktree_id,
1883 path: f.path.clone(),
1884 })
1885 })
1886 .collect::<Vec<_>>()
1887 }
1888}
1889
1890pub struct AvatarRibbon {
1891 color: Color,
1892}
1893
1894impl AvatarRibbon {
1895 pub fn new(color: Color) -> AvatarRibbon {
1896 AvatarRibbon { color }
1897 }
1898}
1899
1900impl Element for AvatarRibbon {
1901 type LayoutState = ();
1902
1903 type PaintState = ();
1904
1905 fn layout(
1906 &mut self,
1907 constraint: gpui::SizeConstraint,
1908 _: &mut gpui::LayoutContext,
1909 ) -> (gpui::geometry::vector::Vector2F, Self::LayoutState) {
1910 (constraint.max, ())
1911 }
1912
1913 fn paint(
1914 &mut self,
1915 bounds: gpui::geometry::rect::RectF,
1916 _: gpui::geometry::rect::RectF,
1917 _: &mut Self::LayoutState,
1918 cx: &mut gpui::PaintContext,
1919 ) -> Self::PaintState {
1920 let mut path = PathBuilder::new();
1921 path.reset(bounds.lower_left());
1922 path.curve_to(
1923 bounds.origin() + vec2f(bounds.height(), 0.),
1924 bounds.origin(),
1925 );
1926 path.line_to(bounds.upper_right() - vec2f(bounds.height(), 0.));
1927 path.curve_to(bounds.lower_right(), bounds.upper_right());
1928 path.line_to(bounds.lower_left());
1929 cx.scene.push_path(path.build(self.color, None));
1930 }
1931
1932 fn dispatch_event(
1933 &mut self,
1934 _: &gpui::Event,
1935 _: gpui::geometry::rect::RectF,
1936 _: &mut Self::LayoutState,
1937 _: &mut Self::PaintState,
1938 _: &mut gpui::EventContext,
1939 ) -> bool {
1940 false
1941 }
1942
1943 fn debug(
1944 &self,
1945 bounds: gpui::geometry::rect::RectF,
1946 _: &Self::LayoutState,
1947 _: &Self::PaintState,
1948 _: &gpui::DebugContext,
1949 ) -> gpui::json::Value {
1950 json::json!({
1951 "type": "AvatarRibbon",
1952 "bounds": bounds.to_json(),
1953 "color": self.color.to_json(),
1954 })
1955 }
1956}
1957
1958impl std::fmt::Debug for OpenParams {
1959 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1960 f.debug_struct("OpenParams")
1961 .field("paths", &self.paths)
1962 .finish()
1963 }
1964}
1965
1966fn open(action: &Open, cx: &mut MutableAppContext) {
1967 let app_state = action.0.clone();
1968 let mut paths = cx.prompt_for_paths(PathPromptOptions {
1969 files: true,
1970 directories: true,
1971 multiple: true,
1972 });
1973 cx.spawn(|mut cx| async move {
1974 if let Some(paths) = paths.recv().await.flatten() {
1975 cx.update(|cx| cx.dispatch_global_action(OpenPaths(OpenParams { paths, app_state })));
1976 }
1977 })
1978 .detach();
1979}
1980
1981pub struct WorkspaceCreated(WeakViewHandle<Workspace>);
1982
1983pub fn open_paths(
1984 abs_paths: &[PathBuf],
1985 app_state: &Arc<AppState>,
1986 cx: &mut MutableAppContext,
1987) -> Task<ViewHandle<Workspace>> {
1988 log::info!("open paths {:?}", abs_paths);
1989
1990 // Open paths in existing workspace if possible
1991 let mut existing = None;
1992 for window_id in cx.window_ids().collect::<Vec<_>>() {
1993 if let Some(workspace_handle) = cx.root_view::<Workspace>(window_id) {
1994 if workspace_handle.update(cx, |workspace, cx| {
1995 if workspace.contains_paths(abs_paths, cx.as_ref()) {
1996 cx.activate_window(window_id);
1997 existing = Some(workspace_handle.clone());
1998 true
1999 } else {
2000 false
2001 }
2002 }) {
2003 break;
2004 }
2005 }
2006 }
2007
2008 let workspace = existing.unwrap_or_else(|| {
2009 cx.add_window((app_state.build_window_options)(), |cx| {
2010 let project = Project::local(
2011 app_state.client.clone(),
2012 app_state.user_store.clone(),
2013 app_state.languages.clone(),
2014 app_state.fs.clone(),
2015 cx,
2016 );
2017 (app_state.build_workspace)(project, &app_state, cx)
2018 })
2019 .1
2020 });
2021
2022 let task = workspace.update(cx, |workspace, cx| workspace.open_paths(abs_paths, cx));
2023 cx.spawn(|_| async move {
2024 task.await;
2025 workspace
2026 })
2027}
2028
2029pub fn join_project(
2030 project_id: u64,
2031 app_state: &Arc<AppState>,
2032 cx: &mut MutableAppContext,
2033) -> Task<Result<ViewHandle<Workspace>>> {
2034 for window_id in cx.window_ids().collect::<Vec<_>>() {
2035 if let Some(workspace) = cx.root_view::<Workspace>(window_id) {
2036 if workspace.read(cx).project().read(cx).remote_id() == Some(project_id) {
2037 return Task::ready(Ok(workspace));
2038 }
2039 }
2040 }
2041
2042 let app_state = app_state.clone();
2043 cx.spawn(|mut cx| async move {
2044 let project = Project::remote(
2045 project_id,
2046 app_state.client.clone(),
2047 app_state.user_store.clone(),
2048 app_state.languages.clone(),
2049 app_state.fs.clone(),
2050 &mut cx,
2051 )
2052 .await?;
2053 Ok(cx.update(|cx| {
2054 cx.add_window((app_state.build_window_options)(), |cx| {
2055 (app_state.build_workspace)(project, &app_state, cx)
2056 })
2057 .1
2058 }))
2059 })
2060}
2061
2062fn open_new(app_state: &Arc<AppState>, cx: &mut MutableAppContext) {
2063 let (window_id, workspace) = cx.add_window((app_state.build_window_options)(), |cx| {
2064 let project = Project::local(
2065 app_state.client.clone(),
2066 app_state.user_store.clone(),
2067 app_state.languages.clone(),
2068 app_state.fs.clone(),
2069 cx,
2070 );
2071 (app_state.build_workspace)(project, &app_state, cx)
2072 });
2073 cx.dispatch_action(window_id, vec![workspace.id()], &OpenNew(app_state.clone()));
2074}