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