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