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